WechatService.php 46 KB

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