WechatService.php 57 KB

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