WechatService.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. <?php
  2. namespace App\Services;
  3. use App\Models\FansModel;
  4. use App\Models\MemberModel;
  5. use BaconQrCode\Renderer\Image\ImagickImageBackEnd;
  6. use BaconQrCode\Renderer\ImageRenderer;
  7. use BaconQrCode\Renderer\RendererStyle\RendererStyle;
  8. use BaconQrCode\Writer;
  9. use Symfony\Component\Console\Input\Input;
  10. class WechatService extends BaseService
  11. {
  12. private static $apiUrl = [
  13. // 授权
  14. 'auth' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=xydc#besi_redirect',
  15. // 第三方
  16. 'qrConnect' => 'https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=SCOPE&state=STATE',
  17. // 永久ACCESS_TOKEN
  18. 'accessToken' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
  19. // 临时ACCESS_TOKEN
  20. 'tempToken' => 'https://api.weixin.qq.com/sns/oauth2/access_token?code=%s&appid=%s&secret=%s&grant_type=authorization_code',
  21. // 微信用户信息
  22. 'wxInfo' => 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN',
  23. // 获取userInfo
  24. 'userInfo' => 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN',
  25. // 统一下单
  26. 'unifiedorder' => 'https://api.mch.weixin.qq.com/pay/unifiedorder',
  27. // 原路退款接口
  28. 'refundOrder' => 'https://api.mch.weixin.qq.com/pay/unifiedorder',
  29. // 查询订单
  30. 'queryOrder' => 'https://api.mch.weixin.qq.com/pay/orderquery',
  31. // 企业付款到零钱
  32. 'transfers' => 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers',
  33. // 查询企业付款订单
  34. 'queryTransfer' => 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo',
  35. // 生成二维码
  36. 'makeQrcode' => 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s',
  37. // 换取二维码
  38. 'getQrcodeByTicket' => 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s',
  39. // 创建公众号菜单
  40. 'createMenu' => 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s',
  41. // 获取公众号菜单
  42. 'getMenu' => 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s',
  43. // 删除公众号菜单
  44. 'delMenu' => 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s',
  45. // 发送客服消息
  46. 'customMessage' => 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s',
  47. // 发送模板消息
  48. 'tplMessage' => 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s',
  49. // 获取消息模板列表
  50. 'templateList' => 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=%s',
  51. // 添加媒体素材
  52. 'uploadMedia' => 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s',
  53. // 生成短连接
  54. 'shortUrl' => 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s',
  55. // 清除接口限制
  56. 'clearTokenQuota'=> 'https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s',
  57. ];
  58. private static $jsApiUrl = [
  59. // jssdk 验证参数
  60. 'ticket' => 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=%s',
  61. // 永久TOKENresponseText
  62. 'token' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
  63. ];
  64. // 支付证书
  65. protected static $certPaths = [
  66. 'cert_path'=> WECHAT_PAY_CERT_PATH.'/apiclient_cert.pem',
  67. 'key_path'=> WECHAT_PAY_CERT_PATH.'/apiclient_key.pem',
  68. ];
  69. /**
  70. * 授权地址校验
  71. */
  72. public static function valid()
  73. {
  74. echo request()->get('echostr');
  75. exit;
  76. }
  77. /**
  78. * 微信注册初始化和授权登录
  79. */
  80. public static function auth()
  81. {
  82. $userInfo = WechatService::getWechatInfo('', true);
  83. $openid = isset($userInfo['openid'])? $userInfo['openid'] : '';
  84. $cacheKey = 'weixin:init:'.get_client_ip().'_'.$openid;
  85. if (empty($userInfo) || empty($openid)) {
  86. return false;
  87. }
  88. // 验证微信信息是否存在
  89. $wxData = [
  90. 'openid' => $openid,
  91. 'nickname' => isset($userInfo['nickname']) ? $userInfo['nickname'] : '',
  92. 'headimgurl' => isset($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '',
  93. 'sex' => isset($userInfo['sex']) ? $userInfo['sex'] : 0,
  94. 'country' => isset($userInfo['country']) ? $userInfo['country'] : '',
  95. 'province' => isset($userInfo['province']) ? $userInfo['province'] : '',
  96. 'city' => isset($userInfo['city']) ? $userInfo['city'] : '',
  97. ];
  98. // 用户信息
  99. $inviteId = request()->all('sid', 0);
  100. $inviteId = $inviteId? $inviteId : session('sid');
  101. $userData = [
  102. 'gender' => $wxData['sex'],
  103. 'openid' => $wxData['openid'],
  104. 'nickname' => $wxData['nickname'],
  105. 'login_time' => time(),
  106. 'login_ip' => get_client_ip(),
  107. 'avatar' => $wxData['headimgurl'],
  108. 'status'=> 1,
  109. ];
  110. // 微信用户不存在
  111. $userId = 0;
  112. $userInfo = MemberModel::select(['id','openid','avatar'])
  113. ->where(['openid' => $openid])
  114. ->where('status','>', 0)
  115. ->find();
  116. if (empty($userInfo)) {
  117. $userData['member_level'] = 1;
  118. $userData['invite_id'] = $inviteId;
  119. $userData['create_time'] = time();
  120. $userId = MemberModel::insertGetId($userData);
  121. } else{
  122. $updateData = [
  123. 'is_follow'=> isset($userInfo['subscribe']) ? intval($userInfo['subscribe']) : 0,
  124. 'login_time'=> time(),
  125. 'login_ip'=> get_client_ip(),
  126. 'update_time'=> time()
  127. ];
  128. MemberModel::where(['openid' => $openid])
  129. ->where('status','>=', 0)
  130. ->update($updateData);
  131. }
  132. // 记录OPENID
  133. $memberService = new MemberService();
  134. $field = ['id','openid','mobile','realname','login_time','status'];
  135. $userInfo = $memberService->getUserInfo(['openid' => $openid], $field);
  136. return $userInfo;
  137. }
  138. /**
  139. * 跳转授权
  140. * @param string $url 回跳地址
  141. * @return mixed
  142. */
  143. public static function makeRedirectUrl($url)
  144. {
  145. $appid = WechatService::getConfigs('wx_appid');
  146. return sprintf(self::$apiUrl['auth'], $appid, urlencode($url), 'snsapi_userinfo');
  147. }
  148. /**
  149. * 获取配置
  150. * @param string $key 键名
  151. * @return array|mixed|string
  152. */
  153. public static function getConfigs($key = '')
  154. {
  155. $configService = new ConfigService();
  156. $defConfig = config('weixin.');
  157. $config = $configService->getConfigByGroup(7);
  158. $config = $config ? $config : $defConfig;
  159. $config['notify'] = isset($defConfig['notify']) ? $defConfig['notify'] : [];
  160. if ($key) {
  161. return isset($config[$key]) ? $config[$key]['value'] : '';
  162. } else {
  163. return $config ? $config : [];
  164. }
  165. }
  166. /**
  167. * 获取ACCESS_TOKEN
  168. * @return bool|string
  169. */
  170. public static function getTempAccessToken($key = '', $refresh = false)
  171. {
  172. $code= request()->get('code','');
  173. $appid = WechatService::getConfigs('wx_appid');
  174. $appsecret = WechatService::getConfigs('wx_appsecret');
  175. $cacheKey = 'caches:tokens:access_temp:' . $code;
  176. $tokenData = RedisService::get($cacheKey);
  177. if (empty($tokenData) || $refresh) {
  178. $url = sprintf(self::$apiUrl['tempToken'], $code, $appid, $appsecret);
  179. $tokenData = httpRequest($url);
  180. RedisService::set("caches:tokens:result:temp_{$code}", $tokenData, 3600);
  181. $code = isset($tokenData['errcode']) ? $tokenData['errcode'] : '';
  182. if ($code || empty($tokenData)) {
  183. return $tokenData;
  184. }
  185. $token = isset($tokenData['access_token']) ? $tokenData['access_token'] : '';
  186. $openid = isset($tokenData['openid']) ? $tokenData['openid'] : '';
  187. $tokenData = [
  188. 'token' => $token,
  189. 'openid' => $openid,
  190. 'data' => $tokenData,
  191. 'date' => date('Y-m-d H:i:s'),
  192. 'expire' => time() + 7000,
  193. ];
  194. RedisService::set($cacheKey, $tokenData, 7200);
  195. }
  196. $expire = isset($tokenData['expire']) ? intval($tokenData['expire']) : 0;
  197. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  198. if (($expire && $expire < time()) || empty($token)) {
  199. $tokenData = WechatService::getTempAccessToken($key, true);
  200. }
  201. if ($key) {
  202. $tokenData = isset($tokenData[$key]) ? trim($tokenData[$key]) : '';
  203. }
  204. return $tokenData;
  205. }
  206. /**
  207. * 获取ACCESS_TOKEN
  208. * @return bool|string
  209. */
  210. public static function getAccessToken($key = '', $refresh = false)
  211. {
  212. $code= request()->get('code','');
  213. $code = $code? $code : session('code');
  214. session('code', $code);
  215. $appid = WechatService::getConfigs('wx_appid');
  216. $appsecret = WechatService::getConfigs('wx_appsecret');
  217. $cacheKey = 'caches:tokens:access_' . $appid . '_' . $appsecret;
  218. $tokenData = RedisService::get($cacheKey);
  219. if (empty($tokenData) || $refresh) {
  220. $url = sprintf(self::$apiUrl['accessToken'], $appid, $appsecret);
  221. $tokenData = httpRequest($url);
  222. RedisService::set("caches:tokens:result:{$code}", $tokenData, 3600);
  223. $code = isset($tokenData['errcode']) ? $tokenData['errcode'] : '';
  224. if ($code || empty($tokenData)) {
  225. return $tokenData;
  226. }
  227. $token = isset($tokenData['access_token']) ? $tokenData['access_token'] : '';
  228. $openid = isset($tokenData['openid']) ? $tokenData['openid'] : '';
  229. $tokenData = [
  230. 'token' => $token,
  231. 'openid' => $openid,
  232. 'data' => $tokenData,
  233. 'date' => date('Y-m-d H:i:s'),
  234. 'expire' => time() + 7000,
  235. ];
  236. RedisService::set($cacheKey, $tokenData, 7200);
  237. }
  238. $expire = isset($tokenData['expire']) ? intval($tokenData['expire']) : 0;
  239. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  240. if (($expire && $expire < time()) || empty($token)) {
  241. $tokenData = WechatService::getAccessToken($key, true);
  242. }
  243. if ($key) {
  244. $tokenData = isset($tokenData[$key]) ? trim($tokenData[$key]) : '';
  245. }
  246. return $tokenData;
  247. }
  248. /**
  249. * 获取微信UserInfo用户信息
  250. * @param string $openid 获取的用户OPENID,默认当前用户
  251. * @return mixed
  252. */
  253. public static function getWechatInfo($curOpenid = '', $saveData = false)
  254. {
  255. $code= request()->get('code','');
  256. $tokenData = WechatService::getTempAccessToken();
  257. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  258. $openid = isset($tokenData['openid']) ? trim($tokenData['openid']) : '';
  259. var_dump($tokenData);
  260. if (empty($token)) {
  261. return false;
  262. }
  263. $openid = $curOpenid ? $curOpenid : $openid;
  264. $url = sprintf(self::$apiUrl['wxInfo'], $token, $openid);
  265. RedisService::set("caches:userInfo:request_{$openid}",['token'=> $tokenData,'url'=> $url], 600);
  266. $result = httpRequest($url);
  267. $errcode = isset($result['errcode']) ? $result['errcode'] : '';
  268. RedisService::set('caches:weixin:userInfo:result_'.$openid, $result, 600);
  269. if (empty($result) || $errcode) {
  270. RedisService::keyDel('caches:tokens:access_temp:' . $code);
  271. return false;
  272. }
  273. if ($saveData) {
  274. $wxData = [
  275. 'openid' => $openid,
  276. 'nickname' => isset($result['nickname']) ? $result['nickname'] : '',
  277. 'headimgurl' => isset($result['headimgurl']) ? $result['headimgurl'] : '',
  278. 'sex' => isset($result['sex']) ? $result['sex'] : 0,
  279. 'country' => isset($result['country']) ? $result['country'] : '',
  280. 'province' => isset($result['province']) ? $result['province'] : '',
  281. 'city' => isset($result['city']) ? $result['city'] : '',
  282. ];
  283. if (empty(FansModel::where(['openid' => $openid])->value('id'))) {
  284. FansModel::insert($wxData);
  285. } else {
  286. FansModel::where(['openid' => $openid])->update($wxData);
  287. }
  288. }
  289. return $result;
  290. }
  291. /**
  292. * 获取JSSDK ticket参数
  293. * @author wesmiler
  294. */
  295. private static function getTicket($refresh = false, $refreshToken = false)
  296. {
  297. $appid = WechatService::getConfigs('wx_appid');
  298. $appsecret = WechatService::getConfigs('wx_appsecret');
  299. $cacheKey = 'caches:tokens:jsapiTicket:' . $appid . '_' . $appsecret;
  300. $ticketData = RedisService::get($cacheKey);
  301. $ticket = isset($ticketData['ticket']) ? $ticketData['ticket'] : '';
  302. if (empty($ticket) || $refresh) {
  303. $tokenData = WechatService::getAccessToken('', $refreshToken);
  304. $code = isset($tokenData['errcode']) ? $tokenData['errcode'] : '';
  305. if ($code) {
  306. return $tokenData;
  307. }
  308. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  309. $url = sprintf(self::$jsApiUrl['ticket'], $token);
  310. $result = httpRequest($url);
  311. if (empty($result)) {
  312. RedisService::set('caches:tokens:jsapiTicket_error', $result, 3600);
  313. return false;
  314. }
  315. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  316. $ticketData = [
  317. 'ticket' => $ticket,
  318. 'expire' => time() + 6000,
  319. ];
  320. RedisService::set($cacheKey, $ticketData, 7200);
  321. }
  322. $expire = isset($ticketData['expire']) ? intval($ticketData['expire']) : 0;
  323. if (empty($expire) || $expire < time()) {
  324. $ticket = WechatService::getTicket(true);
  325. }
  326. if (empty($ticket)) {
  327. $ticket = WechatService::getTicket(true, true);
  328. }
  329. return $ticket;
  330. }
  331. /**
  332. * 获取JSSDK签名参数
  333. * @param string $url 请求地址
  334. * @return array
  335. */
  336. public static function getJssdkParams($url = '')
  337. {
  338. // token请求次数超出警告范围
  339. $countKey = "token:count";
  340. $requestCount = RedisService::get($countKey);
  341. if($requestCount>=5000){
  342. return ['error'=> 'token请求失败次数已超出警告值5000'];
  343. }
  344. $countKey = "token:ticketCount:".get_client_ip();
  345. $requestCount = RedisService::get($countKey);
  346. if($requestCount>=100){
  347. return ['error'=> '分享参数请求次数过多请稍后重试'];
  348. }
  349. $result = WechatService::getTicket();
  350. $url = $url ? $url : Input::url();
  351. $code = isset($result['errcode']) ? $result['errcode'] : '';
  352. if ($code) {
  353. return $result;
  354. }
  355. $params = [
  356. 'jsapi_ticket' => $result,
  357. 'noncestr' => uniqid('J'),
  358. 'timestamp' => time(),
  359. 'url' => $url,
  360. ];
  361. RedisService::set($countKey, $requestCount+1, 30);
  362. $signature = WechatService::getJssdkSign($params);
  363. return [
  364. 'wx_appid' => WechatService::getConfigs('wx_appid'),
  365. 'timestamp' => $params['timestamp'],
  366. 'nonceStr' => $params['noncestr'],
  367. 'signature' => $signature,
  368. 'url' => $url,
  369. ];
  370. }
  371. /**
  372. * 获取JSSDK 签名
  373. * @param $params 签名参数
  374. * @return string
  375. */
  376. private static function getJssdkSign($params)
  377. {
  378. $str = [];
  379. ksort($params);
  380. foreach ($params as $k => $val) {
  381. $str[] = $k . '=' . $val;
  382. }
  383. $str = implode('&', $str);
  384. return sha1($str);
  385. }
  386. /**
  387. * jsapi统一下单
  388. * @param $order 订单参数
  389. * @author wesmiler
  390. * @return array
  391. */
  392. public static function jsapiUnifiedorder($order, $scene = 'jsapiPay')
  393. {
  394. $appId = WechatService::getConfigs('wx_appid');
  395. $mchId = WechatService::getConfigs('wx_mch_id');
  396. $notifyUrls = WechatService::getConfigs('notify');
  397. $notifyUrl = isset($notifyUrls[$scene]) ? url()->formatRoot('//').$notifyUrls[$scene] : url()->formatRoot('//').'/api/notify/pay/index';
  398. $openid = isset($order['openid']) ? trim($order['openid']) : '';
  399. $orderNo = isset($order['orderNo']) ? trim($order['orderNo']) : '';
  400. $totalFee = isset($order['amount']) ? moneyFormat($order['amount']) : 0.00;
  401. // 测试支付金额
  402. $payDebug = config('weixin.payDebug');
  403. if ($payDebug) {
  404. $totalFee = 0.01;
  405. }
  406. if (empty($openid) || empty($orderNo) || empty($totalFee)) {
  407. return ['code' => 'error', 'message' => '参数错误'];
  408. }
  409. $unified = array(
  410. 'appid' => $appId,
  411. 'attach' => 'pay', //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
  412. 'body' => isset($order['body']) ? trim($order['body']) : '订单支付',
  413. 'mch_id' => $mchId,
  414. 'nonce_str' => WechatService::createNonceStr(),
  415. 'notify_url' => $notifyUrl,
  416. 'openid' => $openid, //rade_type=JSAPI,此参数必传
  417. 'out_trade_no' => $orderNo,
  418. 'spbill_create_ip' => get_client_ip(),
  419. 'total_fee' => intval($totalFee * 100), //单位 转为分
  420. 'trade_type' => 'JSAPI',
  421. );
  422. RedisService::set('orders:'.$scene.':'.$openid.':unified', $unified, 600);
  423. $unified['sign'] = WechatService::getPaySign($unified);
  424. RedisService::set('orders:'.$scene.':'.$openid.':unifiedSign', $unified, 600);
  425. $url = !empty(self::$apiUrl['unifiedorder']) ? trim(self::$apiUrl['unifiedorder']) : 'https://api.mch.weixin.qq.com/pay/unifiedorder';
  426. $data = WechatService::arrayToXml($unified);
  427. RedisService::set('orders:'.$scene.':'.$openid.':unifiedXml', ['data'=> $unified,'result'=> $data], 600);
  428. $responseXml = WechatService::curlPost($url, $data);
  429. //禁止引用外部xml实体
  430. libxml_disable_entity_loader(true);
  431. $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  432. $unifiedOrder = (array)$unifiedOrder;
  433. RedisService::set('orders:'.$scene.':'.$openid.':unifiedResult', ['data'=> $unifiedOrder,'result'=> $data], 600);
  434. if ($unifiedOrder === false) {
  435. return ['code' => 'exception', 'message' => 'parase xml error'];
  436. }
  437. if (isset($unifiedOrder['return_code']) && $unifiedOrder['return_code'] != 'SUCCESS') {
  438. return ['code' => 'error', 'message' => $unifiedOrder['return_msg']];
  439. }
  440. if (isset($unifiedOrder['result_code']) && $unifiedOrder['result_code'] != 'SUCCESS') {
  441. return ['code' => 'error', 'message' => $unifiedOrder['err_code']];
  442. }
  443. // 返回支付参数
  444. return WechatService::getJsapiPareams($unifiedOrder, $unified);
  445. }
  446. /**
  447. * 提现打款
  448. * @param $order
  449. * @param string $scene
  450. * @return array|string[]
  451. */
  452. public static function transferOrder($order, $scene='withdraw'){
  453. $appId = WechatService::getConfigs('wx_appid');
  454. $mchId = WechatService::getConfigs('wx_mch_id');
  455. $openid = isset($order['openid']) ? trim($order['openid']) : '';
  456. $orderNo = isset($order['orderNo']) ? trim($order['orderNo']) : '';
  457. $totalFee = isset($order['amount']) ? moneyFormat($order['amount']) : 0.00;
  458. // 测试支付金额
  459. $payDebug = config('weixin.payDebug');
  460. if ($payDebug) {
  461. $totalFee = 0.3;
  462. }
  463. if (empty($openid) || empty($orderNo) || empty($totalFee)) {
  464. return ['code' => 'error', 'message' => '参数错误'];
  465. }
  466. $unified = array(
  467. 'mch_appid' => $appId,
  468. 'mchid' => trim($mchId),
  469. 'device_info' => uniqid(),
  470. 'nonce_str' => WechatService::createNonceStr(),
  471. 'partner_trade_no' => $orderNo,
  472. 'openid' => $openid,
  473. 'check_name' => isset($order['check_name']) && $order['check_name']? trim($order['check_name']) : 'NO_CHECK', // 是否校验真实姓名
  474. 'amount' => intval($totalFee * 100), //单位 转为分
  475. 'desc' => isset($order['body']) ? trim($order['body']) : '余额提现',
  476. 'spbill_create_ip' => get_client_ip(),
  477. );
  478. // 是否校验真实姓名
  479. if($unified['check_name'] == 'FORCE_CHECK'){
  480. $unified['re_user_name'] = isset($order['real_name']) ? trim($order['real_name']) : '';
  481. }
  482. RedisService::set('orders:'.$scene.':'.$openid.':unified', $unified, 600);
  483. $unified['sign'] = WechatService::getPaySign($unified);
  484. RedisService::set('orders:'.$scene.':'.$openid.':unifiedSign', $unified, 600);
  485. $url = !empty(self::$apiUrl['transfers']) ? trim(self::$apiUrl['transfers']) : 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  486. $data = WechatService::arrayToXml($unified);
  487. RedisService::set('orders:'.$scene.':'.$openid.':unifiedXml', ['data'=> $unified,'result'=> $data], 600);
  488. $responseXml = WechatService::curlPost($url, $data, [], self::$certPaths);
  489. //禁止引用外部xml实体
  490. libxml_disable_entity_loader(true);
  491. $result = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  492. $result = (array)$result;
  493. RedisService::set('orders:'.$scene.':'.$openid.':unifiedResult', ['data'=> $result,'result'=> $data], 600);
  494. if ($result === false) {
  495. return ['code' => 'exception', 'message' => 'parase xml error'];
  496. }
  497. if (isset($result['return_code']) && $result['return_code'] != 'SUCCESS') {
  498. return ['code' => 'error', 'message' => WechatService::getError($result['return_msg']),'type'=>'return_code'];
  499. }
  500. if (isset($result['result_code']) && $result['result_code'] != 'SUCCESS') {
  501. return ['code' => 'error', 'message' => $result['err_code_des'],'error_code'=> $result['err_code'],'type'=>'result_code'];
  502. }
  503. return $result;
  504. }
  505. /**
  506. * 查询企业付款订单
  507. * @param $trane_order_no 订单号
  508. * @return string[]
  509. */
  510. public static function queryTransferOrder($trane_order_no){
  511. $appId = WechatService::getConfigs('wx_appid');
  512. $mchId = WechatService::getConfigs('wx_mch_id');
  513. if (empty($trane_order_no)) {
  514. return ['code' => 'error', 'message' => '参数错误'];
  515. }
  516. $unified = array(
  517. 'wx_appid' => $appId,
  518. 'wx_mch_id' => trim($mchId),
  519. 'nonce_str' => WechatService::createNonceStr(),
  520. 'partner_trade_no' => $trane_order_no,
  521. );
  522. RedisService::set('orders:transfer:'.$trane_order_no.':unified', $unified, 600);
  523. $unified['sign'] = WechatService::getPaySign($unified);
  524. RedisService::set('orders:transfer:'.$trane_order_no.':unifiedSign', $unified, 600);
  525. $url = !empty(self::$apiUrl['queryTransfer']) ? trim(self::$apiUrl['queryTransfer']) : 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo';
  526. $data = WechatService::arrayToXml($unified);
  527. RedisService::set('orders:transfer:'.$trane_order_no.':unifiedXml', ['data'=> $unified,'result'=> $data], 600);
  528. $responseXml = WechatService::curlPost($url, $data, [], self::$certPaths);
  529. //禁止引用外部xml实体
  530. libxml_disable_entity_loader(true);
  531. $result = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  532. $result = (array)$result;
  533. RedisService::set('orders:transfer:'.$trane_order_no.':unifiedResult', ['data'=> $result,'result'=> $data], 600);
  534. if ($result === false) {
  535. return ['code' => 'exception', 'message' => 'parase xml error'];
  536. }
  537. if (isset($result['return_code']) && $result['return_code'] != 'SUCCESS') {
  538. return ['code' => 'error', 'message' => WechatService::getError($result['return_msg']),'type'=>'return_code'];
  539. }
  540. if (isset($result['result_code']) && $result['result_code'] != 'SUCCESS') {
  541. return ['code' => 'error', 'message' => $result['err_code_des'],'error_code'=> $result['err_code'],'type'=>'result_code'];
  542. }
  543. return $result;
  544. }
  545. /**
  546. * 获取JSAPI支付签名参数
  547. * @param $unifiedOrder 统一下单结果
  548. * @param array $unified 提交统一下单参数
  549. * @return array
  550. */
  551. public static function getJsapiPareams($unifiedOrder, $unified = [])
  552. {
  553. $time = time();
  554. $prepayId = isset($unifiedOrder['prepay_id']) ? $unifiedOrder['prepay_id'] : '';
  555. $params = array(
  556. "appId" => WechatService::getConfigs('wx_appid'),
  557. "timeStamp" => "$time", //这里是字符串的时间戳,不是int,所以需加引号
  558. "nonceStr" => isset($unified['nonce_str']) ? trim($unified['nonce_str']) : WechatService::createNonceStr(),
  559. "package" => "prepay_id=" . $prepayId,
  560. "signType" => 'MD5',
  561. );
  562. // 重签名
  563. $params['sign'] = WechatService::getPaySign($params);
  564. $params['prepay_id'] = $prepayId;
  565. return $params;
  566. }
  567. /**
  568. * 查询订单
  569. * @param $outTradeNo 单号
  570. * @return bool|\SimpleXMLElement
  571. */
  572. public static function queryOrder($outTradeNo)
  573. {
  574. $params['wx_appid'] = WechatService::getConfigs('wx_appid');
  575. $params['wx_mch_id'] = WechatService::getConfigs('wx_mch_id');
  576. $params['nonce_str'] = WechatService::createNonceStr();
  577. $params['out_trade_no'] = $outTradeNo;
  578. //获取签名数据
  579. $params['sign'] = WechatService::getPaySign($params);
  580. $responseXml = WechatService::curlPost(self::$apiUrl['queryOrder'], WechatService::arrayToXml($params));
  581. $result = WechatService::xmlToArray($responseXml);
  582. $returnCode = isset($result['return_code']) ? $result['return_code'] : '';
  583. $tradState = isset($result['trade_state']) ? $result['trade_state'] : '';
  584. $resultCode = isset($result['result_code']) ? $result['result_code'] : '';
  585. if ($resultCode && $returnCode && $tradState) {
  586. return $result;
  587. } else {
  588. return false;
  589. }
  590. }
  591. /**
  592. * XML转数组
  593. * @param $xml
  594. * @return bool|\SimpleXMLElement
  595. */
  596. private static function xmlToArray($xml)
  597. {
  598. if (empty($xml)) return false;
  599. libxml_disable_entity_loader(true);
  600. return simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  601. }
  602. /**
  603. * 生成随机字符串
  604. * @param int $length 长度
  605. * @return string
  606. */
  607. public static function createNonceStr($length = 16)
  608. {
  609. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  610. $str = '';
  611. for ($i = 0; $i < $length; $i++) {
  612. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  613. }
  614. return $str;
  615. }
  616. /**
  617. * @param $params
  618. * @param $key
  619. * @return string
  620. */
  621. public static function getPaySign($params, $key = '')
  622. {
  623. ksort($params, SORT_STRING);
  624. $key = $key ? $key : WechatService::getConfigs('wx_pay_key');
  625. $taskNo = isset($params['out_trade_no']) ? trim($params['out_trade_no']) : md5(json_encode($params));
  626. $unSignParaString = WechatService::formatParams($params, false);
  627. $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
  628. return $signStr;
  629. }
  630. /**
  631. * 验证JSAPI回调
  632. * @param $notifyData
  633. * @return array|bool
  634. */
  635. public static function checkJsapiNotify($notifyData)
  636. {
  637. if (empty($notifyData)) {
  638. return ['code' => 'error', 'message' => 'parse xml error'];
  639. }
  640. $orderNo = isset($notifyData['out_trade_no']) ? trim($notifyData['out_trade_no']) : '';
  641. $returnCode = isset($notifyData['return_code']) ? trim($notifyData['return_code']) : '';
  642. $resultCode = isset($notifyData['result_code']) ? trim($notifyData['result_code']) : '';
  643. $nofitySign = isset($notifyData['sign']) ? trim($notifyData['sign']) : '';
  644. if ($returnCode != 'SUCCESS') {
  645. $error = isset($notifyData['return_msg']) ? $notifyData['return_msg'] : '';
  646. return ['code' => 'error', 'message' => $error];
  647. }
  648. if ($resultCode != 'SUCCESS') {
  649. $error = isset($notifyData['err_code']) ? $notifyData['err_code'] : '';
  650. return ['code' => 'error', 'message' => $error];
  651. }
  652. // 验证签名
  653. unset($notifyData['sign']);
  654. $sign = WechatService::getPaySign($notifyData);
  655. if ($nofitySign == $sign) {
  656. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  657. }
  658. return true;
  659. }
  660. /**
  661. * 请求接口
  662. * @param string $url 地址
  663. * @param string $postData xml参数
  664. * @param array $options
  665. * @return mixed
  666. */
  667. public static function curlPost($url = '', $postData = '', $options = array(), $cert=[])
  668. {
  669. if (is_array($postData)) {
  670. $postData = http_build_query($postData);
  671. }
  672. $ch = curl_init();
  673. curl_setopt($ch, CURLOPT_URL, $url);
  674. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  675. curl_setopt($ch, CURLOPT_POST, 1);
  676. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  677. curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  678. if (!empty($options)) {
  679. curl_setopt_array($ch, $options);
  680. }
  681. if($cert){
  682. curl_setopt($ch,CURLOPT_HEADER,FALSE);
  683. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
  684. if(isset($cert['cert_path']) && $cert['cert_path']){
  685. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  686. curl_setopt($ch,CURLOPT_SSLCERT, $cert['cert_path']);
  687. }
  688. if(isset($cert['key_path']) && $cert['key_path']) {
  689. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  690. curl_setopt($ch, CURLOPT_SSLKEY, $cert['key_path']);
  691. }
  692. }
  693. //https请求 不验证证书和host
  694. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  695. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  696. $data = curl_exec($ch);
  697. curl_close($ch);
  698. return $data;
  699. }
  700. /**
  701. * 数组转XML
  702. * @param $arr 数组数据
  703. * @return string
  704. */
  705. public static function arrayToXml($arr)
  706. {
  707. $xml = "<xml>";
  708. foreach ($arr as $key => $val) {
  709. if ($key == 'detail') {
  710. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  711. } else {
  712. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  713. }
  714. }
  715. $xml .= "</xml>";
  716. return $xml;
  717. }
  718. /**
  719. * 签名参数格式化
  720. * @param $paraMap 参数
  721. * @param bool $urlEncode 是否编码
  722. * @return bool|string
  723. */
  724. protected static function formatParams($paraMap, $urlEncode = false)
  725. {
  726. $buff = "";
  727. ksort($paraMap);
  728. foreach ($paraMap as $k => $v) {
  729. if (null != $v && "null" != $v) {
  730. if ($urlEncode) {
  731. $v = urlencode($v);
  732. }
  733. $buff .= $k . "=" . $v . "&";
  734. }
  735. }
  736. $reqPar = '';
  737. if (strlen($buff) > 0) {
  738. $reqPar = substr($buff, 0, strlen($buff) - 1);
  739. }
  740. return $reqPar;
  741. }
  742. /**
  743. * 生成微信二维码
  744. * @param int $sourceId 来源ID
  745. * @param $sceneStr 场景参数字符串或ID
  746. * @param $scene 场景标识:qrcode-用户二维码
  747. * @param string $qrType 二维码生成类型:QR_SCENE, QR_STR_SCENE, QR_LIMIT_SCENE, QR_LIMIT_STR_SCENE
  748. * @param int $expire 有效期,配合场景类型使用,临时二维码最长30天有效期,0-永久
  749. * @return array|bool
  750. * @throws \think\Exception
  751. * @throws \think\db\exception\DataNotFoundException
  752. * @throws \think\db\exception\ModelNotFoundException
  753. * @throws \think\exception\DbException
  754. * @throws \think\exception\PDOException
  755. */
  756. public static function makeQrcode($sourceId = 0, $sceneStr = '', $scene = 'qrcode', $qrType = 'QR_STR_SCENE', $expire = -1)
  757. {
  758. $expire = $expire>=0 ? $expire : 24 * 3600 * 20;
  759. $tokenData = WechatService::getAccessToken('');
  760. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  761. $qrData = db('qrcode')
  762. ->where(['source_id' => $sourceId, 'scene' => $scene, 'status' => 1])
  763. ->field('id,source_id,ticket,url,expire_at')
  764. ->find();
  765. $qrcodeId = isset($qrData['id']) ? $qrData['id'] : 0;
  766. $qrcodeExpire = isset($qrData['expire_at']) ? strtotime($qrData['expire_at']) : 0;
  767. if (($expire==0 && $qrcodeId) || $qrcodeExpire > time() && $qrcodeId) {
  768. $ticket = isset($qrData['ticket']) ? $qrData['ticket'] : '';
  769. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  770. $qrData['qrcode'] = WechatService::loadImage($qrcode, $scene);
  771. if($qrData['qrcode']){
  772. return $qrData;
  773. }
  774. }
  775. if (empty($token)) {
  776. $tokenData = WechatService::getAccessToken('', true);
  777. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  778. if (empty($token)) {
  779. return 1010;
  780. }
  781. }
  782. if (!in_array($qrType, ['QR_SCENE', 'QR_STR_SCENE', 'QR_LIMIT_SCENE', 'QR_LIMIT_STR_SCENE'])) {
  783. return 2111;
  784. }
  785. $data = [
  786. 'expire_seconds' => $expire,
  787. 'action_name' => $qrType,
  788. ];
  789. if (in_array($qrType, ['QR_SCENE', 'QR_LIMIT_SCENE'])) {
  790. $data['action_info'] = ['scene' => ['scene_id' => $sceneStr]];
  791. } else {
  792. $data['action_info'] = ['scene' => ['scene_str' => $scene . '_' . $sceneStr]];
  793. }
  794. $url = sprintf(self::$apiUrl['makeQrcode'], $token);
  795. $result = httpRequest($url, json_encode($data, 256));
  796. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  797. RedisService::set('qrcodes:result', ['url'=> $url, 'params'=> $data, 'result'=> $result], 600);
  798. if ($result && $ticket) {
  799. $qrData = [
  800. 'source_id' => $sourceId,
  801. 'scene' => $scene,
  802. 'scene_str' => $sceneStr,
  803. 'ticket' => $ticket,
  804. 'expire_at' => $expire>0? date('Y-m-d H:i:s', time() + $expire) : null,
  805. 'url' => isset($result['url']) ? $result['url'] : '',
  806. ];
  807. if ($qrcodeId) {
  808. $qrData['updated_at'] = date('Y-m-d H:i:s');
  809. //$qrcodeId = db('qrcode')->where(['id' => $qrcodeId])->update($qrData);
  810. } else {
  811. $qrData['created_at'] = date('Y-m-d H:i:s');
  812. //$qrcodeId = db('qrcode')->insertGetId($qrData);
  813. $qrData['id'] = $qrcodeId;
  814. }
  815. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  816. $qrData['qrcode'] = WechatService::loadImage($qrcode, $scene, true);
  817. }
  818. return $qrcodeId > 0 ? $qrData : 1009;
  819. }
  820. /**
  821. * 下载图片
  822. * @param $file 远程文件
  823. * @param string $type 类型
  824. * @return bool|string
  825. */
  826. public static function loadImage($file, $type='qrcode', $refresh=false){
  827. if(empty($file)){
  828. return false;
  829. }
  830. $key = "caches:members:{$type}:".md5($file);
  831. $qrcode = RedisService::get($key);
  832. if(empty($qrcode) || $refresh){
  833. $qrcodeContent = file_get_contents($file);
  834. if($qrcodeContent){
  835. if(!is_dir("upload/{$type}/weixin/")){
  836. mkdir("upload/{$type}/weixin/", 0755, true);
  837. }
  838. $qrcode = "{$type}/weixin/QR_".md5($file).'.jpg';
  839. file_put_contents("upload/".$qrcode, $qrcodeContent);
  840. RedisService::set($key, $qrcode, 7 * 24 * 3600);
  841. }
  842. }
  843. if(!file_exists('./upload/'.$qrcode)){
  844. return false;
  845. }
  846. return get_image_url($qrcode);
  847. }
  848. /**
  849. * 获取微信二维码数据
  850. * @param $where 条件
  851. * @param string $field 返回字段
  852. * @return bool
  853. * @throws \think\db\exception\DataNotFoundException
  854. * @throws \think\db\exception\ModelNotFoundException
  855. * @throws \think\exception\DbException
  856. */
  857. public static function getQrcode($where, $field = '')
  858. {
  859. if (!is_array($where)) {
  860. return false;
  861. }
  862. $where['status'] = 1;
  863. $field = $field ? $field : 'id,source_id,scene,ticket,url';
  864. $info = db('qrcode')
  865. ->where($where)
  866. ->where('expire_at', '>', date('Y-m-d H:i:s'))
  867. ->field($field)
  868. ->find();
  869. $ticket = isset($info['ticket']) ? $info['ticket'] : '';
  870. if ($info && $ticket) {
  871. $info['qrcode'] = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  872. }
  873. return $info;
  874. }
  875. /**
  876. * 响应消息
  877. * @param $postObj
  878. */
  879. public static function responseText($postObj)
  880. {
  881. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  882. $msgId = isset($postObj['MsgId']) ? $postObj['MsgId'] : '';
  883. $keyword = isset($postObj['Content']) ? trim($postObj['Content']) : '';
  884. $cacheKey = "messages:replys:{$msgId}";
  885. if(RedisService::get($cacheKey)){
  886. return false;
  887. }
  888. WechatService::rebackOk();
  889. echo ' ';
  890. exit;
  891. }
  892. /**
  893. * 响应消息
  894. * @param $fromUsername 发送用户
  895. * @param $toUsername 接收用户
  896. * @param $contentStr 发送内容
  897. * @param string $msgType 消息类型
  898. */
  899. public static function responseTplMsg($fromUsername, $toUsername, $contentStr, $msgType = 'text')
  900. {
  901. $textTpl = "<xml>
  902. <ToUserName><![CDATA[%s]]></ToUserName>
  903. <FromUserName><![CDATA[%s]]></FromUserName>
  904. <CreateTime>%s</CreateTime>
  905. <MsgType><![CDATA[%s]]></MsgType>
  906. <Content><![CDATA[%s]]></Content>
  907. </xml>";
  908. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
  909. echo $resultStr;
  910. exit;
  911. }
  912. /**
  913. * 创建菜单
  914. * @param array $menus 菜单数组数据
  915. * @params $delete 是否删除就菜单
  916. * @return bool
  917. */
  918. public static function createMenu($menus = [], $delete = false)
  919. {
  920. $weixinConfig = config('weixin.');
  921. $menus = $menus ? $menus : (isset($weixinConfig['menus']) ? $weixinConfig['menus'] : []);
  922. if (empty($menus)) {
  923. return false;
  924. }
  925. $tokenData = WechatService::getAccessToken('', 'accessToken');
  926. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  927. if (empty($token)) {
  928. return false;
  929. }
  930. // 删除菜单
  931. if ($delete) {
  932. WechatService::delMenu();
  933. }
  934. $url = sprintf(self::$apiUrl['createMenu'], $token);
  935. $result = httpRequest($url, json_encode(['button' => $menus], 256));
  936. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  937. if ($errorCode != 0) {
  938. return false;
  939. }
  940. return $result;
  941. }
  942. /**
  943. * 删除菜单
  944. * @return bool
  945. */
  946. public static function delMenu()
  947. {
  948. $tokenData = WechatService::getAccessToken('', 'accessToken');
  949. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  950. $url = sprintf(self::$apiUrl['delMenu'], $token);
  951. $result = httpRequest($url);
  952. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  953. if ($errorCode == 0) {
  954. return false;
  955. }
  956. return true;
  957. }
  958. /**
  959. * 查询菜单
  960. * @return bool
  961. */
  962. public static function getMenu()
  963. {
  964. $tokenData = WechatService::getAccessToken('', 'accessToken');
  965. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  966. $url = sprintf(self::$apiUrl['getMenu'], $token);
  967. $result = httpRequest($url);
  968. return $result;
  969. }
  970. /**
  971. * 发送客服消息
  972. * @param $openid 接受用户OPENID
  973. * @param $content 消息内容:数组
  974. * @param string $msgType 消息类型
  975. * @return mixed
  976. */
  977. public static function sendCustomMsg($openid, $content, $msgType = 'text')
  978. {
  979. $data = [
  980. 'touser' => $openid,
  981. 'msgtype' => $msgType,
  982. $msgType => $content
  983. ];
  984. $lockKey = 'caches:weixin:custonLock:' . $openid . '_' . md5(json_encode($data));
  985. if (RedisService::get($lockKey)) {
  986. return false;
  987. }
  988. $tokenData = WechatService::getAccessToken('');
  989. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  990. RedisService::set($lockKey, $data, 5);
  991. $url = sprintf(self::$apiUrl['customMessage'], $token);
  992. $result = httpRequest($url, json_encode($data, 256));
  993. RedisService::set('caches:weixin:customLock:' . $openid . '_' . date('YmdHis'), ['data' => $data, 'tokenData' => $tokenData, 'result' => $result], 3);
  994. return $result;
  995. }
  996. /**
  997. * 发送模板消息
  998. * @param $openid OPENID
  999. * @param $params 参数:title-标题(必填),type-模板类型标识字符串(必填),keywords-模板字段数据(必填),url-模板跳转链接,remark-模板备注信息
  1000. * @return array|int
  1001. */
  1002. public static function sendTplMsg($openid, $params, $formatUrl=true)
  1003. {
  1004. $title = isset($params['title']) ? $params['title'] : '';
  1005. $remark = isset($params['remark']) ? $params['remark'] : '';
  1006. $type = isset($params['type']) ? $params['type'] : 'default';
  1007. $keywords = isset($params['keywords']) ? $params['keywords'] : [];
  1008. $keywords = $keywords ? $keywords : [];
  1009. if ($title) {
  1010. $keywords['first'] = ['value' => $title, 'color' => '#173177'];
  1011. }
  1012. if ($remark) {
  1013. $keywords['remark'] = ['value' => $remark, 'color' => '#173177'];
  1014. }
  1015. $configService = new ConfigService();
  1016. $templates = $configService->getConfigByGroup(10);
  1017. $templateId = isset($templates[$type]) ? trim($templates[$type]) : '';
  1018. if (empty($templateId)) {
  1019. return 2110;
  1020. }
  1021. ksort($keywords);
  1022. $tplData = [
  1023. 'touser' => $openid,
  1024. 'template_id' => $templateId,
  1025. 'data' => $keywords,
  1026. ];
  1027. $url = isset($params['url']) ? trim($params['url']) : '';
  1028. if ($url) {
  1029. $tplData['url'] = $formatUrl? WechatService::makeRedirectUrl($url) : $url;
  1030. }
  1031. // 删除旧数据,新增消息记录
  1032. $tokenData = WechatService::getAccessToken('');
  1033. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1034. if (empty($token)) {
  1035. return 1010;
  1036. }
  1037. $url = sprintf(self::$apiUrl['tplMessage'], $token);
  1038. $result = httpRequest($url, json_encode($tplData, 256));
  1039. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1040. RedisService::set('caches:messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1041. if ($code == 'ok') {
  1042. return true;
  1043. } else {
  1044. $result = httpRequest($url, json_encode($tplData, 256));
  1045. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1046. RedisService::set('caches:messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1047. if ($code === 0) {
  1048. return true;
  1049. }
  1050. }
  1051. return 2113;
  1052. }
  1053. /**
  1054. * 获取消息模板列表
  1055. * @return int|mixed
  1056. */
  1057. public static function getTemplateList(){
  1058. $tokenData = WechatService::getAccessToken('');
  1059. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1060. if (empty($token)) {
  1061. return 1010;
  1062. }
  1063. $url = sprintf(self::$apiUrl['templateList'], $token);
  1064. $result = httpRequest($url);
  1065. RedisService::set('caches:messages:templates', $result, 600);
  1066. return $result;
  1067. }
  1068. /**
  1069. * 生成普通参数二维码
  1070. * @param $str 参数
  1071. * @param bool $refresh 是否重新生成
  1072. * @return bool
  1073. */
  1074. public static function makeNormalQrcode($str, $refresh = false, $size = 8, $margin=2)
  1075. {
  1076. $qrFile = '/upload/qrcode/member/';
  1077. if (!is_dir($qrFile)) {
  1078. @mkdir('.' . $qrFile, 0755, true);
  1079. }
  1080. $qrFile = $qrFile . 'U_' . strtoupper(md5($str . '_' . $size)) . '.jpg';
  1081. if (is_file($qrFile) && !$refresh) {
  1082. return false;
  1083. }
  1084. $renderer = new ImageRenderer(
  1085. new RendererStyle(360),
  1086. new ImagickImageBackEnd()
  1087. );
  1088. $writer = new Writer($renderer);
  1089. $writer->writeFile($str, $qrFile);
  1090. if(!file_exists('.'.$qrFile)){
  1091. return false;
  1092. }
  1093. return $qrFile;
  1094. }
  1095. /**
  1096. * 返回给微信
  1097. */
  1098. public static function rebackOk(){
  1099. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  1100. exit;
  1101. }
  1102. }
  1103. ?>