WechatService.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. /**
  16. * 微信处理管理
  17. * Class WechatService
  18. * @package app\wechat\service
  19. *
  20. * ----- WeOpen for Open -----
  21. * @method \WeOpen\Login login() static 第三方微信登录
  22. * @method \WeOpen\Service service() static 第三方服务
  23. *
  24. * ----- WeMini for Open -----
  25. * @method \WeMini\Code WeMiniCode() static 小程序代码管理
  26. * @method \WeMini\User WeMiniUser() static 小程序帐号管理
  27. * @method \WeMini\Basic WeMiniBasic() static 小程序基础信息
  28. * @method \WeMini\Domain WeMiniDomain() static 小程序域名管理
  29. * @method \WeMini\Tester WeMiniTester() static 小程序成员管理
  30. * @method \WeMini\Account WeMiniAccount() static 小程序账号管理
  31. *
  32. * ----- ThinkService -----
  33. * @method mixed wechat() static 第三方微信工具
  34. */
  35. class WechatService extends \We
  36. {
  37. /**
  38. * 获取微信支付配置
  39. * @param array|null $options
  40. * @return array
  41. * @throws \think\Exception
  42. * @throws \think\exception\PDOException
  43. */
  44. public static function config($options = null)
  45. {
  46. if (empty($options)) $options = [
  47. // 微信功能必需参数
  48. 'appid' => self::getAppid(),
  49. 'token' => sysconf('wechat_token'),
  50. 'appsecret' => sysconf('wechat_appsecret'),
  51. 'encodingaeskey' => sysconf('wechat_encodingaeskey'),
  52. // 微信支付必要参数
  53. 'mch_id' => sysconf('wechat_mch_id'),
  54. 'mch_key' => sysconf('wechat_mch_key'),
  55. 'cache_path' => env('runtime_path') . 'wechat' . DIRECTORY_SEPARATOR,
  56. ];
  57. if (sysconf('wechat_mch_ssl_type') === 'p12') {
  58. $options['ssl_p12'] = self::_parseCertPath(sysconf('wechat_mch_ssl_p12'));
  59. } else {
  60. $options['ssl_key'] = self::_parseCertPath(sysconf('wechat_mch_ssl_key'));
  61. $options['ssl_cer'] = self::_parseCertPath(sysconf('wechat_mch_ssl_cer'));
  62. }
  63. return parent::config($options);
  64. }
  65. /**
  66. * 解析证书路径
  67. * @param string $path
  68. * @return mixed
  69. * @throws \think\Exception
  70. */
  71. private static function _parseCertPath($path)
  72. {
  73. if (preg_match('|^[a-z0-9]{16,16}\/[a-z0-9]{16,16}\.|i', $path)) {
  74. return \library\File::instance('local')->path($path, true);
  75. }
  76. return $path;
  77. }
  78. /**
  79. * 静态魔术加载方法
  80. * @param string $name 静态类名
  81. * @param array $arguments 参数集合
  82. * @return mixed
  83. * @throws \SoapFault
  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 (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. }
  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. } elseif (class_exists('SoapClient')) {
  132. $location = config('wechat.service_url') . "/service/api.client/soap/{$token}";
  133. return new \SoapClient(null, ['uri' => strtolower($name), 'location' => $location]);
  134. } else {
  135. throw new \think\Exception("Yar or Soap extensions are not installed.");
  136. }
  137. }
  138. /**
  139. * 获取微信网页JSSDK
  140. * @param string $url JS签名地址
  141. * @return array
  142. * @throws \WeChat\Exceptions\InvalidResponseException
  143. * @throws \WeChat\Exceptions\LocalCacheException
  144. * @throws \think\Exception
  145. * @throws \think\exception\PDOException
  146. */
  147. public static function getWebJssdkSign($url = null)
  148. {
  149. $url = is_null($url) ? request()->url(true) : $url;
  150. if (self::getType() === 'api') {
  151. return self::WeChatScript()->getJsSign($url);
  152. } else {
  153. return self::wechat()->jsSign($url);
  154. }
  155. }
  156. /**
  157. * 初始化进入授权
  158. * @param string $url 授权页面URL地址
  159. * @param integer $isfull 授权微信模式
  160. * @param boolean $isRedirect 是否进行跳转
  161. * @return array
  162. * @throws \WeChat\Exceptions\InvalidResponseException
  163. * @throws \WeChat\Exceptions\LocalCacheException
  164. * @throws \think\Exception
  165. * @throws \think\exception\PDOException
  166. */
  167. public static function getWebOauthInfo($url, $isfull = 0, $isRedirect = true)
  168. {
  169. $appid = self::getAppid();
  170. list($openid, $fansinfo) = [session("{$appid}_openid"), session("{$appid}_fansinfo")];
  171. if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($fansinfo))) {
  172. empty($fansinfo) || FansService::set($fansinfo);
  173. return ['openid' => $openid, 'fansinfo' => $fansinfo];
  174. }
  175. if (self::getType() === 'api') {
  176. $wechat = self::WeChatOauth();
  177. if (request()->get('state') !== $appid) {
  178. $snsapi = empty($isfull) ? 'snsapi_base' : 'snsapi_userinfo';
  179. $param = (strpos($url, '?') !== false ? '&' : '?') . 'rcode=' . encode($url);
  180. $OauthUrl = $wechat->getOauthRedirect($url . $param, $appid, $snsapi);
  181. if ($isRedirect) redirect($OauthUrl, [], 301)->send();
  182. exit("window.location.href='{$OauthUrl}'");
  183. }
  184. if (($token = $wechat->getOauthAccessToken()) && isset($token['openid'])) {
  185. session("{$appid}_openid", $openid = $token['openid']);
  186. if (empty($isfull) && request()->get('rcode')) {
  187. redirect(decode(request()->get('rcode')), [], 301)->send();
  188. }
  189. session("{$appid}_fansinfo", $fansinfo = $wechat->getUserInfo($token['access_token'], $openid));
  190. empty($fansinfo) || FansService::set($fansinfo);
  191. }
  192. redirect(decode(request()->get('rcode')), [], 301)->send();
  193. } else {
  194. $result = self::wechat()->oauth(session_id(), $url, $isfull);
  195. session("{$appid}_openid", $openid = $result['openid']);
  196. session("{$appid}_fansinfo", $fansinfo = $result['fans']);
  197. if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($fansinfo))) {
  198. empty($fansinfo) || FansService::set($fansinfo);
  199. return ['openid' => $openid, 'fansinfo' => $fansinfo];
  200. }
  201. if ($isRedirect && !empty($result['url'])) {
  202. redirect($result['url'], [], 301)->send();
  203. }
  204. exit("window.location.href='{$result['url']}'");
  205. }
  206. }
  207. /**
  208. * 获取当前微信APPID
  209. * @return bool|string
  210. * @throws \think\Exception
  211. * @throws \think\exception\PDOException
  212. */
  213. public static function getAppid()
  214. {
  215. if (self::getType() === 'api') {
  216. return sysconf('wechat_appid');
  217. } else {
  218. return sysconf('wechat_thr_appid');
  219. }
  220. }
  221. /**
  222. * 获取接口授权模式
  223. * @return string
  224. * @throws \think\Exception
  225. * @throws \think\exception\PDOException
  226. */
  227. public static function getType()
  228. {
  229. $type = strtolower(sysconf('wechat_type'));
  230. if (in_array($type, ['api', 'thr'])) return $type;
  231. throw new \think\Exception('请在后台配置微信对接授权模式');
  232. }
  233. }