WechatService.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkAdmin
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://demo.thinkadmin.top
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( https://mit-license.org )
  10. // +----------------------------------------------------------------------
  11. // | gitee 代码仓库:https://gitee.com/zoujingli/ThinkAdmin
  12. // | github 代码仓库:https://github.com/zoujingli/ThinkAdmin
  13. // +----------------------------------------------------------------------
  14. namespace app\wechat\service;
  15. use library\tools\JsonRpcClient;
  16. /**
  17. * 微信处理管理
  18. * Class WechatService
  19. * @package app\wechat\service
  20. *
  21. * ----- WeOpen for Open -----
  22. * @method \WeOpen\Login login() static 第三方微信登录
  23. * @method \WeOpen\Service service() static 第三方服务
  24. *
  25. * ----- WeMini for Open -----
  26. * @method \WeMini\Code WeMiniCode() static 小程序代码管理
  27. * @method \WeMini\User WeMiniUser() static 小程序帐号管理
  28. * @method \WeMini\Basic WeMiniBasic() static 小程序基础信息
  29. * @method \WeMini\Domain WeMiniDomain() static 小程序域名管理
  30. * @method \WeMini\Tester WeMiniTester() static 小程序成员管理
  31. * @method \WeMini\Account WeMiniAccount() static 小程序账号管理
  32. *
  33. * ----- ThinkService -----
  34. * @method mixed wechat() static 第三方微信工具
  35. */
  36. class WechatService extends \We
  37. {
  38. /**
  39. * 获取微信支付配置
  40. * @param array|null $options
  41. * @return array
  42. * @throws \think\Exception
  43. * @throws \think\exception\PDOException
  44. */
  45. public static function config($options = null)
  46. {
  47. if (empty($options)) $options = [
  48. // 微信功能必需参数
  49. 'appid' => self::getAppid(),
  50. 'token' => sysconf('wechat_token'),
  51. 'appsecret' => sysconf('wechat_appsecret'),
  52. 'encodingaeskey' => sysconf('wechat_encodingaeskey'),
  53. // 微信支付必要参数
  54. 'mch_id' => sysconf('wechat_mch_id'),
  55. 'mch_key' => sysconf('wechat_mch_key'),
  56. 'cache_path' => env('runtime_path') . 'wechat' . DIRECTORY_SEPARATOR,
  57. ];
  58. if (sysconf('wechat_mch_ssl_type') === 'p12') {
  59. $options['ssl_p12'] = self::_parseCertPath(sysconf('wechat_mch_ssl_p12'));
  60. } else {
  61. $options['ssl_key'] = self::_parseCertPath(sysconf('wechat_mch_ssl_key'));
  62. $options['ssl_cer'] = self::_parseCertPath(sysconf('wechat_mch_ssl_cer'));
  63. }
  64. return parent::config($options);
  65. }
  66. /**
  67. * 解析证书路径
  68. * @param string $path
  69. * @return mixed
  70. * @throws \think\Exception
  71. */
  72. private static function _parseCertPath($path)
  73. {
  74. if (preg_match('|^[a-z0-9]{16,16}\/[a-z0-9]{16,16}\.|i', $path)) {
  75. return \library\File::instance('local')->path($path, true);
  76. }
  77. return $path;
  78. }
  79. /**
  80. * 静态魔术加载方法
  81. * @param string $name 静态类名
  82. * @param array $arguments 参数集合
  83. * @return mixed
  84. * @throws \think\Exception
  85. * @throws \think\exception\PDOException
  86. */
  87. public static function __callStatic($name, $arguments)
  88. {
  89. $config = [];
  90. if (is_array($arguments) && count($arguments) > 0) {
  91. $option = array_shift($arguments);
  92. $config = is_array($option) ? $option : self::config();
  93. }
  94. if (in_array($name, ['wechat'])) {
  95. return self::instance(trim($name, '_'), 'WeChat', $config);
  96. } elseif (substr($name, 0, 6) === 'WeChat') {
  97. return self::instance(substr($name, 6), 'WeChat', $config);
  98. } elseif (substr($name, 0, 6) === 'WeMini') {
  99. return self::instance(substr($name, 6), 'WeMini', $config);
  100. } elseif (substr($name, 0, 5) === 'WePay') {
  101. return self::instance(substr($name, 5), 'WePay', $config);
  102. } elseif (substr($name, 0, 6) === 'AliPay') {
  103. return self::instance(substr($name, 6), 'AliPay', $config);
  104. } else {
  105. throw new \think\Exception("class {$name} not found");
  106. }
  107. }
  108. /**
  109. * 接口对象实例化
  110. * @param string $name 接口名称
  111. * @param string $type 接口类型
  112. * @param array $config 微信配置
  113. * @return mixed
  114. * @throws \think\Exception
  115. * @throws \think\exception\PDOException
  116. */
  117. public static function instance($name, $type = 'WeChat', $config = [])
  118. {
  119. if (self::getType() === 'api' || in_array($type, ['WePay', 'AliPay']) || "{$type}{$name}" === 'WeChatPay') {
  120. if (class_exists($class = "\\{$type}\\" . ucfirst(strtolower($name)))) {
  121. return new $class(empty($config) ? self::config() : $config);
  122. } else {
  123. throw new \think\Exception("Class {$class} not found");
  124. }
  125. } else {
  126. set_time_limit(3600);
  127. list($appid, $appkey) = [sysconf('wechat_thr_appid'), sysconf('wechat_thr_appkey')];
  128. $token = strtolower("{$name}-{$appid}-{$appkey}-{$type}");
  129. if (class_exists('Yar_Client')) {
  130. return new \Yar_Client(config('wechat.service_url') . "/service/api.client/yar/{$token}");
  131. } else {
  132. return new JsonRpcClient(config('wechat.service_url') . "/service/api.client/jsonrpc/{$token}");
  133. }
  134. }
  135. }
  136. /**
  137. * 获取微信网页JSSDK
  138. * @param string $url JS签名地址
  139. * @return array
  140. * @throws \WeChat\Exceptions\InvalidResponseException
  141. * @throws \WeChat\Exceptions\LocalCacheException
  142. * @throws \think\Exception
  143. * @throws \think\exception\PDOException
  144. */
  145. public static function getWebJssdkSign($url = null)
  146. {
  147. $url = is_null($url) ? request()->url(true) : $url;
  148. if (self::getType() === 'api') {
  149. return self::WeChatScript()->getJsSign($url);
  150. } else {
  151. return self::wechat()->jsSign($url);
  152. }
  153. }
  154. /**
  155. * 初始化进入授权
  156. * @param string $url 授权页面URL地址
  157. * @param integer $isfull 授权微信模式
  158. * @param boolean $isRedirect 是否进行跳转
  159. * @return array
  160. * @throws \WeChat\Exceptions\InvalidResponseException
  161. * @throws \WeChat\Exceptions\LocalCacheException
  162. * @throws \think\Exception
  163. * @throws \think\exception\PDOException
  164. */
  165. public static function getWebOauthInfo($url, $isfull = 0, $isRedirect = true)
  166. {
  167. $appid = self::getAppid();
  168. list($openid, $fansinfo) = [session("{$appid}_openid"), session("{$appid}_fansinfo")];
  169. if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($fansinfo))) {
  170. empty($fansinfo) || FansService::set($fansinfo);
  171. return ['openid' => $openid, 'fansinfo' => $fansinfo];
  172. }
  173. if (self::getType() === 'api') {
  174. $wechat = self::WeChatOauth();
  175. if (request()->get('state') !== $appid) {
  176. $snsapi = empty($isfull) ? 'snsapi_base' : 'snsapi_userinfo';
  177. $param = (strpos($url, '?') !== false ? '&' : '?') . 'rcode=' . encode($url);
  178. $OauthUrl = $wechat->getOauthRedirect($url . $param, $appid, $snsapi);
  179. if ($isRedirect) redirect($OauthUrl, [], 301)->send();
  180. exit("window.location.href='{$OauthUrl}'");
  181. }
  182. if (($token = $wechat->getOauthAccessToken()) && isset($token['openid'])) {
  183. session("{$appid}_openid", $openid = $token['openid']);
  184. if (empty($isfull) && request()->get('rcode')) {
  185. redirect(decode(request()->get('rcode')), [], 301)->send();
  186. }
  187. session("{$appid}_fansinfo", $fansinfo = $wechat->getUserInfo($token['access_token'], $openid));
  188. empty($fansinfo) || FansService::set($fansinfo);
  189. }
  190. redirect(decode(request()->get('rcode')), [], 301)->send();
  191. } else {
  192. $result = self::wechat()->oauth(session_id(), $url, $isfull);
  193. session("{$appid}_openid", $openid = $result['openid']);
  194. session("{$appid}_fansinfo", $fansinfo = $result['fans']);
  195. if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($fansinfo))) {
  196. empty($fansinfo) || FansService::set($fansinfo);
  197. return ['openid' => $openid, 'fansinfo' => $fansinfo];
  198. }
  199. if ($isRedirect && !empty($result['url'])) {
  200. redirect($result['url'], [], 301)->send();
  201. }
  202. exit("window.location.href='{$result['url']}'");
  203. }
  204. }
  205. /**
  206. * 获取当前微信APPID
  207. * @return bool|string
  208. * @throws \think\Exception
  209. * @throws \think\exception\PDOException
  210. */
  211. public static function getAppid()
  212. {
  213. if (self::getType() === 'api') {
  214. return sysconf('wechat_appid');
  215. } else {
  216. return sysconf('wechat_thr_appid');
  217. }
  218. }
  219. /**
  220. * 获取接口授权模式
  221. * @return string
  222. * @throws \think\Exception
  223. * @throws \think\exception\PDOException
  224. */
  225. public static function getType()
  226. {
  227. $type = strtolower(sysconf('wechat_type'));
  228. if (in_array($type, ['api', 'thr'])) return $type;
  229. throw new \think\Exception('请在后台配置微信对接授权模式');
  230. }
  231. }