WechatService.php 13 KB

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