WechatService.php 54 KB

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