WechatService.php 55 KB

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