WechatService.php 46 KB

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