WechatService.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  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, $notifyData=[])
  764. {
  765. $tradeState = isset($notifyData['trade_state'])? $notifyData['trade_state'] : false;
  766. if($notifyData && $tradeState != 'SUCCESS'){
  767. return false;
  768. }
  769. $transaction_id = isset($notifyData['transaction_id'])? $notifyData['transaction_id'] : '';
  770. if($notifyData && empty($transaction_id)){
  771. return false;
  772. }
  773. return true;
  774. $sign = stripslashes($sign);
  775. var_dump($signStr);
  776. var_dump($sign);
  777. var_dump($notifyData);
  778. $signature = base64_decode($sign);
  779. $publicKey = openssl_pkey_get_public(file_get_contents(self::$certPaths['cert_path']));
  780. return openssl_verify($signStr, $signature, $publicKey, 'sha256WithRSAEncryption');
  781. }
  782. /**
  783. * 验证JSAPI回调
  784. * @param $notifyData
  785. * @return array|bool
  786. */
  787. public static function checkJsapiNotify($notifyData)
  788. {
  789. if (empty($notifyData)) {
  790. return ['code' => 'error', 'message' => 'parse xml error'];
  791. }
  792. $returnCode = isset($notifyData['return_code']) ? trim($notifyData['return_code']) : '';
  793. $resultCode = isset($notifyData['result_code']) ? trim($notifyData['result_code']) : '';
  794. $nofitySign = isset($notifyData['sign']) ? trim($notifyData['sign']) : '';
  795. if ($returnCode != 'SUCCESS') {
  796. $error = isset($notifyData['return_msg']) ? $notifyData['return_msg'] : '';
  797. return ['code' => 'error', 'message' => $error];
  798. }
  799. if ($resultCode != 'SUCCESS') {
  800. $error = isset($notifyData['err_code']) ? $notifyData['err_code'] : '';
  801. return ['code' => 'error', 'message' => $error];
  802. }
  803. // 验证签名
  804. unset($notifyData['sign']);
  805. $sign = WechatService::getPaySign($notifyData);
  806. if ($nofitySign == $sign) {
  807. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  808. return true;
  809. }
  810. return false;
  811. }
  812. /**
  813. * 请求接口
  814. * @param string $url 地址
  815. * @param string $postData xml参数
  816. * @param array $options
  817. * @return mixed
  818. */
  819. public static function curlPost($url = '', $postData = '', $options = array(), $cert=[], $headers=[])
  820. {
  821. if (is_array($postData)) {
  822. $postData = http_build_query($postData);
  823. }
  824. $ch = curl_init();
  825. curl_setopt($ch, CURLOPT_URL, $url);
  826. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  827. curl_setopt($ch, CURLOPT_POST, 1);
  828. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  829. curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  830. if (!empty($options)) {
  831. curl_setopt_array($ch, $options);
  832. }
  833. if($headers){
  834. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  835. }
  836. if($cert){
  837. curl_setopt($ch,CURLOPT_HEADER,FALSE);
  838. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
  839. if(isset($cert['cert_path']) && $cert['cert_path']){
  840. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  841. curl_setopt($ch,CURLOPT_SSLCERT, $cert['cert_path']);
  842. }
  843. if(isset($cert['key_path']) && $cert['key_path']) {
  844. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  845. curl_setopt($ch, CURLOPT_SSLKEY, $cert['key_path']);
  846. }
  847. }
  848. //https请求 不验证证书和host
  849. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  850. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  851. $data = curl_exec($ch);
  852. curl_close($ch);
  853. return $data;
  854. }
  855. /**
  856. * 数组转XML
  857. * @param $arr 数组数据
  858. * @return string
  859. */
  860. public static function arrayToXml($arr)
  861. {
  862. $xml = "<xml>";
  863. foreach ($arr as $key => $val) {
  864. if ($key == 'detail') {
  865. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  866. } else {
  867. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  868. }
  869. }
  870. $xml .= "</xml>";
  871. return $xml;
  872. }
  873. /**
  874. * 签名参数格式化
  875. * @param $paraMap 参数
  876. * @param bool $urlEncode 是否编码
  877. * @return bool|string
  878. */
  879. protected static function formatParams($paraMap, $urlEncode = false)
  880. {
  881. $buff = "";
  882. ksort($paraMap);
  883. foreach ($paraMap as $k => $v) {
  884. if (null != $v && "null" != $v) {
  885. if ($urlEncode) {
  886. $v = urlencode($v);
  887. }
  888. $buff .= $k . "=" . $v . "&";
  889. }
  890. }
  891. $reqPar = '';
  892. if (strlen($buff) > 0) {
  893. $reqPar = substr($buff, 0, strlen($buff) - 1);
  894. }
  895. return $reqPar;
  896. }
  897. /**
  898. * 生成微信二维码
  899. * @param int $sourceId 来源ID
  900. * @param $sceneStr 场景参数字符串或ID
  901. * @param $scene 场景标识:qrcode-用户二维码
  902. * @param string $qrType 二维码生成类型:QR_SCENE, QR_STR_SCENE, QR_LIMIT_SCENE, QR_LIMIT_STR_SCENE
  903. * @param int $expire 有效期,配合场景类型使用,临时二维码最长30天有效期,0-永久
  904. * @return array|bool
  905. * @throws \think\Exception
  906. * @throws \think\db\exception\DataNotFoundException
  907. * @throws \think\db\exception\ModelNotFoundException
  908. * @throws \think\exception\DbException
  909. * @throws \think\exception\PDOException
  910. */
  911. public static function makeQrcode($sourceId = 0, $sceneStr = '', $scene = 'qrcode', $qrType = 'QR_STR_SCENE', $expire = -1)
  912. {
  913. $expire = $expire>=0 ? $expire : 24 * 3600 * 20;
  914. $tokenData = WechatService::getAccessToken('');
  915. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  916. $qrData = db('qrcode')
  917. ->where(['source_id' => $sourceId, 'scene' => $scene, 'status' => 1])
  918. ->field('id,source_id,ticket,url,expire_at')
  919. ->find();
  920. $qrcodeId = isset($qrData['id']) ? $qrData['id'] : 0;
  921. $qrcodeExpire = isset($qrData['expire_at']) ? strtotime($qrData['expire_at']) : 0;
  922. if (($expire==0 && $qrcodeId) || $qrcodeExpire > time() && $qrcodeId) {
  923. $ticket = isset($qrData['ticket']) ? $qrData['ticket'] : '';
  924. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  925. $qrData['qrcode'] = WechatService::loadImage($qrcode, $scene);
  926. if($qrData['qrcode']){
  927. return $qrData;
  928. }
  929. }
  930. if (empty($token)) {
  931. $tokenData = WechatService::getAccessToken('', true);
  932. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  933. if (empty($token)) {
  934. return 1010;
  935. }
  936. }
  937. if (!in_array($qrType, ['QR_SCENE', 'QR_STR_SCENE', 'QR_LIMIT_SCENE', 'QR_LIMIT_STR_SCENE'])) {
  938. return 2111;
  939. }
  940. $data = [
  941. 'expire_seconds' => $expire,
  942. 'action_name' => $qrType,
  943. ];
  944. if (in_array($qrType, ['QR_SCENE', 'QR_LIMIT_SCENE'])) {
  945. $data['action_info'] = ['scene' => ['scene_id' => $sceneStr]];
  946. } else {
  947. $data['action_info'] = ['scene' => ['scene_str' => $scene . '_' . $sceneStr]];
  948. }
  949. $url = sprintf(self::$apiUrl['makeQrcode'], $token);
  950. $result = httpRequest($url, json_encode($data, 256));
  951. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  952. RedisService::set('qrcodes:result', ['url'=> $url, 'params'=> $data, 'result'=> $result], 600);
  953. if ($result && $ticket) {
  954. $qrData = [
  955. 'source_id' => $sourceId,
  956. 'scene' => $scene,
  957. 'scene_str' => $sceneStr,
  958. 'ticket' => $ticket,
  959. 'expire_at' => $expire>0? date('Y-m-d H:i:s', time() + $expire) : null,
  960. 'url' => isset($result['url']) ? $result['url'] : '',
  961. ];
  962. if ($qrcodeId) {
  963. $qrData['updated_at'] = date('Y-m-d H:i:s');
  964. //$qrcodeId = db('qrcode')->where(['id' => $qrcodeId])->update($qrData);
  965. } else {
  966. $qrData['created_at'] = date('Y-m-d H:i:s');
  967. //$qrcodeId = db('qrcode')->insertGetId($qrData);
  968. $qrData['id'] = $qrcodeId;
  969. }
  970. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  971. $qrData['qrcode'] = WechatService::loadImage($qrcode, $scene, true);
  972. }
  973. return $qrcodeId > 0 ? $qrData : 1009;
  974. }
  975. /**
  976. * 下载图片
  977. * @param $file 远程文件
  978. * @param string $type 类型
  979. * @return bool|string
  980. */
  981. public static function loadImage($file, $type='qrcode', $refresh=false){
  982. if(empty($file)){
  983. return false;
  984. }
  985. $key = "caches:members:{$type}:".md5($file);
  986. $qrcode = RedisService::get($key);
  987. if(empty($qrcode) || $refresh){
  988. $qrcodeContent = file_get_contents($file);
  989. if($qrcodeContent){
  990. if(!is_dir("upload/{$type}/weixin/")){
  991. mkdir("upload/{$type}/weixin/", 0755, true);
  992. }
  993. $qrcode = "{$type}/weixin/QR_".md5($file).'.jpg';
  994. file_put_contents("upload/".$qrcode, $qrcodeContent);
  995. RedisService::set($key, $qrcode, 7 * 24 * 3600);
  996. }
  997. }
  998. if(!file_exists('./upload/'.$qrcode)){
  999. return false;
  1000. }
  1001. return get_image_url($qrcode);
  1002. }
  1003. /**
  1004. * 获取微信二维码数据
  1005. * @param $where 条件
  1006. * @param string $field 返回字段
  1007. * @return bool
  1008. * @throws \think\db\exception\DataNotFoundException
  1009. * @throws \think\db\exception\ModelNotFoundException
  1010. * @throws \think\exception\DbException
  1011. */
  1012. public static function getQrcode($where, $field = '')
  1013. {
  1014. if (!is_array($where)) {
  1015. return false;
  1016. }
  1017. $where['status'] = 1;
  1018. $field = $field ? $field : 'id,source_id,scene,ticket,url';
  1019. $info = db('qrcode')
  1020. ->where($where)
  1021. ->where('expire_at', '>', date('Y-m-d H:i:s'))
  1022. ->field($field)
  1023. ->find();
  1024. $ticket = isset($info['ticket']) ? $info['ticket'] : '';
  1025. if ($info && $ticket) {
  1026. $info['qrcode'] = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  1027. }
  1028. return $info;
  1029. }
  1030. /**
  1031. * 响应消息
  1032. * @param $postObj
  1033. */
  1034. public static function responseText($postObj)
  1035. {
  1036. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  1037. $msgId = isset($postObj['MsgId']) ? $postObj['MsgId'] : '';
  1038. $keyword = isset($postObj['Content']) ? trim($postObj['Content']) : '';
  1039. $cacheKey = "messages:replys:{$msgId}";
  1040. if(RedisService::get($cacheKey)){
  1041. return false;
  1042. }
  1043. WechatService::rebackOk();
  1044. echo ' ';
  1045. exit;
  1046. }
  1047. /**
  1048. * 响应消息
  1049. * @param $fromUsername 发送用户
  1050. * @param $toUsername 接收用户
  1051. * @param $contentStr 发送内容
  1052. * @param string $msgType 消息类型
  1053. */
  1054. public static function responseTplMsg($fromUsername, $toUsername, $contentStr, $msgType = 'text')
  1055. {
  1056. $textTpl = "<xml>
  1057. <ToUserName><![CDATA[%s]]></ToUserName>
  1058. <FromUserName><![CDATA[%s]]></FromUserName>
  1059. <CreateTime>%s</CreateTime>
  1060. <MsgType><![CDATA[%s]]></MsgType>
  1061. <Content><![CDATA[%s]]></Content>
  1062. </xml>";
  1063. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
  1064. echo $resultStr;
  1065. exit;
  1066. }
  1067. /**
  1068. * 创建菜单
  1069. * @param array $menus 菜单数组数据
  1070. * @params $delete 是否删除就菜单
  1071. * @return bool
  1072. */
  1073. public static function createMenu($menus = [], $delete = false)
  1074. {
  1075. $weixinConfig = config('weixin.');
  1076. $menus = $menus ? $menus : (isset($weixinConfig['menus']) ? $weixinConfig['menus'] : []);
  1077. if (empty($menus)) {
  1078. return false;
  1079. }
  1080. $tokenData = WechatService::getAccessToken('', 'accessToken');
  1081. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1082. if (empty($token)) {
  1083. return false;
  1084. }
  1085. // 删除菜单
  1086. if ($delete) {
  1087. WechatService::delMenu();
  1088. }
  1089. $url = sprintf(self::$apiUrl['createMenu'], $token);
  1090. $result = httpRequest($url, json_encode(['button' => $menus], 256));
  1091. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1092. if ($errorCode != 0) {
  1093. return false;
  1094. }
  1095. return $result;
  1096. }
  1097. /**
  1098. * 删除菜单
  1099. * @return bool
  1100. */
  1101. public static function delMenu()
  1102. {
  1103. $tokenData = WechatService::getAccessToken('', 'accessToken');
  1104. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1105. $url = sprintf(self::$apiUrl['delMenu'], $token);
  1106. $result = httpRequest($url);
  1107. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1108. if ($errorCode == 0) {
  1109. return false;
  1110. }
  1111. return true;
  1112. }
  1113. /**
  1114. * 查询菜单
  1115. * @return bool
  1116. */
  1117. public static function getMenu()
  1118. {
  1119. $tokenData = WechatService::getAccessToken('', 'accessToken');
  1120. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1121. $url = sprintf(self::$apiUrl['getMenu'], $token);
  1122. $result = httpRequest($url);
  1123. return $result;
  1124. }
  1125. /**
  1126. * 发送客服消息
  1127. * @param $openid 接受用户OPENID
  1128. * @param $content 消息内容:数组
  1129. * @param string $msgType 消息类型
  1130. * @return mixed
  1131. */
  1132. public static function sendCustomMsg($openid, $content, $msgType = 'text')
  1133. {
  1134. $data = [
  1135. 'touser' => $openid,
  1136. 'msgtype' => $msgType,
  1137. $msgType => $content
  1138. ];
  1139. $lockKey = 'caches:weixin:custonLock:' . $openid . '_' . md5(json_encode($data));
  1140. if (RedisService::get($lockKey)) {
  1141. return false;
  1142. }
  1143. $tokenData = WechatService::getAccessToken('');
  1144. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1145. RedisService::set($lockKey, $data, 5);
  1146. $url = sprintf(self::$apiUrl['customMessage'], $token);
  1147. $result = httpRequest($url, json_encode($data, 256));
  1148. RedisService::set('caches:weixin:customLock:' . $openid . '_' . date('YmdHis'), ['data' => $data, 'tokenData' => $tokenData, 'result' => $result], 3);
  1149. return $result;
  1150. }
  1151. /**
  1152. * 发送模板消息
  1153. * @param $openid OPENID
  1154. * @param $params 参数:title-标题(必填),type-模板类型标识字符串(必填),keywords-模板字段数据(必填),url-模板跳转链接,remark-模板备注信息
  1155. * @return array|int
  1156. */
  1157. public static function sendTplMsg($openid, $params, $formatUrl=true)
  1158. {
  1159. $title = isset($params['title']) ? $params['title'] : '';
  1160. $remark = isset($params['remark']) ? $params['remark'] : '';
  1161. $type = isset($params['type']) ? $params['type'] : 'default';
  1162. $keywords = isset($params['keywords']) ? $params['keywords'] : [];
  1163. $keywords = $keywords ? $keywords : [];
  1164. if ($title) {
  1165. $keywords['first'] = ['value' => $title, 'color' => '#173177'];
  1166. }
  1167. if ($remark) {
  1168. $keywords['remark'] = ['value' => $remark, 'color' => '#173177'];
  1169. }
  1170. $configService = new ConfigService();
  1171. $templates = $configService->getConfigByGroup(10);
  1172. $templateId = isset($templates[$type]) ? trim($templates[$type]) : '';
  1173. if (empty($templateId)) {
  1174. return 2110;
  1175. }
  1176. ksort($keywords);
  1177. $tplData = [
  1178. 'touser' => $openid,
  1179. 'template_id' => $templateId,
  1180. 'data' => $keywords,
  1181. ];
  1182. $url = isset($params['url']) ? trim($params['url']) : '';
  1183. if ($url) {
  1184. $tplData['url'] = $formatUrl? WechatService::makeRedirectUrl($url) : $url;
  1185. }
  1186. // 删除旧数据,新增消息记录
  1187. $tokenData = WechatService::getAccessToken('');
  1188. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1189. if (empty($token)) {
  1190. return 1010;
  1191. }
  1192. $url = sprintf(self::$apiUrl['tplMessage'], $token);
  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 == 'ok') {
  1197. return true;
  1198. } else {
  1199. $result = httpRequest($url, json_encode($tplData, 256));
  1200. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1201. RedisService::set('caches:messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1202. if ($code === 0) {
  1203. return true;
  1204. }
  1205. }
  1206. return 2113;
  1207. }
  1208. /**
  1209. * 获取消息模板列表
  1210. * @return int|mixed
  1211. */
  1212. public static function getTemplateList(){
  1213. $tokenData = WechatService::getAccessToken('');
  1214. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1215. if (empty($token)) {
  1216. return 1010;
  1217. }
  1218. $url = sprintf(self::$apiUrl['templateList'], $token);
  1219. $result = httpRequest($url);
  1220. RedisService::set('caches:messages:templates', $result, 600);
  1221. return $result;
  1222. }
  1223. /**
  1224. * 获取支付签名token
  1225. * @return string
  1226. */
  1227. public static function getSignToken($params){
  1228. $url = $params['url'];
  1229. $url_parts = parse_url($url);
  1230. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  1231. $nonce = WechatService::createNonceStr(32);
  1232. $timestamp = time();
  1233. $body = isset($params['body'])? $params['body'] : '';
  1234. $method = isset($params['method'])? $params['method'] : 'POST';
  1235. $message = "{$method}\n".
  1236. $canonical_url."\n".
  1237. $timestamp."\n".
  1238. $nonce."\n";
  1239. if($body){
  1240. $message .= $body."\n";
  1241. }
  1242. $mch_private_key = openssl_get_privatekey(file_get_contents(self::$certPaths['key_path']));
  1243. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  1244. $sign = base64_encode($raw_sign);
  1245. $schema = 'WECHATPAY2-SHA256-RSA2048';
  1246. $serial_no = WechatService::getConfigs('wx_mch_cert_no');
  1247. $mchId = isset($params['mchid'])? $params['mchid'] : WechatService::getConfigs('wx_mchid');
  1248. $token = sprintf('%s mchid="%s",nonce_str="%s",timestamp="%d",signature="%s",serial_no="%s"', $schema, $mchId, $nonce, $timestamp, $sign, $serial_no);
  1249. return $token;
  1250. }
  1251. /**
  1252. * Read certificate from file
  1253. *
  1254. * @param string $filepath PEM encoded X.509 certificate file path
  1255. *
  1256. * @return resource|bool X.509 certificate resource identifier on success or FALSE on failure
  1257. */
  1258. public static function getCertificate() {
  1259. return openssl_x509_read(file_get_contents(self::$certPaths['cert_path']));}
  1260. /**
  1261. * 生成普通参数二维码
  1262. * @param $str 参数
  1263. * @param bool $refresh 是否重新生成
  1264. * @return bool
  1265. */
  1266. public static function makeNormalQrcode($str, $refresh = false, $size = 8, $margin=2)
  1267. {
  1268. $qrFile = '/upload/qrcode/member/';
  1269. if (!is_dir($qrFile)) {
  1270. @mkdir('.' . $qrFile, 0755, true);
  1271. }
  1272. $qrFile = $qrFile . 'U_' . strtoupper(md5($str . '_' . $size)) . '.jpg';
  1273. if (is_file($qrFile) && !$refresh) {
  1274. return false;
  1275. }
  1276. $renderer = new ImageRenderer(
  1277. new RendererStyle(360),
  1278. new ImagickImageBackEnd()
  1279. );
  1280. $writer = new Writer($renderer);
  1281. $writer->writeFile($str, $qrFile);
  1282. if(!file_exists('.'.$qrFile)){
  1283. return false;
  1284. }
  1285. return $qrFile;
  1286. }
  1287. /**
  1288. * 返回给微信
  1289. */
  1290. public static function rebackOk(){
  1291. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  1292. exit;
  1293. }
  1294. }
  1295. ?>