WechatService.php 54 KB

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