| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <?php
- namespace common\components;
- use common\services\xhMerchantService;
- use linslin\yii2\curl;
- use yii\helpers\Json;
- class jsSDK
- {
- public function getMiniSignPackage()
- {
- $jsapiTicket = $this->getJsApiTicket($merchant);
- $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
- $timestamp = time();
- $nonceStr = $this->createNonceStr();
- $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";// 这里参数的顺序要按照 key 值 ASCII 码升序排序
- $signature = sha1($string);
- $appId = $merchant['miniAppId'];
- $signPackage = array(
- "appId" => $appId,
- "nonceStr" => $nonceStr,
- "timestamp" => $timestamp,
- "url" => $url,
- "signature" => $signature,
- "rawString" => $string
- );
- return $signPackage;
- }
-
- public function getSignPackage($merchant)
- {
- $jsapiTicket = $this->getJsApiTicket($merchant);
- $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
- $timestamp = time();
- $nonceStr = $this->createNonceStr();
- $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";// 这里参数的顺序要按照 key 值 ASCII 码升序排序
- $signature = sha1($string);
- $appId = !empty($merchant) && !empty($merchant['wxAppId']) ? $merchant['wxAppId'] : '';
- $signPackage = array(
- "appId" => $appId,
- "nonceStr" => $nonceStr,
- "timestamp" => $timestamp,
- "url" => $url,
- "signature" => $signature,
- "rawString" => $string
- );
- return $signPackage;
- }
-
- private function createNonceStr($length = 16)
- {
- $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- $str = "";
- for ($i = 0; $i < $length; $i++) {
- $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
- }
- return $str;
- }
-
- private function getJsApiTicket($merchant)
- {
- $now = time();
- $merchantId = $merchant['id'];
- if (!empty($merchant) && !empty($merchant['wxJsApiTicket']) && ($now < strtotime($merchant['wxJsApiTicketExpire']))) {
- return $merchant['wxJsApiTicket'];
- } else {
- $accessToken = weixinUtil::getAuthorizerAccessToken($merchant);
- $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
- $curl = new curl\Curl();
- $result = $curl->get($url);
- $res = Json::decode($result);
- if (isset($res['ticket'])) {
- $expireTime = (int)($now + $res['expires_in']);
- $uData['wxJsApiTicket'] = $res['ticket'];
- $uData['wxJsApiTicketExpire'] = date("Y-m-d H:i:s", $expireTime);
- xhMerchantService::updateById($merchantId, $uData);
- return $res['ticket'];
- }
- return '';
- }
- }
-
- }
|