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