WechatService.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. namespace App\Common\Services;
  3. use App\Common\Library\AES;
  4. use App\Exceptions\ApiException;
  5. use App\Services\CommonBaseService;
  6. use GuzzleHttp\Client;
  7. use GuzzleHttp\Exception\RequestException;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\Log;
  10. class WechatService extends CommonBaseService
  11. {
  12. protected $cache = true;
  13. protected $cacheBucket = 'wechat:';
  14. protected $client = null;
  15. protected $appId = null;
  16. protected $appSecret = null;
  17. public function __construct()
  18. {
  19. $client = new Client();
  20. $this->client = $client;
  21. $this->appId = config('wechat.app_id');
  22. $this->appSecret = config('wechat.app_secret');
  23. }
  24. public function getAccessToken()
  25. {
  26. $accessTokenKey = 'wechat:access:key';
  27. $cache = Cache::get($accessTokenKey);
  28. if($cache) {
  29. return $cache;
  30. }
  31. $url = 'https://api.weixin.qq.com/cgi-bin/stable_token';
  32. $formParams = [
  33. 'appid' => $this->appId,
  34. 'secret' => $this->appSecret,
  35. 'grant_type' => 'client_credential'
  36. ];
  37. try {
  38. $options = [
  39. 'json' => $formParams,
  40. 'headers' => [
  41. 'Content-Type' => 'application/json'
  42. ]
  43. ];
  44. $response = $this->client->request('POST', $url, $options);
  45. // 获取响应体并解码为数组
  46. $body = json_decode($response->getBody()->getContents(), true);
  47. if (!empty($body['errcode'])) {
  48. $this->throwApiError($options, json_encode($body['errcode']).json_encode($body['errmsg']));
  49. } else {
  50. Cache::put($accessTokenKey, $body['access_token'], 240);
  51. return $body['access_token'];
  52. }
  53. } catch (RequestException $e) {
  54. $this->throwApiError($options, $e->getMessage(), $e->getCode());
  55. }
  56. }
  57. public function getSessionInfo($code)
  58. {
  59. $url = 'https://api.weixin.qq.com/sns/jscode2session';
  60. // 准备请求参数
  61. $formParams = [
  62. 'appid' => $this->appId,
  63. 'secret' => $this->appSecret,
  64. 'js_code' => $code,
  65. 'grant_type' => 'authorization_code'
  66. ];
  67. try {
  68. $options = [
  69. 'query' => $formParams
  70. ];
  71. $response = $this->client->request('GET', $url, $options);
  72. // 获取响应体并解码为数组
  73. $body = json_decode($response->getBody()->getContents(), true);
  74. if (!empty($body['errcode'])) {
  75. $this->throwApiError($options, json_encode($body['errcode']).json_encode($body['errmsg']));
  76. } else {
  77. // $openid = $data['openid'];
  78. // $sessionKey = $data['session_key'];
  79. return $body;
  80. }
  81. } catch (RequestException $e) {
  82. $this->throwApiError($options, $e->getMessage(), $e->getCode());
  83. }
  84. }
  85. public function getUserPhoneNumber($code)
  86. {
  87. $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber';
  88. // 准备请求参数
  89. try {
  90. $options = [
  91. 'query' => ['access_token' => $this->getAccessToken()],
  92. 'json' => ['code' => $code],
  93. 'headers' => [
  94. 'Content-Type' => 'application/json'
  95. ]
  96. ];
  97. $response = $this->client->request('POST', $url, $options);
  98. // 获取响应体并解码为数组
  99. $body = json_decode($response->getBody()->getContents(), true);
  100. if (!empty($body['errcode'])) {
  101. $this->throwApiError($options, json_encode($body['errcode']).json_encode($body['errmsg']));
  102. } else {
  103. /*
  104. * {
  105. "errcode":0,
  106. "errmsg":"ok",
  107. "phone_info": {
  108. "phoneNumber":"xxxxxx",
  109. "purePhoneNumber": "xxxxxx",
  110. "countryCode": 86,
  111. "watermark": {
  112. "timestamp": 1637744274,
  113. "appid": "xxxx"
  114. }
  115. }
  116. }
  117. */
  118. return $body;
  119. }
  120. } catch (RequestException $e) {
  121. $this->throwApiError($options, $e->getMessage(), $e->getCode());
  122. }
  123. }
  124. public function getWxaQueryScheme($scheme)
  125. {
  126. //https://api.weixin.qq.com/wxa/queryscheme?access_token=ACCESS_TOKEN
  127. //query_type
  128. $keyScheme = 'key:wechat:key:scheme';
  129. $cache = Cache::get($keyScheme);
  130. if($cache) {
  131. return $cache;
  132. }
  133. $url = 'https://api.weixin.qq.com/wxa/generatescheme';
  134. // 准备请求参数
  135. try {
  136. $options = [
  137. 'query' => ['access_token' => $this->getAccessToken()],
  138. 'json' => ['expire_time' => strtotime('+28 day', time()), 'expire_type' => 0],
  139. 'headers' => [
  140. 'Content-Type' => 'application/json'
  141. ]
  142. ];
  143. $response = $this->client->request('POST', $url, $options);
  144. // 获取响应体并解码为数组
  145. $body = json_decode($response->getBody()->getContents(), true);
  146. if (!empty($body['errcode'])) {
  147. $this->throwApiError($options, json_encode($body['errcode']).json_encode($body['errmsg']));
  148. } else {
  149. Cache::put($keyScheme, $body['openlink'], 20 * 24 * 60 * 60);
  150. return $body['openlink'] ?? '';
  151. }
  152. } catch (RequestException $e) {
  153. $this->throwApiError($options, $e->getMessage(), $e->getCode());
  154. }
  155. }
  156. public function decryptData(string $sessionKey, string $iv, string $encrypted)
  157. {
  158. $decrypted = AES::decrypt(
  159. base64_decode($encrypted, false), base64_decode($sessionKey, false), base64_decode($iv, false)
  160. );
  161. $decrypted = json_decode($this->pkcs7Unpad($decrypted), true);
  162. if (!$decrypted) {
  163. $this->throwApiError([$sessionKey, $iv, $encrypted], '解密失败', 500);
  164. }
  165. return $decrypted;
  166. }
  167. public function pkcs7Unpad(string $text)
  168. {
  169. $pad = ord(substr($text, -1));
  170. if ($pad < 1 || $pad > 32) {
  171. $pad = 0;
  172. }
  173. return substr($text, 0, (strlen($text) - $pad));
  174. }
  175. private function throwApiError($options, $error, $code = 200)
  176. {
  177. $key = createGuid();
  178. Log::info('Wechat第三方接口出错key:'.$key);
  179. Log::info('Wechat第三方接口出错params:'.json_encode($options));
  180. Log::info('Wechat第三方接口出错:'.$code.','.$error);
  181. throw new ApiException(500);
  182. }
  183. }