WechatService.php 56 KB

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