MpService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <?php
  2. namespace App\Services;
  3. /**
  4. * 微信服务管理-服务类
  5. * @author laravel开发员
  6. * @since 2020/11/11
  7. * Class WechatService
  8. * @package App\Services
  9. */
  10. class MpService extends BaseService
  11. {
  12. // 静态对象
  13. protected static $instance = null;
  14. protected $debug = true;
  15. protected $expireTime = 7200; // 缓存日志时长
  16. protected $mpAppid = '';
  17. protected $mpAppSecret = '';
  18. protected $corpid = '';
  19. protected $corpsecret = '';
  20. // 接口地址
  21. protected $apiUrls = [
  22. // 授权登录
  23. 'auth'=> 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
  24. // 授权跳转地址
  25. 'authorize'=>'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect',
  26. // 获取token
  27. 'getToken'=>'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
  28. // 获取二维码
  29. 'getQrcode'=>'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s&scene=%s&page=%s&env_version=%s',
  30. // 获取用户信息
  31. 'getUserInfo'=>'https://api.weixin.qq.com/sns/jscode2session',
  32. // 获取手机号
  33. 'getPhoneNumber'=>'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s',
  34. // 获取客服token
  35. 'getServiceToken'=>'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s',
  36. // 获取客服地址
  37. 'getServiceUrl'=>'https://qyapi.weixin.qq.com/cgi-bin/kf/add_contact_way?access_token=%s',
  38. ];
  39. public function __construct()
  40. {
  41. $this->mpAppid = ConfigService::make()->getConfigByCode('wechat_mp_appid');
  42. $this->mpAppSecret = ConfigService::make()->getConfigByCode('wechat_mp_appsecret');
  43. $this->corpid = ConfigService::make()->getConfigByCode('wechat_corpid');
  44. $this->corpsecret = ConfigService::make()->getConfigByCode('wechat_corpsecret');
  45. }
  46. /**
  47. * 静态入口
  48. * @return static|null
  49. */
  50. public static function make()
  51. {
  52. if (!self::$instance) {
  53. self::$instance = new static();
  54. }
  55. return self::$instance;
  56. }
  57. /**
  58. * web 授权
  59. * @param $code
  60. * @return array|false|mixed|string|string[]
  61. */
  62. public function auth($code)
  63. {
  64. try {
  65. if(empty($this->mpAppid) || empty($this->mpAppSecret)){
  66. $this->error = '小程序参数未配置';
  67. return false;
  68. }
  69. // 没有code参数
  70. if(empty($code)){
  71. $uri=urlencode(env("WEB_URL")."/v1/mpAuth");
  72. $state=get_random_code(16);
  73. $url= sprintf($this->apiUrls['authorize'], $this->mpAppid, $this->mpAppSecret, $uri, $state);
  74. return redirect($url);
  75. }
  76. $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
  77. $url = sprintf($this->apiUrls['auth'],$this->mpAppid, $this->mpAppSecret, $code);
  78. $result = httpRequest($url, '', 'get','',5);
  79. $this->saveLog($cacheKey.'auth:request', ['url'=>$url,'code'=>$code,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
  80. if(empty($result)){
  81. $this->error = '授权登录失败';
  82. return "<script>alert('微信授权失败');window.close()</script>";
  83. }
  84. return $result;
  85. }catch (\Exception $e){
  86. $this->error = $e->getMessage();
  87. $this->saveLog($cacheKey.'auth:error', ['code'=>$code,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
  88. return false;
  89. }
  90. }
  91. /**
  92. * 获取 access_token
  93. * @param false $refresh
  94. * @return false|mixed|string
  95. */
  96. public function getAccessToken($refresh = false)
  97. {
  98. try {
  99. if(empty($this->mpAppid) || empty($this->mpAppSecret)){
  100. $this->error = '小程序参数未配置';
  101. return false;
  102. }
  103. $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
  104. $tokenData = RedisService::get($cacheKey.'access_token');
  105. $token = isset($tokenData['access_token'])? $tokenData['access_token'] : '';
  106. if($token && !$refresh){
  107. return $token;
  108. }
  109. $url = sprintf($this->apiUrls['getToken'], $this->mpAppid, $this->mpAppSecret);
  110. $result = httpRequest($url,'', 'get','',5);
  111. $this->saveLog($cacheKey.'tokens:request', ['url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
  112. $token = isset($result['access_token'])? $result['access_token'] : '';
  113. if(empty($result) || empty($token)){
  114. $this->error = '获取小程序TOKEN失败';
  115. return false;
  116. }
  117. $result['date'] = date('Y-m-d H:i:s');
  118. RedisService::set($cacheKey.'access_token', $result, 7000);
  119. return $token;
  120. }catch (\Exception $e){
  121. $this->error = $e->getMessage();
  122. $this->saveLog($cacheKey.'tokens:error', ['error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
  123. return false;
  124. }
  125. }
  126. /**
  127. * 小程序二维码
  128. * @param $page 页面
  129. * @param $scene 场景参数
  130. * @param string $version 类型:release-永久
  131. * @param false $refresh
  132. * @return false|string
  133. */
  134. public function getMiniQrcode($page, $scene, $version='release', $refresh=false)
  135. {
  136. if (!in_array($version,['release','trial','develop'])) {
  137. $version='release';
  138. }
  139. try {
  140. if(empty($page) || empty($scene)){
  141. $this->error = '缺少二维码参数';
  142. return false;
  143. }
  144. if(empty($this->mpAppid) || empty($this->mpAppSecret)){
  145. $this->error = '小程序参数未配置';
  146. return false;
  147. }
  148. if(!$token = $this->getAccessToken())
  149. {
  150. $this->error = '获取token失败';
  151. return false;
  152. }
  153. $cacheKey = "caches:mpQrcode:mp_{$this->mpAppid}:";
  154. $filePath = base_path('public/uploads');
  155. $qrFile = '/qrcodes/mp_'.date("YmdHis")."_".md5($page.$scene).".png";
  156. $qrKey = md5($qrFile);
  157. if(RedisService::get($cacheKey.$qrKey) && file_exists($filePath.'/'.$qrFile) && !$refresh){
  158. return $qrFile;
  159. }
  160. if(!is_dir($filePath.'/qrcodes/')){
  161. @mkdirs($filePath.'/qrcodes/');
  162. }
  163. $url = sprintf($this->apiUrls['getQrcode'], $token, $scene, $page, $version);
  164. $result = curl_post($url, '');
  165. $datas = $result? json_decode($result, true) : [];
  166. $this->saveLog($cacheKey.'qrcode:request', ['page'=>$page,'scene'=>$scene,'url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
  167. $errcode = isset($datas['errcode'])? $datas['errcode'] : '';
  168. $errmsg = isset($datas['errmsg'])? $datas['errmsg'] : '';
  169. if($errcode){
  170. $this->error = $errmsg? $errmsg : '获取二维码失败';
  171. return false;
  172. }
  173. file_put_contents($filePath.'/'.$qrFile, $result);
  174. if(!file_exists($filePath.'/'.$qrFile)){
  175. $this->error = '保存二维码失败';
  176. return false;
  177. }
  178. $result['date'] = date('Y-m-d H:i:s');
  179. RedisService::set($cacheKey.$qrKey, ['page'=>$page,'scene'=>$scene,'qrcode'=>$qrFile,'date'=>date('Y-m-d H:i:s')], 30 * 86400);
  180. return $qrFile;
  181. }catch (\Exception $e){
  182. $this->error = $e->getMessage();
  183. $this->saveLog($cacheKey.'qrcode:error', ['page'=>$page,'scene'=>$scene,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
  184. return false;
  185. }
  186. }
  187. /**
  188. * 获取用户信息
  189. * @param $code
  190. * @return array|false|mixed|string[]
  191. */
  192. public function getUserinfo($code)
  193. {
  194. try {
  195. if(empty($code)){
  196. $this->error = '缺少授权参数';
  197. return false;
  198. }
  199. if(empty($this->mpAppid) || empty($this->mpAppSecret)){
  200. $this->error = '小程序参数未配置';
  201. return false;
  202. }
  203. $data=[
  204. 'appid' => $this->mpAppid,
  205. 'secret'=> $this->mpAppSecret,
  206. 'js_code'=>$code,
  207. 'grant_type'=>'authorization_code'
  208. ];
  209. $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
  210. $url = $this->apiUrls['getUserInfo'];
  211. $result = httpRequest($url, $data,'get','',5);
  212. $this->saveLog($cacheKey.'userInfo:request', ['code'=>$code,'url'=>$url,'query'=>$data,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
  213. if(empty($result)){
  214. $this->error = '获取用户信息失败';
  215. return false;
  216. }
  217. return $result;
  218. }catch (\Exception $e){
  219. $this->error = $e->getMessage();
  220. $this->saveLog($cacheKey.'userInfo:error', ['code'=>$code,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
  221. return false;
  222. }
  223. }
  224. /**
  225. * 获取用户手机号码
  226. * @param $code
  227. * @return array|false|mixed|string[]
  228. */
  229. public function getPhoneNumber($code)
  230. {
  231. try {
  232. if(empty($code)){
  233. $this->error = '缺少授权参数';
  234. return false;
  235. }
  236. if(empty($this->mpAppid) || empty($this->mpAppSecret)){
  237. $this->error = '小程序参数未配置';
  238. return false;
  239. }
  240. if(!$token = $this->getAccessToken())
  241. {
  242. $this->error = '获取token失败';
  243. return false;
  244. }
  245. $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
  246. $url = sprintf($this->apiUrls['getPhoneNumber'], $token);
  247. $result = httpRequest($url, json_encode(['code'=>$code],256),'post','',5);
  248. $this->saveLog($cacheKey.'phone:request', ['code'=>$code,'url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
  249. if(empty($result)){
  250. $this->error = '获取用户手机号失败';
  251. return false;
  252. }
  253. return $result;
  254. }catch (\Exception $e){
  255. $this->error = $e->getMessage();
  256. $this->saveLog($cacheKey.'phone:error', ['code'=>$code,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
  257. return false;
  258. }
  259. }
  260. /**
  261. * 获取 客服接口 access_token
  262. * @param false $refresh
  263. * @return false|mixed|string
  264. */
  265. public function getServiceToken($refresh = false)
  266. {
  267. try {
  268. if(empty($this->mpAppid) || empty($this->mpAppSecret)){
  269. $this->error = '小程序参数未配置';
  270. return false;
  271. }
  272. $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
  273. $tokenData = RedisService::get($cacheKey.'kf_access_token');
  274. $token = isset($tokenData['access_token'])? $tokenData['access_token'] : '';
  275. if($token && !$refresh){
  276. return $token;
  277. }
  278. $url = sprintf($this->apiUrls['getServiceToken'], $this->mpAppid, $this->mpAppSecret);
  279. $result = httpRequest($url,'', 'get','',5);
  280. $this->saveLog($cacheKey.'kfTokens:request', ['url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
  281. $token = isset($result['access_token'])? $result['access_token'] : '';
  282. if(empty($result) || empty($token)){
  283. $this->error = '获取小程序客服TOKEN失败';
  284. return false;
  285. }
  286. $result['date'] = date('Y-m-d H:i:s');
  287. RedisService::set($cacheKey.'kf_access_token', $result, 7000);
  288. return $token;
  289. }catch (\Exception $e){
  290. $this->error = $e->getMessage();
  291. $this->saveLog($cacheKey.'kfTokens:error', ['error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
  292. return false;
  293. }
  294. }
  295. /**
  296. * 获取客服地址
  297. * @return array|false|mixed|string[]
  298. */
  299. public function getServiceUrl()
  300. {
  301. try {
  302. if(empty($this->mpAppid) || empty($this->mpAppSecret)){
  303. $this->error = '小程序参数未配置';
  304. return false;
  305. }
  306. if(!$token = $this->getServiceToken())
  307. {
  308. $this->error = '获取token失败';
  309. return false;
  310. }
  311. $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
  312. $url = sprintf($this->apiUrls['getServiceUrl'], $token);
  313. $result = httpRequest($url, '','post','',5);
  314. $this->saveLog($cacheKey.'service:request', ['url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
  315. if(empty($result)){
  316. $this->error = '获取小程序客服地址失败';
  317. return false;
  318. }
  319. return $result;
  320. }catch (\Exception $e){
  321. $this->error = $e->getMessage();
  322. $this->saveLog($cacheKey.'service:error', ['error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
  323. return false;
  324. }
  325. }
  326. /**
  327. * 保存日志
  328. * @param $cackekey
  329. * @param $data
  330. * @param $time
  331. */
  332. public function saveLog($cackekey, $data, $time=0)
  333. {
  334. if($this->debug){
  335. RedisService::set($cackekey, $data, $time?$time : $this->expireTime);
  336. }
  337. }
  338. }