jsSDK.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace common\components;
  3. use common\services\xhMerchantService;
  4. use linslin\yii2\curl;
  5. use yii\helpers\Json;
  6. class jsSDK
  7. {
  8. public function getMiniSignPackage()
  9. {
  10. $jsapiTicket = $this->getJsApiTicket($merchant);
  11. $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  12. $timestamp = time();
  13. $nonceStr = $this->createNonceStr();
  14. $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";// 这里参数的顺序要按照 key 值 ASCII 码升序排序
  15. $signature = sha1($string);
  16. $appId = $merchant['miniAppId'];
  17. $signPackage = array(
  18. "appId" => $appId,
  19. "nonceStr" => $nonceStr,
  20. "timestamp" => $timestamp,
  21. "url" => $url,
  22. "signature" => $signature,
  23. "rawString" => $string
  24. );
  25. return $signPackage;
  26. }
  27. public function getSignPackage($merchant)
  28. {
  29. $jsapiTicket = $this->getJsApiTicket($merchant);
  30. $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  31. $timestamp = time();
  32. $nonceStr = $this->createNonceStr();
  33. $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";// 这里参数的顺序要按照 key 值 ASCII 码升序排序
  34. $signature = sha1($string);
  35. $appId = !empty($merchant) && !empty($merchant['wxAppId']) ? $merchant['wxAppId'] : '';
  36. $signPackage = array(
  37. "appId" => $appId,
  38. "nonceStr" => $nonceStr,
  39. "timestamp" => $timestamp,
  40. "url" => $url,
  41. "signature" => $signature,
  42. "rawString" => $string
  43. );
  44. return $signPackage;
  45. }
  46. private function createNonceStr($length = 16)
  47. {
  48. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  49. $str = "";
  50. for ($i = 0; $i < $length; $i++) {
  51. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  52. }
  53. return $str;
  54. }
  55. private function getJsApiTicket($merchant)
  56. {
  57. $now = time();
  58. $merchantId = $merchant['id'];
  59. if (!empty($merchant) && !empty($merchant['wxJsApiTicket']) && ($now < strtotime($merchant['wxJsApiTicketExpire']))) {
  60. return $merchant['wxJsApiTicket'];
  61. } else {
  62. $accessToken = weixinUtil::getAuthorizerAccessToken($merchant);
  63. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
  64. $curl = new curl\Curl();
  65. $result = $curl->get($url);
  66. $res = Json::decode($result);
  67. if (isset($res['ticket'])) {
  68. $expireTime = (int)($now + $res['expires_in']);
  69. $uData['wxJsApiTicket'] = $res['ticket'];
  70. $uData['wxJsApiTicketExpire'] = date("Y-m-d H:i:s", $expireTime);
  71. xhMerchantService::updateById($merchantId, $uData);
  72. return $res['ticket'];
  73. }
  74. return '';
  75. }
  76. }
  77. }