WechatService.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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) {
  163. return isset($config[$key]) ? $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('//').$notifyUrls[$scene] : url()->formatRoot('//').'/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('orders:'.$scene.':'.$openid.':unified', $unified, 600);
  424. $unified['sign'] = WechatService::getPaySign($unified);
  425. RedisService::set('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('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('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('orders:'.$scene.':'.$openid.':unified', $unified, 600);
  484. $unified['sign'] = WechatService::getPaySign($unified);
  485. RedisService::set('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('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('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. }
  659. return true;
  660. }
  661. /**
  662. * 请求接口
  663. * @param string $url 地址
  664. * @param string $postData xml参数
  665. * @param array $options
  666. * @return mixed
  667. */
  668. public static function curlPost($url = '', $postData = '', $options = array(), $cert=[])
  669. {
  670. if (is_array($postData)) {
  671. $postData = http_build_query($postData);
  672. }
  673. $ch = curl_init();
  674. curl_setopt($ch, CURLOPT_URL, $url);
  675. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  676. curl_setopt($ch, CURLOPT_POST, 1);
  677. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  678. curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  679. if (!empty($options)) {
  680. curl_setopt_array($ch, $options);
  681. }
  682. if($cert){
  683. curl_setopt($ch,CURLOPT_HEADER,FALSE);
  684. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
  685. if(isset($cert['cert_path']) && $cert['cert_path']){
  686. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  687. curl_setopt($ch,CURLOPT_SSLCERT, $cert['cert_path']);
  688. }
  689. if(isset($cert['key_path']) && $cert['key_path']) {
  690. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  691. curl_setopt($ch, CURLOPT_SSLKEY, $cert['key_path']);
  692. }
  693. }
  694. //https请求 不验证证书和host
  695. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  696. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  697. $data = curl_exec($ch);
  698. curl_close($ch);
  699. return $data;
  700. }
  701. /**
  702. * 数组转XML
  703. * @param $arr 数组数据
  704. * @return string
  705. */
  706. public static function arrayToXml($arr)
  707. {
  708. $xml = "<xml>";
  709. foreach ($arr as $key => $val) {
  710. if ($key == 'detail') {
  711. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  712. } else {
  713. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  714. }
  715. }
  716. $xml .= "</xml>";
  717. return $xml;
  718. }
  719. /**
  720. * 签名参数格式化
  721. * @param $paraMap 参数
  722. * @param bool $urlEncode 是否编码
  723. * @return bool|string
  724. */
  725. protected static function formatParams($paraMap, $urlEncode = false)
  726. {
  727. $buff = "";
  728. ksort($paraMap);
  729. foreach ($paraMap as $k => $v) {
  730. if (null != $v && "null" != $v) {
  731. if ($urlEncode) {
  732. $v = urlencode($v);
  733. }
  734. $buff .= $k . "=" . $v . "&";
  735. }
  736. }
  737. $reqPar = '';
  738. if (strlen($buff) > 0) {
  739. $reqPar = substr($buff, 0, strlen($buff) - 1);
  740. }
  741. return $reqPar;
  742. }
  743. /**
  744. * 生成微信二维码
  745. * @param int $sourceId 来源ID
  746. * @param $sceneStr 场景参数字符串或ID
  747. * @param $scene 场景标识:qrcode-用户二维码
  748. * @param string $qrType 二维码生成类型:QR_SCENE, QR_STR_SCENE, QR_LIMIT_SCENE, QR_LIMIT_STR_SCENE
  749. * @param int $expire 有效期,配合场景类型使用,临时二维码最长30天有效期,0-永久
  750. * @return array|bool
  751. * @throws \think\Exception
  752. * @throws \think\db\exception\DataNotFoundException
  753. * @throws \think\db\exception\ModelNotFoundException
  754. * @throws \think\exception\DbException
  755. * @throws \think\exception\PDOException
  756. */
  757. public static function makeQrcode($sourceId = 0, $sceneStr = '', $scene = 'qrcode', $qrType = 'QR_STR_SCENE', $expire = -1)
  758. {
  759. $expire = $expire>=0 ? $expire : 24 * 3600 * 20;
  760. $tokenData = WechatService::getAccessToken('');
  761. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  762. $qrData = db('qrcode')
  763. ->where(['source_id' => $sourceId, 'scene' => $scene, 'status' => 1])
  764. ->field('id,source_id,ticket,url,expire_at')
  765. ->find();
  766. $qrcodeId = isset($qrData['id']) ? $qrData['id'] : 0;
  767. $qrcodeExpire = isset($qrData['expire_at']) ? strtotime($qrData['expire_at']) : 0;
  768. if (($expire==0 && $qrcodeId) || $qrcodeExpire > time() && $qrcodeId) {
  769. $ticket = isset($qrData['ticket']) ? $qrData['ticket'] : '';
  770. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  771. $qrData['qrcode'] = WechatService::loadImage($qrcode, $scene);
  772. if($qrData['qrcode']){
  773. return $qrData;
  774. }
  775. }
  776. if (empty($token)) {
  777. $tokenData = WechatService::getAccessToken('', true);
  778. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  779. if (empty($token)) {
  780. return 1010;
  781. }
  782. }
  783. if (!in_array($qrType, ['QR_SCENE', 'QR_STR_SCENE', 'QR_LIMIT_SCENE', 'QR_LIMIT_STR_SCENE'])) {
  784. return 2111;
  785. }
  786. $data = [
  787. 'expire_seconds' => $expire,
  788. 'action_name' => $qrType,
  789. ];
  790. if (in_array($qrType, ['QR_SCENE', 'QR_LIMIT_SCENE'])) {
  791. $data['action_info'] = ['scene' => ['scene_id' => $sceneStr]];
  792. } else {
  793. $data['action_info'] = ['scene' => ['scene_str' => $scene . '_' . $sceneStr]];
  794. }
  795. $url = sprintf(self::$apiUrl['makeQrcode'], $token);
  796. $result = httpRequest($url, json_encode($data, 256));
  797. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  798. RedisService::set('qrcodes:result', ['url'=> $url, 'params'=> $data, 'result'=> $result], 600);
  799. if ($result && $ticket) {
  800. $qrData = [
  801. 'source_id' => $sourceId,
  802. 'scene' => $scene,
  803. 'scene_str' => $sceneStr,
  804. 'ticket' => $ticket,
  805. 'expire_at' => $expire>0? date('Y-m-d H:i:s', time() + $expire) : null,
  806. 'url' => isset($result['url']) ? $result['url'] : '',
  807. ];
  808. if ($qrcodeId) {
  809. $qrData['updated_at'] = date('Y-m-d H:i:s');
  810. //$qrcodeId = db('qrcode')->where(['id' => $qrcodeId])->update($qrData);
  811. } else {
  812. $qrData['created_at'] = date('Y-m-d H:i:s');
  813. //$qrcodeId = db('qrcode')->insertGetId($qrData);
  814. $qrData['id'] = $qrcodeId;
  815. }
  816. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  817. $qrData['qrcode'] = WechatService::loadImage($qrcode, $scene, true);
  818. }
  819. return $qrcodeId > 0 ? $qrData : 1009;
  820. }
  821. /**
  822. * 下载图片
  823. * @param $file 远程文件
  824. * @param string $type 类型
  825. * @return bool|string
  826. */
  827. public static function loadImage($file, $type='qrcode', $refresh=false){
  828. if(empty($file)){
  829. return false;
  830. }
  831. $key = "caches:members:{$type}:".md5($file);
  832. $qrcode = RedisService::get($key);
  833. if(empty($qrcode) || $refresh){
  834. $qrcodeContent = file_get_contents($file);
  835. if($qrcodeContent){
  836. if(!is_dir("upload/{$type}/weixin/")){
  837. mkdir("upload/{$type}/weixin/", 0755, true);
  838. }
  839. $qrcode = "{$type}/weixin/QR_".md5($file).'.jpg';
  840. file_put_contents("upload/".$qrcode, $qrcodeContent);
  841. RedisService::set($key, $qrcode, 7 * 24 * 3600);
  842. }
  843. }
  844. if(!file_exists('./upload/'.$qrcode)){
  845. return false;
  846. }
  847. return get_image_url($qrcode);
  848. }
  849. /**
  850. * 获取微信二维码数据
  851. * @param $where 条件
  852. * @param string $field 返回字段
  853. * @return bool
  854. * @throws \think\db\exception\DataNotFoundException
  855. * @throws \think\db\exception\ModelNotFoundException
  856. * @throws \think\exception\DbException
  857. */
  858. public static function getQrcode($where, $field = '')
  859. {
  860. if (!is_array($where)) {
  861. return false;
  862. }
  863. $where['status'] = 1;
  864. $field = $field ? $field : 'id,source_id,scene,ticket,url';
  865. $info = db('qrcode')
  866. ->where($where)
  867. ->where('expire_at', '>', date('Y-m-d H:i:s'))
  868. ->field($field)
  869. ->find();
  870. $ticket = isset($info['ticket']) ? $info['ticket'] : '';
  871. if ($info && $ticket) {
  872. $info['qrcode'] = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  873. }
  874. return $info;
  875. }
  876. /**
  877. * 响应消息
  878. * @param $postObj
  879. */
  880. public static function responseText($postObj)
  881. {
  882. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  883. $msgId = isset($postObj['MsgId']) ? $postObj['MsgId'] : '';
  884. $keyword = isset($postObj['Content']) ? trim($postObj['Content']) : '';
  885. $cacheKey = "messages:replys:{$msgId}";
  886. if(RedisService::get($cacheKey)){
  887. return false;
  888. }
  889. WechatService::rebackOk();
  890. echo ' ';
  891. exit;
  892. }
  893. /**
  894. * 响应消息
  895. * @param $fromUsername 发送用户
  896. * @param $toUsername 接收用户
  897. * @param $contentStr 发送内容
  898. * @param string $msgType 消息类型
  899. */
  900. public static function responseTplMsg($fromUsername, $toUsername, $contentStr, $msgType = 'text')
  901. {
  902. $textTpl = "<xml>
  903. <ToUserName><![CDATA[%s]]></ToUserName>
  904. <FromUserName><![CDATA[%s]]></FromUserName>
  905. <CreateTime>%s</CreateTime>
  906. <MsgType><![CDATA[%s]]></MsgType>
  907. <Content><![CDATA[%s]]></Content>
  908. </xml>";
  909. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
  910. echo $resultStr;
  911. exit;
  912. }
  913. /**
  914. * 创建菜单
  915. * @param array $menus 菜单数组数据
  916. * @params $delete 是否删除就菜单
  917. * @return bool
  918. */
  919. public static function createMenu($menus = [], $delete = false)
  920. {
  921. $weixinConfig = config('weixin.');
  922. $menus = $menus ? $menus : (isset($weixinConfig['menus']) ? $weixinConfig['menus'] : []);
  923. if (empty($menus)) {
  924. return false;
  925. }
  926. $tokenData = WechatService::getAccessToken('', 'accessToken');
  927. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  928. if (empty($token)) {
  929. return false;
  930. }
  931. // 删除菜单
  932. if ($delete) {
  933. WechatService::delMenu();
  934. }
  935. $url = sprintf(self::$apiUrl['createMenu'], $token);
  936. $result = httpRequest($url, json_encode(['button' => $menus], 256));
  937. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  938. if ($errorCode != 0) {
  939. return false;
  940. }
  941. return $result;
  942. }
  943. /**
  944. * 删除菜单
  945. * @return bool
  946. */
  947. public static function delMenu()
  948. {
  949. $tokenData = WechatService::getAccessToken('', 'accessToken');
  950. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  951. $url = sprintf(self::$apiUrl['delMenu'], $token);
  952. $result = httpRequest($url);
  953. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  954. if ($errorCode == 0) {
  955. return false;
  956. }
  957. return true;
  958. }
  959. /**
  960. * 查询菜单
  961. * @return bool
  962. */
  963. public static function getMenu()
  964. {
  965. $tokenData = WechatService::getAccessToken('', 'accessToken');
  966. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  967. $url = sprintf(self::$apiUrl['getMenu'], $token);
  968. $result = httpRequest($url);
  969. return $result;
  970. }
  971. /**
  972. * 发送客服消息
  973. * @param $openid 接受用户OPENID
  974. * @param $content 消息内容:数组
  975. * @param string $msgType 消息类型
  976. * @return mixed
  977. */
  978. public static function sendCustomMsg($openid, $content, $msgType = 'text')
  979. {
  980. $data = [
  981. 'touser' => $openid,
  982. 'msgtype' => $msgType,
  983. $msgType => $content
  984. ];
  985. $lockKey = 'caches:weixin:custonLock:' . $openid . '_' . md5(json_encode($data));
  986. if (RedisService::get($lockKey)) {
  987. return false;
  988. }
  989. $tokenData = WechatService::getAccessToken('');
  990. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  991. RedisService::set($lockKey, $data, 5);
  992. $url = sprintf(self::$apiUrl['customMessage'], $token);
  993. $result = httpRequest($url, json_encode($data, 256));
  994. RedisService::set('caches:weixin:customLock:' . $openid . '_' . date('YmdHis'), ['data' => $data, 'tokenData' => $tokenData, 'result' => $result], 3);
  995. return $result;
  996. }
  997. /**
  998. * 发送模板消息
  999. * @param $openid OPENID
  1000. * @param $params 参数:title-标题(必填),type-模板类型标识字符串(必填),keywords-模板字段数据(必填),url-模板跳转链接,remark-模板备注信息
  1001. * @return array|int
  1002. */
  1003. public static function sendTplMsg($openid, $params, $formatUrl=true)
  1004. {
  1005. $title = isset($params['title']) ? $params['title'] : '';
  1006. $remark = isset($params['remark']) ? $params['remark'] : '';
  1007. $type = isset($params['type']) ? $params['type'] : 'default';
  1008. $keywords = isset($params['keywords']) ? $params['keywords'] : [];
  1009. $keywords = $keywords ? $keywords : [];
  1010. if ($title) {
  1011. $keywords['first'] = ['value' => $title, 'color' => '#173177'];
  1012. }
  1013. if ($remark) {
  1014. $keywords['remark'] = ['value' => $remark, 'color' => '#173177'];
  1015. }
  1016. $configService = new ConfigService();
  1017. $templates = $configService->getConfigByGroup(10);
  1018. $templateId = isset($templates[$type]) ? trim($templates[$type]) : '';
  1019. if (empty($templateId)) {
  1020. return 2110;
  1021. }
  1022. ksort($keywords);
  1023. $tplData = [
  1024. 'touser' => $openid,
  1025. 'template_id' => $templateId,
  1026. 'data' => $keywords,
  1027. ];
  1028. $url = isset($params['url']) ? trim($params['url']) : '';
  1029. if ($url) {
  1030. $tplData['url'] = $formatUrl? WechatService::makeRedirectUrl($url) : $url;
  1031. }
  1032. // 删除旧数据,新增消息记录
  1033. $tokenData = WechatService::getAccessToken('');
  1034. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1035. if (empty($token)) {
  1036. return 1010;
  1037. }
  1038. $url = sprintf(self::$apiUrl['tplMessage'], $token);
  1039. $result = httpRequest($url, json_encode($tplData, 256));
  1040. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1041. RedisService::set('caches:messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1042. if ($code == 'ok') {
  1043. return true;
  1044. } else {
  1045. $result = httpRequest($url, json_encode($tplData, 256));
  1046. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1047. RedisService::set('caches:messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1048. if ($code === 0) {
  1049. return true;
  1050. }
  1051. }
  1052. return 2113;
  1053. }
  1054. /**
  1055. * 获取消息模板列表
  1056. * @return int|mixed
  1057. */
  1058. public static function getTemplateList(){
  1059. $tokenData = WechatService::getAccessToken('');
  1060. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1061. if (empty($token)) {
  1062. return 1010;
  1063. }
  1064. $url = sprintf(self::$apiUrl['templateList'], $token);
  1065. $result = httpRequest($url);
  1066. RedisService::set('caches:messages:templates', $result, 600);
  1067. return $result;
  1068. }
  1069. /**
  1070. * 生成普通参数二维码
  1071. * @param $str 参数
  1072. * @param bool $refresh 是否重新生成
  1073. * @return bool
  1074. */
  1075. public static function makeNormalQrcode($str, $refresh = false, $size = 8, $margin=2)
  1076. {
  1077. $qrFile = '/upload/qrcode/member/';
  1078. if (!is_dir($qrFile)) {
  1079. @mkdir('.' . $qrFile, 0755, true);
  1080. }
  1081. $qrFile = $qrFile . 'U_' . strtoupper(md5($str . '_' . $size)) . '.jpg';
  1082. if (is_file($qrFile) && !$refresh) {
  1083. return false;
  1084. }
  1085. $renderer = new ImageRenderer(
  1086. new RendererStyle(360),
  1087. new ImagickImageBackEnd()
  1088. );
  1089. $writer = new Writer($renderer);
  1090. $writer->writeFile($str, $qrFile);
  1091. if(!file_exists('.'.$qrFile)){
  1092. return false;
  1093. }
  1094. return $qrFile;
  1095. }
  1096. /**
  1097. * 返回给微信
  1098. */
  1099. public static function rebackOk(){
  1100. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  1101. exit;
  1102. }
  1103. }
  1104. ?>