Service.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. <?php
  2. namespace app\common\library\Wechat;
  3. use fast\Http;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Psr7\Response;
  6. use think\Cache;
  7. use think\Log;
  8. use think\Config;
  9. use app\common\Enum\ChannelEnum;
  10. use app\common\Service\ShopConfigService;
  11. /**
  12. * 小程序服务类
  13. */
  14. class Service
  15. {
  16. private $appId = '';
  17. private $appSecret = '';
  18. public function __construct($platform = ChannelEnum::CHANNEL_WECHAT_MINI_PROGRAM)
  19. {
  20. // 需要转换 前段穿 DouyinMiniProgram 后端配置是 douyin_mini_program
  21. $platformKey = $this->convertPlatformName($platform);
  22. $platformConfig = ShopConfigService::getConfigs('shop.platform.' . $platformKey);
  23. $this->appId = $platformConfig['app_id'] ?? '';
  24. $this->appSecret = $platformConfig['secret'] ?? '';
  25. }
  26. /**
  27. * 转换平台名称格式
  28. * 将前端驼峰命名转换为后端下划线格式
  29. *
  30. * @param string $platform
  31. * @return string
  32. */
  33. protected function convertPlatformName($platform)
  34. {
  35. // 将驼峰命名转换为下划线格式
  36. return strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst($platform)));
  37. }
  38. /**
  39. * 批量并发发送
  40. * @param array $pushList
  41. * @return bool
  42. */
  43. public function subscribeMessageSendMultiple($pushList)
  44. {
  45. $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $this->getAccessToken();
  46. $concurrentSize = 10;
  47. $promises = [];
  48. $client = new Client();
  49. $promiseProcess = function ($promises) {
  50. $results = \GuzzleHttp\Promise\Utils::unwrap($promises);
  51. foreach ($results as $key => $response) {
  52. $res = (array)json_decode($response->getBody()->getContents(), true);
  53. if (isset($res['errmsg']) && Config::get('app_debug')) {
  54. Log::write($res, 'send_msg');
  55. }
  56. }
  57. };
  58. foreach ($pushList as $index => $item) {
  59. $promises[] = $client->postAsync($url, ['body' => json_encode($item, JSON_UNESCAPED_UNICODE)]);
  60. if (count($promises) == $concurrentSize) {
  61. $promiseProcess($promises);
  62. $promises = [];
  63. }
  64. }
  65. if ($promises) {
  66. $promiseProcess($promises);
  67. }
  68. return true;
  69. }
  70. /**
  71. * 单次异步发送
  72. * @param array $pushData
  73. * @return bool
  74. */
  75. public function subscribeMessageSend($pushData)
  76. {
  77. $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $this->getAccessToken();
  78. $client = new Client();
  79. $client->postAsync($url, ['body' => json_encode($pushData, JSON_UNESCAPED_UNICODE)])->then(function (Response $response) {
  80. $res = (array)json_decode($response->getBody()->getContents(), true);
  81. if (isset($res['errmsg']) && Config::get('app_debug')) {
  82. Log::write($res, 'send_msg');
  83. return false;
  84. }
  85. })->wait();
  86. return true;
  87. }
  88. //获取access_token
  89. public function getAccessToken()
  90. {
  91. $access_token = Cache::get('shop' . $this->appId);
  92. if (!$access_token) {
  93. $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appId . '&secret=' . $this->appSecret;
  94. $res = Http::get($url);
  95. $res = (array)json_decode($res, true);
  96. if (isset($res['access_token'])) {
  97. $access_token = $res['access_token'];
  98. } elseif (Config::get('app_debug')) {
  99. Log::write('code:' . $res['errcode'] . ',message:' . $res['errmsg'], 'access_token');
  100. }
  101. Cache::set('shop' . $this->appId, $access_token, 7000);
  102. }
  103. return $access_token;
  104. }
  105. //生成小程序码
  106. public function getWxCodeUnlimited($param)
  107. {
  108. $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $this->getAccessToken();
  109. $data = array_merge([
  110. 'width' => '280'
  111. ], $param);
  112. return Http::post($url, json_encode($data, JSON_UNESCAPED_UNICODE));
  113. }
  114. //获取手机号
  115. public function getWechatMobile($code)
  116. {
  117. $access_token = $this->getAccessToken();
  118. $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
  119. $res = Http::post($url, json_encode(['code' => $code]));
  120. $res = (array)json_decode($res, true);
  121. if (!isset($res['phone_info']) && config('app_debug')) {
  122. \think\Log::write($res);
  123. }
  124. return $res['phone_info'] ?? [];
  125. }
  126. //获取Session信息
  127. public function getWechatSession($code)
  128. {
  129. $params = [
  130. 'appid' => $this->appId,
  131. 'secret' => $this->appSecret,
  132. 'js_code' => $code,
  133. 'grant_type' => 'authorization_code'
  134. ];
  135. $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
  136. if ($result['ret']) {
  137. $json = (array)json_decode($result['msg'], true);
  138. return $json;
  139. }
  140. if (config('app_debug')) {
  141. Log::write($result);
  142. }
  143. return ['errmsg' => config('app_debug') ? $result['msg'] : '网络错误'];
  144. }
  145. }