1、【后端】扩展Application类增加新的Js类的扩展类Jssdk
<?php
namespace common\helpers\wx;
use yii\helpers\ArrayHelper;
/**
* Created by PhpStorm.
* User: nodelog
* Date: 2018/9/23
* Time: 0:55
*/
class Application extends \abei2017\wx\Application
{
public function init(){
parent::init();
$this->classMap = ArrayHelper::merge($this->classMap, [
'mp.jssdk'=>'common\helpers\wx\mp\Jssdk', // JSSDK
]);
}
}
2、【后端】Jssdk类覆盖父类的signature函数增加url参数
<?php
namespace common\helpers\wx\mp;
use abei2017\wx\mp\js\Js;
use Yii;
use yii\helpers\Json;
/**
* Created by PhpStorm.
* User: nodelog
* Date: 2018/9/23
* Time: 1:08
*/
class Jssdk extends Js
{
public function buildConfig($apis = [],$debug = false, $url){
$signPackage = $this->signature($url);
$config = array_merge(['debug'=>$debug],$signPackage,['jsApiList'=>$apis]);
return Json::encode($config);
}
public function signature($url){
$nonce = Yii::$app->security->generateRandomString(32);
$timestamp = time();
$ticket = $this->ticket();
$sign = [
'appId' => $this->conf['app_id'],
'nonceStr' => $nonce,
'timestamp' => $timestamp,
'signature' => $this->getSignature($ticket, $nonce, $timestamp, $url),
];
return $sign;
}
}
3、【前端】ajax请求加入url参数
$.get('api域名/weixin/jssdk',{
'apis':'getLocation', //jssdk api列表,多个api逗号分隔
'debug': true, //是否开启调试
'url':location.href.split('#')[0] //签名的ur需要是当前网页的URL,不包含#及其后面部分
},function (res) {
wx.config(res.config);
});
4、【接口】api接口中buildConfig函数返回参数json解码
<?php
namespace api\modules\v1\controllers;
use api\common\controllers\Controller;
use common\helpers\wx\Application;
use yii\helpers\Json;
/**
* Created by PhpStorm.
* User: nodelog
* Date: 2018/9/23
* Time: 0:00
*/
class WeixinController extends Controller
{
/**
* JSSDK
* @throws \abei2017\wx\core\Exception
*/
public function actionJssdk()
{
$app = new Application(['conf' => \Yii::$app->params['wx']['mp']]);
$js = $app->driver("mp.jssdk");
$apis = explode(',', request('apis'));
$debug = request('debug') == "true" ? true : false;
$url = request('url');
$config = $js->buildConfig($apis, $debug, $url);
return ['config' => Json::decode($config)];
}
}
网友评论