Mini.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. <?php
  2. namespace App\libs\wechat\auth\Gateways;
  3. use App\libs\cache\redis\Redis;
  4. use App\libs\helpers\Curl;
  5. use Illuminate\Support\Facades\DB;
  6. /**
  7. * @desc 微信小程序类
  8. */
  9. class Mini extends Base
  10. {
  11. private $appId;
  12. private $secret;
  13. public function __construct()
  14. {
  15. parent::__construct();
  16. $this->appId = $this->config['appid'];
  17. $this->secret = $this->config['secret'];
  18. }
  19. /**
  20. * @see https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
  21. *
  22. * @desc 使用授权code换取openid
  23. */
  24. public function code2Openid(string $code): array
  25. {
  26. $url = 'https://api.weixin.qq.com/sns/jscode2session';
  27. $res = Curl::requestCurl($url, 'GET', [], http_build_query([
  28. 'appid' => $this->appId,
  29. 'secret' => $this->secret,
  30. 'js_code' => $code,
  31. 'grant_type' => 'authorization_code',
  32. ]));
  33. return $res ? json_decode($res, true) : [];
  34. }
  35. /**
  36. * @see https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
  37. *
  38. * @desc 解密小程序信息
  39. *
  40. * @param string $sessionKey session_key
  41. * @param string $encryptedData 加密字符
  42. * @param string $iv 偏移量
  43. */
  44. public function decrypt($sessionKey, $encryptedData, $iv): array
  45. {
  46. if (24 !== \strlen($iv)) {
  47. // 偏移量错误
  48. return ['code' => 41002, 'data' => '', 'msg' => 'iv解密失败'];
  49. }
  50. if (24 !== \strlen($sessionKey)) {
  51. // sessionkey 错误
  52. return ['code' => 41001, 'data' => '', 'msg' => 'sessionKey解密失败'];
  53. }
  54. $data = openssl_decrypt(base64_decode($encryptedData, true), 'AES-128-CBC', base64_decode($sessionKey, true), OPENSSL_RAW_DATA, base64_decode($iv, true));
  55. if (!$data) {
  56. return ['code' => 41001, 'data' => '', 'msg' => '解密失败'];
  57. }
  58. $userInfo = json_decode($data, true);
  59. if ($userInfo['watermark']['appid'] !== $this->appId) {
  60. return ['code' => 41003, 'data' => '', 'msg' => 'appid不匹配'];
  61. }
  62. $userInfo['nickName'] = !empty($userInfo['nickName']) ? $userInfo['nickName'] : '';
  63. return ['code' => 0, 'data' => $userInfo, 'msg' => 'success'];
  64. }
  65. /**
  66. * @see https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
  67. *
  68. * @desc 获取小程序码(限量)
  69. *
  70. * @param string $path 页面路径
  71. * @param int $width 二维码宽度
  72. */
  73. public function qrcode(string $path, $width = 430)
  74. {
  75. $params = ['path' => $path, 'width' => $width];
  76. $url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' . $this->accessToken();
  77. return Curl::requestCurl($url, 'POST', [], json_encode($params));
  78. }
  79. /**
  80. * @see https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
  81. *
  82. * @desc 获取小程序码(不限量)
  83. *
  84. * @param string $scene 场景值
  85. * @param array $extra 额外参数,详见
  86. *
  87. * @return bool|mixed|string
  88. */
  89. public function qrcodeUnlimited(string $scene, $extra = [])
  90. {
  91. $params = array_merge($extra, ['scene' => $scene]);
  92. $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $this->accessToken();
  93. return Curl::requestCurl($url, 'POST', [], json_encode($params));
  94. }
  95. /**
  96. * @see https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-link/urllink.generate.html
  97. *
  98. * @desc 生成短链接
  99. *
  100. * @return bool|string
  101. */
  102. public function urlLink(array $params)
  103. {
  104. $url = 'https://api.weixin.qq.com/wxa/generate_urllink?access_token=' . $this->accessToken();
  105. return Curl::requestCurl($url, 'POST', [], json_encode($params));
  106. }
  107. /**
  108. * @see https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
  109. *
  110. * @desc 发送模板消息
  111. *
  112. * @param string $openid 小程序openid
  113. * @param string $template 模板ID
  114. * @param array $data 小程序数据
  115. * @param string $page 跳转页面
  116. * @param string $state 小程序状态
  117. *
  118. * @return bool|mixed
  119. */
  120. public function sendMiniMsg(string $openid, string $template, array $data, string $page = null, string $state = 'normal'): array
  121. {
  122. $params = [
  123. 'touser' => $openid,
  124. 'template_id' => $template,
  125. 'miniprogram_state' => $state,
  126. 'data' => $data,
  127. ];
  128. if ($page) {
  129. $params['page'] = $page;
  130. }
  131. $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $this->accessToken();
  132. $res = Curl::requestCurl($url, 'POST', [], json_encode($params));
  133. return $res ? json_decode($res, true) : [];
  134. }
  135. /**
  136. * @see https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
  137. *
  138. * @desc 获取全局唯一接口调用凭据
  139. *
  140. * @param int $repeatCnt
  141. *
  142. * @return string
  143. */
  144. public function accessToken(&$repeatCnt = 0)
  145. {
  146. $drive = $this->config['token_drive'] ?? 'redis';
  147. $key = 'mini_' . $this->appId . '_accessToken';
  148. switch ($drive) {
  149. case 'redis':
  150. $redis = Redis::instance();
  151. $redis->select(15);
  152. $token = $redis->get($key);
  153. break;
  154. case 'db':
  155. default:
  156. $token = Db::table('configs')->where('c_key', $key)->where('c_expired', '>', time())->value('c_value');
  157. break;
  158. }
  159. if ($token) {
  160. return $token;
  161. }
  162. $url = 'https://api.weixin.qq.com/cgi-bin/token';
  163. $res = Curl::requestCurl($url, 'GET', [], http_build_query([
  164. 'grant_type' => 'client_credential',
  165. 'appid' => $this->appId,
  166. 'secret' => $this->secret,
  167. ]));
  168. $data = json_decode($res, true);
  169. if (isset($data['access_token'])) {
  170. $token = $data['access_token'];
  171. switch ($drive) {
  172. case 'redis':
  173. $redis->setex($key, 7000, $token);
  174. break;
  175. case 'db':
  176. default:
  177. $isWin = Db::table('configs')->where('c_key', $key)->value('c_value');
  178. if ($isWin) {
  179. Db::table('configs')
  180. ->where('c_key', $key)
  181. ->update([
  182. 'c_value' => $token,
  183. 'c_expired' => time() + 7000,
  184. 'c_updated' => date('Y-m-d H:i:s'),
  185. ])
  186. ;
  187. } else {
  188. Db::table('configs')
  189. ->insert([
  190. 'c_key' => $key,
  191. 'c_value' => $token,
  192. 'c_expired' => time() + 7000,
  193. 'c_updated' => date('Y-m-d H:i:s'),
  194. ])
  195. ;
  196. }
  197. break;
  198. }
  199. return $token;
  200. }
  201. if ($repeatCnt <= 3) {
  202. ++$repeatCnt;
  203. return $this->accessToken($repeatCnt);
  204. }
  205. return $data['errcode'];
  206. }
  207. }