WechatService.php 46 KB

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