WechatService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. <?php
  2. namespace app\wechat\service;
  3. use think\admin\extend\JsonRpcClient;
  4. use think\admin\Service;
  5. use think\admin\storage\LocalStorage;
  6. use think\exception\HttpResponseException;
  7. /**
  8. * Class WechatService
  9. * @package app\wechat\serivce
  10. *
  11. * @method \WeChat\Card WeChatCard() static 微信卡券管理
  12. * @method \WeChat\Custom WeChatCustom() static 微信客服消息
  13. * @method \WeChat\Limit WeChatLimit() static 接口调用频次限制
  14. * @method \WeChat\Media WeChatMedia() static 微信素材管理
  15. * @method \WeChat\Menu WeChatMenu() static 微信菜单管理
  16. * @method \WeChat\Oauth WeChatOauth() static 微信网页授权
  17. * @method \WeChat\Pay WeChatPay() static 微信支付商户
  18. * @method \WeChat\Product WeChatProduct() static 微信商店管理
  19. * @method \WeChat\Qrcode WeChatQrcode() static 微信二维码管理
  20. * @method \WeChat\Receive WeChatReceive() static 微信推送管理
  21. * @method \WeChat\Scan WeChatScan() static 微信扫一扫接入管理
  22. * @method \WeChat\Script WeChatScript() static 微信前端支持
  23. * @method \WeChat\Shake WeChatShake() static 微信揺一揺周边
  24. * @method \WeChat\Tags WeChatTags() static 微信用户标签管理
  25. * @method \WeChat\Template WeChatTemplate() static 微信模板消息
  26. * @method \WeChat\User WeChatUser() static 微信粉丝管理
  27. * @method \WeChat\Wifi WeChatWifi() static 微信门店WIFI管理
  28. *
  29. * ----- WeMini -----
  30. * @method \WeMini\Account WeMiniAccount() static 小程序账号管理
  31. * @method \WeMini\Basic WeMiniBasic() static 小程序基础信息设置
  32. * @method \WeMini\Code WeMiniCode() static 小程序代码管理
  33. * @method \WeMini\Domain WeMiniDomain() static 小程序域名管理
  34. * @method \WeMini\Tester WeMinitester() static 小程序成员管理
  35. * @method \WeMini\User WeMiniUser() static 小程序帐号管理
  36. * --------------------
  37. * @method \WeMini\Crypt WeMiniCrypt() static 小程序数据加密处理
  38. * @method \WeMini\Delivery WeMiniDelivery() static 小程序即时配送
  39. * @method \WeMini\Image WeMiniImage() static 小程序图像处理
  40. * @method \WeMini\Logistics WeMiniLogistics() static 小程序物流助手
  41. * @method \WeMini\Message WeMiniMessage() static 小程序动态消息
  42. * @method \WeMini\Ocr WeMiniOcr() static 小程序ORC服务
  43. * @method \WeMini\Plugs WeMiniPlugs() static 小程序插件管理
  44. * @method \WeMini\Poi WeMiniPoi() static 小程序地址管理
  45. * @method \WeMini\Qrcode WeMiniQrcode() static 小程序二维码管理
  46. * @method \WeMini\Security WeMiniSecurity() static 小程序内容安全
  47. * @method \WeMini\Soter WeMiniSoter() static 小程序生物认证
  48. * @method \WeMini\Template WeMiniTemplate() static 小程序模板消息支持
  49. * @method \WeMini\Total WeMiniTotal() static 小程序数据接口
  50. * @method \WeMini\Newtmpl WeMiniNewtmpl() static 小程序订阅消息支持
  51. *
  52. * ----- WePay -----
  53. * @method \WePay\Bill WePayBill() static 微信商户账单及评论
  54. * @method \WePay\Order WePayOrder() static 微信商户订单
  55. * @method \WePay\Refund WePayRefund() static 微信商户退款
  56. * @method \WePay\Coupon WePayCoupon() static 微信商户代金券
  57. * @method \WePay\Redpack WePayRedpack() static 微信红包支持
  58. * @method \WePay\Transfers WePayTransfers() static 微信商户打款到零钱
  59. * @method \WePay\TransfersBank WePayTransfersBank() static 微信商户打款到银行卡
  60. *
  61. * ----- WeOpen -----
  62. * @method \WeOpen\Login WeOpenLogin() static 第三方微信登录
  63. * @method \WeOpen\Service WeOpenService() static 第三方服务
  64. *
  65. * ----- ThinkService -----
  66. * @method mixed ThinkServiceConfig() static 平台服务配置
  67. */
  68. class WechatService extends Service
  69. {
  70. /**
  71. * 静态初始化对象
  72. * @param string $name
  73. * @param array $arguments
  74. * @return mixed
  75. * @throws \think\admin\Exception
  76. * @throws \think\db\exception\DataNotFoundException
  77. * @throws \think\db\exception\DbException
  78. * @throws \think\db\exception\ModelNotFoundException
  79. */
  80. public static function __callStatic(string $name, array $arguments)
  81. {
  82. [$type, $class, $classname] = static::parseName($name);
  83. if ("{$type}{$class}" !== $name) {
  84. throw new \think\admin\Exception("抱歉,实例 {$name} 不在符合规则!");
  85. }
  86. if (sysconf('wechat.type') === 'api' || $type === 'WePay') {
  87. if ($type === 'ThinkService') {
  88. throw new \think\admin\Exception("抱歉,接口模式不能实例 {$classname} 对象!");
  89. }
  90. return new $classname(static::instance()->getConfig());
  91. } else {
  92. [$appid, $appkey] = [sysconf('wechat.thr_appid'), sysconf('wechat.thr_appkey')];
  93. $data = ['class' => $name, 'appid' => $appid, 'time' => time(), 'nostr' => uniqid()];
  94. $data['sign'] = md5("{$data['class']}#{$appid}#{$appkey}#{$data['time']}#{$data['nostr']}");
  95. // 创建远程连接,默认使用 JSON RPC 方式
  96. $token = enbase64url(json_encode($data, JSON_UNESCAPED_UNICODE));
  97. $client = new JsonRpcClient("https://open.cuci.cc/service/api.client/jsonrpc?not_init_session=1&token={$token}");
  98. if (is_numeric(stripos($client->__call('_get_class_name_', []), 'Exception'))) {
  99. throw new \think\admin\Exception($client->getMessage(), $client->getCode());
  100. }
  101. return $client;
  102. }
  103. }
  104. /**
  105. * 解析调用对象名称
  106. * @param string $name
  107. * @return array
  108. */
  109. private static function parseName(string $name): array
  110. {
  111. foreach (['WeChat', 'WeMini', 'WeOpen', 'WePay', 'ThinkService'] as $type) {
  112. if (strpos($name, $type) === 0) {
  113. [, $class] = explode($type, $name);
  114. return [$type, $class, "\\{$type}\\{$class}"];
  115. }
  116. }
  117. return ['-', '-', $name];
  118. }
  119. /**
  120. * 获取当前微信APPID
  121. * @return string
  122. * @throws \think\admin\Exception
  123. * @throws \think\db\exception\DataNotFoundException
  124. * @throws \think\db\exception\DbException
  125. * @throws \think\db\exception\ModelNotFoundException
  126. */
  127. public function getAppid(): string
  128. {
  129. if ($this->getType() === 'api') {
  130. return sysconf('wechat.appid');
  131. } else {
  132. return sysconf('wechat.thr_appid');
  133. }
  134. }
  135. /**
  136. * 获取接口授权模式
  137. * @return string
  138. * @throws \think\admin\Exception
  139. * @throws \think\db\exception\DataNotFoundException
  140. * @throws \think\db\exception\DbException
  141. * @throws \think\db\exception\ModelNotFoundException
  142. */
  143. public function getType(): string
  144. {
  145. $type = strtolower(sysconf('wechat.type'));
  146. if (in_array($type, ['api', 'thr'])) return $type;
  147. throw new \think\admin\Exception('请在后台配置微信对接授权模式');
  148. }
  149. /**
  150. * 获取公众号配置参数
  151. * @return array
  152. * @throws \think\admin\Exception
  153. * @throws \think\db\exception\DataNotFoundException
  154. * @throws \think\db\exception\DbException
  155. * @throws \think\db\exception\ModelNotFoundException
  156. */
  157. public function getConfig(): array
  158. {
  159. $options = [
  160. 'appid' => $this->getAppid(),
  161. 'token' => sysconf('wechat.token'),
  162. 'appsecret' => sysconf('wechat.appsecret'),
  163. 'encodingaeskey' => sysconf('wechat.encodingaeskey'),
  164. 'mch_id' => sysconf('wechat.mch_id'),
  165. 'mch_key' => sysconf('wechat.mch_key'),
  166. 'cache_path' => $this->app->getRuntimePath() . 'wechat',
  167. ];
  168. $local = LocalStorage::instance();
  169. switch (strtolower(sysconf('wechat.mch_ssl_type'))) {
  170. case 'p12':
  171. $options['ssl_p12'] = $local->path(sysconf('wechat.mch_ssl_p12'), true);
  172. break;
  173. case 'pem':
  174. $options['ssl_key'] = $local->path(sysconf('wechat.mch_ssl_key'), true);
  175. $options['ssl_cer'] = $local->path(sysconf('wechat.mch_ssl_cer'), true);
  176. break;
  177. }
  178. return $options;
  179. }
  180. /**
  181. * 通过网页授权获取粉丝信息
  182. * @param string $source 回跳URL地址
  183. * @param integer $isfull 获取资料模式
  184. * @param boolean $redirect 是否直接跳转
  185. * @return array
  186. * @throws \WeChat\Exceptions\InvalidResponseException
  187. * @throws \WeChat\Exceptions\LocalCacheException
  188. * @throws \think\admin\Exception
  189. * @throws \think\db\exception\DataNotFoundException
  190. * @throws \think\db\exception\DbException
  191. * @throws \think\db\exception\ModelNotFoundException
  192. */
  193. public function getWebOauthInfo(string $source, $isfull = 0, $redirect = true): array
  194. {
  195. $appid = $this->getAppid();
  196. $openid = $this->app->session->get("{$appid}_openid");
  197. $userinfo = $this->app->session->get("{$appid}_fansinfo");
  198. if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($userinfo))) {
  199. empty($userinfo) || FansService::instance()->set($userinfo, $appid);
  200. return ['openid' => $openid, 'fansinfo' => $userinfo];
  201. }
  202. if ($this->getType() === 'api') {
  203. // 解析 GET 参数
  204. parse_str(parse_url($source, PHP_URL_QUERY), $params);
  205. $getVars = [
  206. 'code' => $params['code'] ?? input('code', ''),
  207. 'rcode' => $params['rcode'] ?? input('rcode', ''),
  208. 'state' => $params['state'] ?? input('state', ''),
  209. ];
  210. $wechat = static::WeChatOauth();
  211. if ($getVars['state'] !== $appid || empty($getVars['code'])) {
  212. $params['rcode'] = enbase64url($source);
  213. $location = strstr("{$source}?", '?', true) . '?' . http_build_query($params);
  214. $oauthurl = $wechat->getOauthRedirect($location, $appid, $isfull ? 'snsapi_userinfo' : 'snsapi_base');
  215. throw new HttpResponseException($redirect ? redirect($oauthurl, 301) : response("location.href='{$oauthurl}'"));
  216. } elseif (($token = $wechat->getOauthAccessToken($getVars['code'])) && isset($token['openid'])) {
  217. $this->app->session->set("{$appid}_openid", $openid = $token['openid']);
  218. if ($isfull && isset($token['access_token'])) {
  219. $userinfo = $wechat->getUserInfo($token['access_token'], $openid);
  220. $this->app->session->set("{$appid}_fansinfo", $userinfo);
  221. empty($userinfo) || FansService::instance()->set($userinfo, $appid);
  222. }
  223. }
  224. if ($getVars['rcode']) {
  225. $location = debase64url($getVars['rcode']);
  226. throw new HttpResponseException($redirect ? redirect($location, 301) : response("location.href='{$location}'"));
  227. } elseif ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($userinfo))) {
  228. return ['openid' => $openid, 'fansinfo' => $userinfo];
  229. } else {
  230. throw new \think\admin\Exception('Query params [rcode] not find.');
  231. }
  232. } else {
  233. $result = static::ThinkServiceConfig()->oauth($this->app->session->getId(), $source, $isfull);
  234. $this->app->session->set("{$appid}_openid", $openid = $result['openid']);
  235. $this->app->session->set("{$appid}_fansinfo", $userinfo = $result['fans']);
  236. if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($userinfo))) {
  237. empty($userinfo) || FansService::instance()->set($userinfo, $appid);
  238. return ['openid' => $openid, 'fansinfo' => $userinfo];
  239. }
  240. if ($redirect) {
  241. throw new HttpResponseException(redirect($result['url'], 301));
  242. } else {
  243. throw new HttpResponseException(response("location.href='{$result['url']}'"));
  244. }
  245. }
  246. }
  247. /**
  248. * 获取微信网页JSSDK签名参数
  249. * @param null|string $location 签名地址
  250. * @return array
  251. * @throws \WeChat\Exceptions\InvalidResponseException
  252. * @throws \WeChat\Exceptions\LocalCacheException
  253. * @throws \think\admin\Exception
  254. * @throws \think\db\exception\DataNotFoundException
  255. * @throws \think\db\exception\DbException
  256. * @throws \think\db\exception\ModelNotFoundException
  257. */
  258. public function getWebJssdkSign(?string $location = null): array
  259. {
  260. $location = $location ?: $this->app->request->url(true);
  261. if ($this->getType() === 'api') {
  262. return static::WeChatScript()->getJsSign($location);
  263. } else {
  264. return static::ThinkServiceConfig()->jsSign($location);
  265. }
  266. }
  267. }