WechatService.php 53 KB

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