Wechat.php 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. <?php
  2. namespace app\weixin\model;
  3. use app\weixin\service\Award;
  4. use app\weixin\service\PRedis;
  5. use cmf\phpqrcode\QRcode;
  6. use FontLib\Table\Type\head;
  7. use think\Model;
  8. class Wechat
  9. {
  10. private static $apiUrl = [
  11. // 授权
  12. 'auth' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=xydc#wechat_redirect',
  13. // 第三方
  14. 'qrConnect' => 'https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=SCOPE&state=STATE',
  15. // 永久ACCESS_TOKEN
  16. 'accessToken' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
  17. // 临时ACCESS_TOKEN
  18. 'tempToken' => 'https://api.weixin.qq.com/sns/oauth2/access_token?code=%s&appid=%s&secret=%s&grant_type=authorization_code',
  19. // 清除接口限制
  20. 'clearTokenQuota' => 'https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s',
  21. // 微信用户信息
  22. 'wxInfo' => 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN',
  23. // 获取userInfo
  24. 'userInfo' => 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN',
  25. // 统一下单
  26. 'unifiedorder' => 'https://api.mch.weixin.qq.com/pay/unifiedorder',
  27. // 原路退款接口
  28. 'refundOrder' => 'https://api.mch.weixin.qq.com/pay/unifiedorder',
  29. // 查询订单
  30. 'queryOrder' => 'https://api.mch.weixin.qq.com/pay/orderquery',
  31. // 企业付款到零钱
  32. 'transfers' => 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers',
  33. // 查询企业付款订单
  34. 'queryTransfer' => 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo',
  35. // 生成二维码
  36. 'makeQrcode' => 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s',
  37. // 换取二维码
  38. 'getQrcodeByTicket' => 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s',
  39. // 创建公众号菜单
  40. 'createMenu' => 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s',
  41. // 获取公众号菜单
  42. 'getMenu' => 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s',
  43. // 删除公众号菜单
  44. 'delMenu' => 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s',
  45. // 发送客服消息
  46. 'customMessage' => 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s',
  47. // 发送模板消息
  48. 'tplMessage' => 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s',
  49. // 获取消息模板列表
  50. 'templateList' => 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=%s',
  51. // 添加媒体素材
  52. 'uploadMedia' => 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s',
  53. // 生成短连接
  54. 'shortUrl' => 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s',
  55. // 清除接口限制
  56. 'clearTokenQuota'=> 'https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s',
  57. ];
  58. private static $jsApiUrl = [
  59. // jssdk 验证参数
  60. 'ticket' => 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=%s',
  61. // 永久TOKENresponseText
  62. 'token' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
  63. ];
  64. // 支付证书
  65. protected static $certPaths = [
  66. 'cert_path'=> CMF_ROOT.'data/cert/apiclient_cert.pem',
  67. 'key_path'=> CMF_ROOT.'data/cert/apiclient_key.pem',
  68. ];
  69. /**
  70. * 授权地址校验
  71. */
  72. public static function valid()
  73. {
  74. echo input('echostr');
  75. exit;
  76. }
  77. /**
  78. * 获取授权后信息
  79. */
  80. public static function init()
  81. {
  82. $code = input('code', '');
  83. // 获取token
  84. if ($code) {
  85. Wechat::wxInit();
  86. } else {
  87. $url = urlencode(request()->domain() . request()->url());
  88. Wechat::redirectUrl($url);
  89. }
  90. }
  91. /**
  92. * 授权认证
  93. * @throws \think\Exception
  94. * @throws \think\exception\PDOException
  95. */
  96. public static function auth()
  97. {
  98. $code = input('code', '');
  99. // 获取token
  100. if ($code) {
  101. Wechat::wxAuth();
  102. } else {
  103. $url = urlencode(request()->domain() . request()->url());
  104. Wechat::redirectUrl($url);
  105. }
  106. }
  107. /**
  108. * 跳转授权
  109. * @param string $url 回跳地址
  110. * @return mixed
  111. */
  112. public static function redirectUrl($url)
  113. {
  114. ob_clean();
  115. $appid = Wechat::getConfigs('appid');
  116. $redirectUrl = sprintf(self::$apiUrl['auth'], $appid, $url, 'snsapi_userinfo');
  117. header("Location:" . $redirectUrl);
  118. exit;
  119. }
  120. /**
  121. * 跳转授权
  122. * @param string $url 回跳地址
  123. * @return mixed
  124. */
  125. public static function makeRedirectUrl($url)
  126. {
  127. $appid = Wechat::getConfigs('appid');
  128. return sprintf(self::$apiUrl['auth'], $appid, $url, 'snsapi_userinfo');
  129. }
  130. /**
  131. * 获取配置
  132. * @param string $key 键名
  133. * @return array|mixed|string
  134. */
  135. public static function getConfigs($key = '')
  136. {
  137. $defConfig = config('weixin.');
  138. $config = cmf_get_option('wechat');
  139. $config = $config ? $config : $defConfig;
  140. $config['notify'] = isset($defConfig['notify']) ? $defConfig['notify'] : [];
  141. if ($key) {
  142. return isset($config[$key]) ? $config[$key] : '';
  143. } else {
  144. return $config ? $config : [];
  145. }
  146. }
  147. /**
  148. * 授权获取微信信息用于绑定
  149. * @throws \think\Exception
  150. * @throws \think\exception\PDOException
  151. */
  152. private static function wxAuth()
  153. {
  154. $wxInfo = Wechat::getWxInfo('', true);
  155. $openid = isset($wxInfo['openid']) ? $wxInfo['openid'] : '';
  156. if (empty($wxInfo) || empty($openid)) {
  157. // 重新获取授权
  158. Wechat::auth();
  159. }
  160. // 验证微信信息是否存在
  161. $cacheKey = 'updateWeixinInfo:' . $openid;
  162. $updateCheck = cache($cacheKey);
  163. $wxData = [
  164. 'openid' => $openid,
  165. 'nickname' => isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '',
  166. 'headimgurl' => isset($wxInfo['headimgurl']) ? $wxInfo['headimgurl'] : '',
  167. 'sex' => isset($wxInfo['sex']) ? $wxInfo['sex'] : 0,
  168. 'country' => isset($wxInfo['country']) ? $wxInfo['country'] : '',
  169. 'province' => isset($wxInfo['province']) ? $wxInfo['province'] : '',
  170. 'city' => isset($wxInfo['city']) ? $wxInfo['city'] : '',
  171. ];
  172. if (empty(db('fans')->where(['openid' => $openid])->value('id'))) {
  173. $wxData['created_at'] = time();
  174. $resId = db('fans')->insertGetId($wxData);
  175. // 每3个小时才更新一次微信信息
  176. $expire = config('weixin.update_expire');
  177. $expire = $expire ? $expire : 3 * 3600;
  178. cache($cacheKey, date('Y-m-d H:i:s'), ['expire' => $expire]);
  179. } else if (empty($updateCheck)) {
  180. // 更新微信用户信息
  181. db('fans')->where(['openid' => $openid])->update($wxData);
  182. // 每3个小时才更新一次微信信息
  183. $expire = config('weixin.update_expire');
  184. $expire = $expire ? $expire : 3 * 3600;
  185. cache($cacheKey, date('Y-m-d H:i:s'), ['expire' => $expire]);
  186. }
  187. session('openid', $openid);
  188. session('wxInfo', $wxData);
  189. }
  190. /**
  191. * 微信注册初始化和授权登录
  192. */
  193. private static function wxInit()
  194. {
  195. $wxInfo = Wechat::getWxInfo('', true);
  196. $openid = isset($wxInfo['openid']) ? $wxInfo['openid'] : '';
  197. $userInfo = Wechat::getUserInfo($openid);
  198. $wxInfo = $userInfo? $userInfo : $wxInfo;
  199. $cacheKey = 'weixin:init:'.get_client_ip().'_'.$openid;
  200. if (empty($wxInfo) || empty($openid)) {
  201. if(PRedis::get($cacheKey)<10){
  202. // 重新获取授权
  203. PRedis::inc($cacheKey, 1);
  204. Wechat::init();
  205. }else{
  206. Wechat::redirectUrl(url('/weixin/match/index','','',true));
  207. exit;
  208. }
  209. }
  210. // 验证微信信息是否存在
  211. PRedis::del($cacheKey);
  212. $cacheKey = 'updateFansInfo:' . $openid;
  213. $updateCheck = cache($cacheKey);
  214. $wxData = [
  215. 'openid' => $openid,
  216. 'nickname' => isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '',
  217. 'headimgurl' => isset($wxInfo['headimgurl']) ? $wxInfo['headimgurl'] : '',
  218. 'sex' => isset($wxInfo['sex']) ? $wxInfo['sex'] : 0,
  219. 'country' => isset($wxInfo['country']) ? $wxInfo['country'] : '',
  220. 'province' => isset($wxInfo['province']) ? $wxInfo['province'] : '',
  221. 'city' => isset($wxInfo['city']) ? $wxInfo['city'] : '',
  222. ];
  223. // 用户信息
  224. $userData = [
  225. 'sex' => $wxData['sex'],
  226. 'openid' => $wxData['openid'],
  227. 'user_nickname' => $wxData['nickname'],
  228. 'last_login_time' => time(),
  229. 'last_login_ip' => get_client_ip(),
  230. 'avatar' => $wxData['headimgurl'],
  231. ];
  232. // 微信用户不存在
  233. $userId = 0;
  234. db()->startTrans();
  235. $userInfo = db('user')->field('id,avatar')
  236. ->where(['openid' => $openid])
  237. ->where('user_status','>=', 0)
  238. ->find();
  239. if (empty(db('fans')->where(['openid' => $openid])->value('id'))) {
  240. // 验证更新注册用户
  241. $userId = db('user')
  242. ->where(['openid' => $openid])
  243. ->where('user_status','>=', 0)
  244. ->value('id');
  245. if ($userId) {
  246. db('user')->where(['openid' => $openid])
  247. ->where('user_status','>=', 0)
  248. ->update($userData);
  249. } else {
  250. $userData['wxInfo'] = $wxInfo;
  251. $result = Member::regMember($userData);
  252. $userId = isset($result['userId']) ? $result['userId'] : 0;
  253. if (!$userId) {
  254. db()->rollback();
  255. return false;
  256. }
  257. }
  258. // 保存微信用户信息
  259. $wxData['uid'] = $userId;
  260. $wxData['created_at'] = time();
  261. $resId = db('fans')->insertGetId($wxData);
  262. if (!$resId) {
  263. db()->rollback();
  264. return false;
  265. }
  266. // 每3个小时才更新一次微信信息
  267. $expire = config('weixin.update_expire');
  268. $expire = $expire ? $expire : 3 * 3600;
  269. cache($cacheKey, date('Y-m-d H:i:s'), ['expire' => $expire]);
  270. } else if (empty($updateCheck) || empty($userInfo)) {
  271. // 验证是否绑定用户,更新用户头像信息
  272. $userId = isset($userInfo['id']) ? intval($userInfo['id']) : 0;
  273. if (!$userId) {
  274. // 注册用户
  275. $userData['wxInfo'] = $wxInfo;
  276. $result = Member::regMember($userData);
  277. $userId = isset($result['userId']) ? $result['userId'] : 0;
  278. if (!$userId) {
  279. db()->rollback();
  280. return false;
  281. }
  282. }
  283. // 更新微信用户信息
  284. db('fans')->where(['openid' => $openid])->update($wxData);
  285. // 每3个小时才更新一次微信信息
  286. $expire = config('weixin.update_expire');
  287. $expire = $expire ? $expire : 3 * 3600;
  288. cache($cacheKey, date('Y-m-d H:i:s'), ['expire' => $expire]);
  289. }else{
  290. $updateData = [
  291. 'is_follow'=> isset($wxInfo['subscribe']) ? intval($wxInfo['subscribe']) : 0,
  292. 'last_login_time'=> time(),
  293. 'last_login_ip'=> get_client_ip(),
  294. 'updated_at'=> date('Y-m-d H:i:s')
  295. ];
  296. db('user')->where(['openid' => $openid])
  297. ->where('user_status','>=', 0)
  298. ->update($updateData);
  299. }
  300. db()->commit();
  301. // 记录OPENID
  302. $userInfo = Member::getInfo(['openid' => $openid]);
  303. PRedis::set($cacheKey, $userInfo, 7 * 24 * 3600);
  304. session('userInfo', $userInfo);
  305. session('openid', $openid);
  306. session('wxInfo', $wxData);
  307. }
  308. /**
  309. * 获取ACCESS_TOKEN
  310. * @return bool|string
  311. */
  312. public static function getAccessToken($key = '', $type = 'tempToken', $refresh = false)
  313. {
  314. $code = input('code', '');
  315. $appid = Wechat::getConfigs('appid');
  316. $appsecret = Wechat::getConfigs('appsecret');
  317. $cacheKey = 'token:' . $type . ':' . $appid . '_' . $appsecret;
  318. $tokenData = PRedis::get($cacheKey);
  319. if (empty($tokenData) || $type == 'tempToken' || $refresh) {
  320. if ($type == 'tempToken') {
  321. $url = sprintf(self::$apiUrl[$type], $code, $appid, $appsecret);
  322. } else {
  323. $url = sprintf(self::$apiUrl[$type], $appid, $appsecret);
  324. }
  325. $countKey = "token:count";
  326. $requestCount = PRedis::get($countKey);
  327. if($type == 'accessToken'){
  328. if($requestCount >=8000){
  329. PRedis::set("token:error", 'token请求次数超出警告值8000:'.date('Y-m-d H:i:s'), 3 * 24 *3600);
  330. return false;
  331. }
  332. PRedis::set($countKey, $requestCount+1, 24*3600);
  333. }
  334. $tokenData = httpRequest($url);
  335. PRedis::set("token:result", $tokenData, 3600);
  336. $code = isset($tokenData['errcode']) ? $tokenData['errcode'] : '';
  337. if ($code || empty($tokenData)) {
  338. return $tokenData;
  339. }
  340. $token = isset($tokenData['access_token']) ? $tokenData['access_token'] : '';
  341. $openid = isset($tokenData['openid']) ? $tokenData['openid'] : '';
  342. $tokenData = [
  343. 'token' => $token,
  344. 'openid' => $openid,
  345. 'data' => $tokenData,
  346. 'date' => date('Y-m-d H:i:s'),
  347. 'expire' => $type == 'tempToken' ? time() + 7000 : time() + 7000,
  348. ];
  349. PRedis::set($cacheKey, $tokenData, 7200);
  350. }
  351. $expire = isset($tokenData['expire']) ? intval($tokenData['expire']) : 0;
  352. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  353. if (($expire && $expire < time()) || empty($token)) {
  354. $tokenData = Wechat::getAccessToken($key, $type, true);
  355. }
  356. if ($key) {
  357. $tokenData = isset($tokenData[$key]) ? trim($tokenData[$key]) : '';
  358. }
  359. return $tokenData;
  360. }
  361. /**
  362. * 获取微信用户信息
  363. * @param string $openid 获取的用户OPENID,默认当前用户
  364. * @return mixed
  365. */
  366. public static function getWxInfo($curOpenid = '', $refreshToken = false, $saveData = false)
  367. {
  368. $type = $curOpenid ? 'accessToken' : 'tempToken';
  369. $tokenData = Wechat::getAccessToken('', $type, $refreshToken);
  370. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  371. $openid = isset($tokenData['openid']) ? trim($tokenData['openid']) : '';
  372. if (empty($token)) {
  373. return false;
  374. }
  375. $openid = $curOpenid ? $curOpenid : $openid;
  376. $url = sprintf(self::$apiUrl['wxInfo'], $token, $openid);
  377. $result = httpRequest($url);
  378. $errcode = isset($result['errcode']) ? $result['errcode'] : '';
  379. $cacheCount = PRedis::get('weixin:getWxInfo:' . $openid);
  380. if (empty($result) || ($errcode && $cacheCount <= 3)) {
  381. // 更新TOKEN重新获取
  382. PRedis::set('weixin:getWxInfo:' . $openid, $cacheCount + 1, 600);
  383. $result = Wechat::getWxInfo($curOpenid, $errcode ? true : false);
  384. }
  385. PRedis::set('weixin:info:'.$openid, $result, 600);
  386. if ($saveData && empty($errcode)) {
  387. $wxData = [
  388. 'openid' => $openid,
  389. 'nickname' => isset($result['nickname']) ? $result['nickname'] : '',
  390. 'headimgurl' => isset($result['headimgurl']) ? $result['headimgurl'] : '',
  391. 'sex' => isset($result['sex']) ? $result['sex'] : 0,
  392. 'country' => isset($result['country']) ? $result['country'] : '',
  393. 'province' => isset($result['province']) ? $result['province'] : '',
  394. 'city' => isset($result['city']) ? $result['city'] : '',
  395. ];
  396. if (empty(db('fans')->where(['openid' => $openid])->value('id'))) {
  397. db('fans')->insertGetId($wxData);
  398. } else {
  399. db('fans')->where(['openid' => $openid])->update($wxData);
  400. }
  401. }
  402. return $result;
  403. }
  404. /**
  405. * 获取微信UserInfo用户信息
  406. * @param string $openid 获取的用户OPENID,默认当前用户
  407. * @return mixed
  408. */
  409. public static function getUserInfo($curOpenid = '', $refreshToken = false, $saveData = false)
  410. {
  411. $type = 'accessToken';
  412. $tokenData = Wechat::getAccessToken('', $type, $refreshToken);
  413. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  414. $openid = isset($tokenData['openid']) ? trim($tokenData['openid']) : '';
  415. if (empty($token)) {
  416. return false;
  417. }
  418. $openid = $curOpenid ? $curOpenid : $openid;
  419. $url = sprintf(self::$apiUrl['userInfo'], $token, $openid);
  420. $result = httpRequest($url);
  421. $errcode = isset($result['errcode']) ? $result['errcode'] : '';
  422. $cacheCount = PRedis::get('weixin:getInfo:' . $openid);
  423. if (empty($result) || ($errcode && $cacheCount <= 3)) {
  424. // 更新TOKEN重新获取
  425. PRedis::set('weixin:getInfo:' . $openid, $cacheCount + 1, 600);
  426. $result = Wechat::getUserInfo($curOpenid, $errcode ? true : false);
  427. }
  428. PRedis::set('weixin:userInfo:'.$openid, $result, 600);
  429. if ($saveData && empty($errcode)) {
  430. $wxData = [
  431. 'openid' => $openid,
  432. 'nickname' => isset($result['nickname']) ? $result['nickname'] : '',
  433. 'headimgurl' => isset($result['headimgurl']) ? $result['headimgurl'] : '',
  434. 'sex' => isset($result['sex']) ? $result['sex'] : 0,
  435. 'country' => isset($result['country']) ? $result['country'] : '',
  436. 'province' => isset($result['province']) ? $result['province'] : '',
  437. 'city' => isset($result['city']) ? $result['city'] : '',
  438. ];
  439. if (empty(db('fans')->where(['openid' => $openid])->value('id'))) {
  440. db('fans')->insertGetId($wxData);
  441. } else {
  442. db('fans')->where(['openid' => $openid])->update($wxData);
  443. }
  444. }
  445. return $result;
  446. }
  447. /**
  448. * 获取JSSDK ticket参数
  449. * @author wesmiler
  450. */
  451. private static function getTicket($refresh = false, $refreshToken = false)
  452. {
  453. $appid = Wechat::getConfigs('appid');
  454. $appsecret = Wechat::getConfigs('appsecret');
  455. $cacheKey = 'token:jsapiTicket:' . $appid . '_' . $appsecret;
  456. $ticketData = PRedis::get($cacheKey);
  457. $ticket = isset($ticketData['ticket']) ? $ticketData['ticket'] : '';
  458. if (empty($ticket) || $refresh) {
  459. $tokenData = Wechat::getAccessToken('', 'accessToken', $refreshToken);
  460. $code = isset($tokenData['errcode']) ? $tokenData['errcode'] : '';
  461. if ($code) {
  462. return $tokenData;
  463. }
  464. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  465. $url = sprintf(self::$jsApiUrl['ticket'], $token);
  466. $result = httpRequest($url);
  467. if (empty($result)) {
  468. PRedis::set('token:jsapiTicket_error', $result, 3600);
  469. return false;
  470. }
  471. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  472. $ticketData = [
  473. 'ticket' => $ticket,
  474. 'expire' => time() + 6000,
  475. ];
  476. PRedis::set($cacheKey, $ticketData, 7200);
  477. }
  478. $expire = isset($ticketData['expire']) ? intval($ticketData['expire']) : 0;
  479. if (empty($expire) || $expire < time()) {
  480. $ticket = Wechat::getTicket(true);
  481. }
  482. if (empty($ticket)) {
  483. $ticket = Wechat::getTicket(true, true);
  484. }
  485. return $ticket;
  486. }
  487. /**
  488. * 获取JSSDK签名参数
  489. * @param string $url 请求地址
  490. * @return array
  491. */
  492. public static function getJssdkParams($url = '')
  493. {
  494. // token请求次数超出警告范围
  495. $countKey = "token:count";
  496. $requestCount = PRedis::get($countKey);
  497. if($requestCount>=5000){
  498. return ['error'=> 'token请求失败次数已超出警告值5000'];
  499. }
  500. $countKey = "token:ticketCount:".get_client_ip();
  501. $requestCount = PRedis::get($countKey);
  502. if($requestCount>=100){
  503. return ['error'=> '分享参数请求次数过多请稍后重试'];
  504. }
  505. $result = Wechat::getTicket();
  506. $url = $url ? $url : request()->domain() . request()->url();
  507. $code = isset($result['errcode']) ? $result['errcode'] : '';
  508. if ($code) {
  509. return $result;
  510. }
  511. $params = [
  512. 'jsapi_ticket' => $result,
  513. 'noncestr' => uniqid('J'),
  514. 'timestamp' => time(),
  515. 'url' => $url,
  516. ];
  517. PRedis::set($countKey, $requestCount+1, 30);
  518. $signature = Wechat::getJssdkSign($params);
  519. return [
  520. 'appId' => Wechat::getConfigs('appid'),
  521. 'timestamp' => $params['timestamp'],
  522. 'nonceStr' => $params['noncestr'],
  523. 'signature' => $signature,
  524. 'url' => $url,
  525. ];
  526. }
  527. /**
  528. * 获取JSSDK 签名
  529. * @param $params 签名参数
  530. * @return string
  531. */
  532. private static function getJssdkSign($params)
  533. {
  534. $str = [];
  535. ksort($params);
  536. foreach ($params as $k => $val) {
  537. $str[] = $k . '=' . $val;
  538. }
  539. $str = implode('&', $str);
  540. return sha1($str);
  541. }
  542. /**
  543. * jsapi统一下单
  544. * @param $order 订单参数
  545. * @author wesmiler
  546. * @return array
  547. */
  548. public static function jsapiUnifiedorder($order, $scene = 'jsapiPay')
  549. {
  550. $appId = Wechat::getConfigs('appid');
  551. $mchId = Wechat::getConfigs('mch_id');
  552. $notifyUrls = Wechat::getConfigs('notify');
  553. $notifyUrl = isset($notifyUrls[$scene]) ? request()->domain().$notifyUrls[$scene] : request()->domain().'/api/notify/index';
  554. $openid = isset($order['openid']) ? trim($order['openid']) : '';
  555. $orderNo = isset($order['orderNo']) ? trim($order['orderNo']) : '';
  556. $totalFee = isset($order['amount']) ? moneyFormat($order['amount']) : 0.00;
  557. // 测试支付金额
  558. $payDebug = config('weixin.payDebug');
  559. if ($payDebug) {
  560. $totalFee = 0.01;
  561. }
  562. if (empty($openid) || empty($orderNo) || empty($totalFee)) {
  563. return ['code' => 'error', 'message' => '参数错误'];
  564. }
  565. $unified = array(
  566. 'appid' => $appId,
  567. 'attach' => 'pay', //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
  568. 'body' => isset($order['body']) ? trim($order['body']) : '订单支付',
  569. 'mch_id' => $mchId,
  570. 'nonce_str' => Wechat::createNonceStr(),
  571. 'notify_url' => $notifyUrl,
  572. 'openid' => $openid, //rade_type=JSAPI,此参数必传
  573. //'timeStamp'=>time(),
  574. 'out_trade_no' => $orderNo,
  575. 'spbill_create_ip' => get_client_ip(),
  576. 'total_fee' => intval($totalFee * 100), //单位 转为分
  577. 'trade_type' => 'JSAPI',
  578. );
  579. PRedis::set('orders:'.$scene.':'.$openid.':unified', $unified, 600);
  580. $unified['sign'] = Wechat::getPaySign($unified);
  581. PRedis::set('orders:'.$scene.':'.$openid.':unifiedSign', $unified, 600);
  582. $url = !empty(self::$apiUrl['unifiedorder']) ? trim(self::$apiUrl['unifiedorder']) : 'https://api.mch.weixin.qq.com/pay/unifiedorder';
  583. $data = Wechat::arrayToXml($unified);
  584. PRedis::set('orders:'.$scene.':'.$openid.':unifiedXml', ['data'=> $unified,'result'=> $data], 600);
  585. $responseXml = Wechat::curlPost($url, $data);
  586. //禁止引用外部xml实体
  587. libxml_disable_entity_loader(true);
  588. $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  589. $unifiedOrder = (array)$unifiedOrder;
  590. PRedis::set('orders:'.$scene.':'.$openid.':unifiedResult', ['data'=> $unifiedOrder,'result'=> $data], 600);
  591. if ($unifiedOrder === false) {
  592. return ['code' => 'exception', 'message' => 'parase xml error'];
  593. }
  594. if (isset($unifiedOrder['return_code']) && $unifiedOrder['return_code'] != 'SUCCESS') {
  595. return ['code' => 'error', 'message' => $unifiedOrder['return_msg']];
  596. }
  597. if (isset($unifiedOrder['result_code']) && $unifiedOrder['result_code'] != 'SUCCESS') {
  598. return ['code' => 'error', 'message' => $unifiedOrder['err_code']];
  599. }
  600. // 返回支付参数
  601. return Wechat::getJsapiPareams($unifiedOrder, $unified);
  602. }
  603. /**
  604. * 提现打款
  605. * @param $order
  606. * @param string $scene
  607. * @return array|string[]
  608. */
  609. public static function transferOrder($order, $scene='withdraw'){
  610. $appId = Wechat::getConfigs('appid');
  611. $mchId = Wechat::getConfigs('mch_id');
  612. $openid = isset($order['openid']) ? trim($order['openid']) : '';
  613. $orderNo = isset($order['orderNo']) ? trim($order['orderNo']) : '';
  614. $totalFee = isset($order['amount']) ? moneyFormat($order['amount']) : 0.00;
  615. // 测试支付金额
  616. $payDebug = config('weixin.payDebug');
  617. if ($payDebug) {
  618. $totalFee = 0.3;
  619. }
  620. if (empty($openid) || empty($orderNo) || empty($totalFee)) {
  621. return ['code' => 'error', 'message' => '参数错误'];
  622. }
  623. $unified = array(
  624. 'mch_appid' => $appId,
  625. 'mchid' => trim($mchId),
  626. 'device_info' => uniqid(),
  627. 'nonce_str' => Wechat::createNonceStr(),
  628. 'partner_trade_no' => $orderNo,
  629. 'openid' => $openid,
  630. 'check_name' => isset($order['check_name']) && $order['check_name']? trim($order['check_name']) : 'NO_CHECK', // 是否校验真实姓名
  631. 'amount' => intval($totalFee * 100), //单位 转为分
  632. 'desc' => isset($order['body']) ? trim($order['body']) : '余额提现',
  633. 'spbill_create_ip' => get_client_ip(),
  634. );
  635. // 是否校验真实姓名
  636. if($unified['check_name'] == 'FORCE_CHECK'){
  637. $unified['re_user_name'] = isset($order['real_name']) ? trim($order['real_name']) : '';
  638. }
  639. PRedis::set('orders:'.$scene.':'.$openid.':unified', $unified, 600);
  640. $unified['sign'] = Wechat::getPaySign($unified);
  641. PRedis::set('orders:'.$scene.':'.$openid.':unifiedSign', $unified, 600);
  642. $url = !empty(self::$apiUrl['transfers']) ? trim(self::$apiUrl['transfers']) : 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  643. $data = Wechat::arrayToXml($unified);
  644. PRedis::set('orders:'.$scene.':'.$openid.':unifiedXml', ['data'=> $unified,'result'=> $data], 600);
  645. $responseXml = Wechat::curlPost($url, $data, [], self::$certPaths);
  646. //禁止引用外部xml实体
  647. libxml_disable_entity_loader(true);
  648. $result = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  649. $result = (array)$result;
  650. PRedis::set('orders:'.$scene.':'.$openid.':unifiedResult', ['data'=> $result,'result'=> $data], 600);
  651. if ($result === false) {
  652. return ['code' => 'exception', 'message' => 'parase xml error'];
  653. }
  654. if (isset($result['return_code']) && $result['return_code'] != 'SUCCESS') {
  655. return ['code' => 'error', 'message' => Wechat::getError($result['return_msg']),'type'=>'return_code'];
  656. }
  657. if (isset($result['result_code']) && $result['result_code'] != 'SUCCESS') {
  658. return ['code' => 'error', 'message' => $result['err_code_des'],'error_code'=> $result['err_code'],'type'=>'result_code'];
  659. }
  660. return $result;
  661. }
  662. /**
  663. * 查询企业付款订单
  664. * @param $trane_order_no 订单号
  665. * @return string[]
  666. */
  667. public static function queryTransferOrder($trane_order_no){
  668. $appId = Wechat::getConfigs('appid');
  669. $mchId = Wechat::getConfigs('mch_id');
  670. if (empty($trane_order_no)) {
  671. return ['code' => 'error', 'message' => '参数错误'];
  672. }
  673. $unified = array(
  674. 'appid' => $appId,
  675. 'mch_id' => trim($mchId),
  676. 'nonce_str' => Wechat::createNonceStr(),
  677. 'partner_trade_no' => $trane_order_no,
  678. );
  679. PRedis::set('orders:transfer:'.$trane_order_no.':unified', $unified, 600);
  680. $unified['sign'] = Wechat::getPaySign($unified);
  681. PRedis::set('orders:transfer:'.$trane_order_no.':unifiedSign', $unified, 600);
  682. $url = !empty(self::$apiUrl['queryTransfer']) ? trim(self::$apiUrl['queryTransfer']) : 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo';
  683. $data = Wechat::arrayToXml($unified);
  684. PRedis::set('orders:transfer:'.$trane_order_no.':unifiedXml', ['data'=> $unified,'result'=> $data], 600);
  685. $responseXml = Wechat::curlPost($url, $data, [], self::$certPaths);
  686. //禁止引用外部xml实体
  687. libxml_disable_entity_loader(true);
  688. $result = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  689. $result = (array)$result;
  690. PRedis::set('orders:transfer:'.$trane_order_no.':unifiedResult', ['data'=> $result,'result'=> $data], 600);
  691. if ($result === false) {
  692. return ['code' => 'exception', 'message' => 'parase xml error'];
  693. }
  694. if (isset($result['return_code']) && $result['return_code'] != 'SUCCESS') {
  695. return ['code' => 'error', 'message' => Wechat::getError($result['return_msg']),'type'=>'return_code'];
  696. }
  697. if (isset($result['result_code']) && $result['result_code'] != 'SUCCESS') {
  698. return ['code' => 'error', 'message' => $result['err_code_des'],'error_code'=> $result['err_code'],'type'=>'result_code'];
  699. }
  700. return $result;
  701. }
  702. /**
  703. * 退款订单
  704. */
  705. public static function refundOrder(){
  706. }
  707. /**
  708. * 获取JSAPI支付签名参数
  709. * @param $unifiedOrder 统一下单结果
  710. * @param array $unified 提交统一下单参数
  711. * @return array
  712. */
  713. public static function getJsapiPareams($unifiedOrder, $unified = [])
  714. {
  715. $time = time();
  716. $prepayId = isset($unifiedOrder['prepay_id']) ? $unifiedOrder['prepay_id'] : '';
  717. $params = array(
  718. "appId" => Wechat::getConfigs('appid'),
  719. "timeStamp" => "$time", //这里是字符串的时间戳,不是int,所以需加引号
  720. "nonceStr" => isset($unified['nonce_str']) ? trim($unified['nonce_str']) : Wechat::createNonceStr(),
  721. "package" => "prepay_id=" . $prepayId,
  722. "signType" => 'MD5',
  723. );
  724. // 重签名
  725. $params['sign'] = Wechat::getPaySign($params);
  726. $params['prepay_id'] = $prepayId;
  727. return $params;
  728. }
  729. /**
  730. * 查询订单
  731. * @param $outTradeNo 单号
  732. * @return bool|\SimpleXMLElement
  733. */
  734. public static function queryOrder($outTradeNo)
  735. {
  736. $params['appid'] = Wechat::getConfigs('appid');
  737. $params['mch_id'] = Wechat::getConfigs('mch_id');
  738. $params['nonce_str'] = Wechat::createNonceStr();
  739. $params['out_trade_no'] = $outTradeNo;
  740. //获取签名数据
  741. $params['sign'] = Wechat::getPaySign($params);
  742. $responseXml = Wechat::curlPost(self::$apiUrl['queryOrder'], Wechat::arrayToXml($params));
  743. $result = Wechat::xmlToArray($responseXml);
  744. saveLogCache('OrderPay:jsapiPay:query:' . $outTradeNo, json_encode($result, 256));
  745. $returnCode = isset($result['return_code']) ? $result['return_code'] : '';
  746. $tradState = isset($result['trade_state']) ? $result['trade_state'] : '';
  747. $resultCode = isset($result['result_code']) ? $result['result_code'] : '';
  748. if ($resultCode && $returnCode && $tradState) {
  749. return $result;
  750. } else {
  751. return false;
  752. }
  753. }
  754. /**
  755. * XML转数组
  756. * @param $xml
  757. * @return bool|\SimpleXMLElement
  758. */
  759. private static function xmlToArray($xml)
  760. {
  761. if (empty($xml)) return false;
  762. libxml_disable_entity_loader(true);
  763. return simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  764. }
  765. /**
  766. * 生成随机字符串
  767. * @param int $length 长度
  768. * @return string
  769. */
  770. public static function createNonceStr($length = 16)
  771. {
  772. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  773. $str = '';
  774. for ($i = 0; $i < $length; $i++) {
  775. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  776. }
  777. return $str;
  778. }
  779. /**
  780. * @param $params
  781. * @param $key
  782. * @return string
  783. */
  784. public static function getPaySign($params, $key = '')
  785. {
  786. ksort($params, SORT_STRING);
  787. $key = $key ? $key : Wechat::getConfigs('key');
  788. $taskNo = isset($params['out_trade_no']) ? trim($params['out_trade_no']) : md5(json_encode($params));
  789. $unSignParaString = Wechat::formatParams($params, false);
  790. saveLogCache('OrderPay:jsapiPay:makeSign:' . $taskNo, '签名字符串:' . $unSignParaString . "\n密钥:" . $key);
  791. $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
  792. return $signStr;
  793. }
  794. /**
  795. * 验证JSAPI回调
  796. * @param $notifyData
  797. * @return array|bool
  798. */
  799. public static function checkJsapiNotify($notifyData)
  800. {
  801. if (empty($notifyData)) {
  802. return ['code' => 'error', 'message' => 'parse xml error'];
  803. }
  804. $orderNo = isset($notifyData['out_trade_no']) ? trim($notifyData['out_trade_no']) : '';
  805. $returnCode = isset($notifyData['return_code']) ? trim($notifyData['return_code']) : '';
  806. $resultCode = isset($notifyData['result_code']) ? trim($notifyData['result_code']) : '';
  807. $nofitySign = isset($notifyData['sign']) ? trim($notifyData['sign']) : '';
  808. if ($returnCode != 'SUCCESS') {
  809. $error = isset($notifyData['return_msg']) ? $notifyData['return_msg'] : '';
  810. return ['code' => 'error', 'message' => $error];
  811. }
  812. if ($resultCode != 'SUCCESS') {
  813. $error = isset($notifyData['err_code']) ? $notifyData['err_code'] : '';
  814. return ['code' => 'error', 'message' => $error];
  815. }
  816. // 验证签名
  817. unset($notifyData['sign']);
  818. $sign = Wechat::getPaySign($notifyData);
  819. saveLogCache('OrderPay:jsapiNotify:checkSign:' . $orderNo, '返回签名:' . $nofitySign . "\n当前签名:" . $sign);
  820. if ($nofitySign == $sign) {
  821. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  822. }
  823. return true;
  824. }
  825. /**
  826. * 请求接口
  827. * @param string $url 地址
  828. * @param string $postData xml参数
  829. * @param array $options
  830. * @return mixed
  831. */
  832. public static function curlPost($url = '', $postData = '', $options = array(), $cert=[])
  833. {
  834. if (is_array($postData)) {
  835. $postData = http_build_query($postData);
  836. }
  837. $ch = curl_init();
  838. curl_setopt($ch, CURLOPT_URL, $url);
  839. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  840. curl_setopt($ch, CURLOPT_POST, 1);
  841. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  842. curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  843. if (!empty($options)) {
  844. curl_setopt_array($ch, $options);
  845. }
  846. if($cert){
  847. curl_setopt($ch,CURLOPT_HEADER,FALSE);
  848. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
  849. if(isset($cert['cert_path']) && $cert['cert_path']){
  850. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  851. curl_setopt($ch,CURLOPT_SSLCERT, $cert['cert_path']);
  852. }
  853. if(isset($cert['key_path']) && $cert['key_path']) {
  854. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  855. curl_setopt($ch, CURLOPT_SSLKEY, $cert['key_path']);
  856. }
  857. }
  858. //https请求 不验证证书和host
  859. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  860. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  861. $data = curl_exec($ch);
  862. var_dump($data);
  863. curl_close($ch);
  864. return $data;
  865. }
  866. /**
  867. * 数组转XML
  868. * @param $arr 数组数据
  869. * @return string
  870. */
  871. public static function arrayToXml($arr)
  872. {
  873. $xml = "<xml>";
  874. foreach ($arr as $key => $val) {
  875. if ($key == 'detail') {
  876. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  877. } else {
  878. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  879. }
  880. }
  881. $xml .= "</xml>";
  882. return $xml;
  883. }
  884. /**
  885. * 签名参数格式化
  886. * @param $paraMap 参数
  887. * @param bool $urlEncode 是否编码
  888. * @return bool|string
  889. */
  890. protected static function formatParams($paraMap, $urlEncode = false)
  891. {
  892. $buff = "";
  893. ksort($paraMap);
  894. foreach ($paraMap as $k => $v) {
  895. if (null != $v && "null" != $v) {
  896. if ($urlEncode) {
  897. $v = urlencode($v);
  898. }
  899. $buff .= $k . "=" . $v . "&";
  900. }
  901. }
  902. $reqPar = '';
  903. if (strlen($buff) > 0) {
  904. $reqPar = substr($buff, 0, strlen($buff) - 1);
  905. }
  906. return $reqPar;
  907. }
  908. /**
  909. * 生成微信二维码
  910. * @param int $sourceId 来源ID
  911. * @param $sceneStr 场景参数字符串或ID
  912. * @param $scene 场景标识:qrcode-用户二维码
  913. * @param string $qrType 二维码生成类型:QR_SCENE, QR_STR_SCENE, QR_LIMIT_SCENE, QR_LIMIT_STR_SCENE
  914. * @param int $expire 有效期,配合场景类型使用,临时二维码最长30天有效期,0-永久
  915. * @return array|bool
  916. * @throws \think\Exception
  917. * @throws \think\db\exception\DataNotFoundException
  918. * @throws \think\db\exception\ModelNotFoundException
  919. * @throws \think\exception\DbException
  920. * @throws \think\exception\PDOException
  921. */
  922. public static function makeQrcode($sourceId = 0, $sceneStr = '', $scene = 'qrcode', $qrType = 'QR_STR_SCENE', $expire = -1)
  923. {
  924. $expire = $expire>=0 ? $expire : 24 * 3600 * 20;
  925. $tokenData = Wechat::getAccessToken('', 'accessToken');
  926. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  927. $qrData = db('qrcode')
  928. ->where(['source_id' => $sourceId, 'scene' => $scene, 'status' => 1])
  929. ->field('id,source_id,ticket,url,expire_at')
  930. ->find();
  931. $qrcodeId = isset($qrData['id']) ? $qrData['id'] : 0;
  932. $qrcodeExpire = isset($qrData['expire_at']) ? strtotime($qrData['expire_at']) : 0;
  933. if (($expire==0 && $qrcodeId) || $qrcodeExpire > time() && $qrcodeId) {
  934. $ticket = isset($qrData['ticket']) ? $qrData['ticket'] : '';
  935. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  936. $qrData['qrcode'] = Wechat::loadImage($qrcode, $scene);
  937. if($qrData['qrcode']){
  938. return $qrData;
  939. }
  940. }
  941. if (empty($token)) {
  942. $tokenData = Wechat::getAccessToken('', 'accessToken', true);
  943. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  944. if (empty($token)) {
  945. return 1010;
  946. }
  947. }
  948. if (!in_array($qrType, ['QR_SCENE', 'QR_STR_SCENE', 'QR_LIMIT_SCENE', 'QR_LIMIT_STR_SCENE'])) {
  949. return 2111;
  950. }
  951. $data = [
  952. 'expire_seconds' => $expire,
  953. 'action_name' => $qrType,
  954. ];
  955. if (in_array($qrType, ['QR_SCENE', 'QR_LIMIT_SCENE'])) {
  956. $data['action_info'] = ['scene' => ['scene_id' => $sceneStr]];
  957. } else {
  958. $data['action_info'] = ['scene' => ['scene_str' => $scene . '_' . $sceneStr]];
  959. }
  960. $url = sprintf(self::$apiUrl['makeQrcode'], $token);
  961. $result = httpRequest($url, json_encode($data, 256));
  962. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  963. PRedis::set('qrcodes:result', ['url'=> $url, 'params'=> $data, 'result'=> $result], 600);
  964. if ($result && $ticket) {
  965. $qrData = [
  966. 'source_id' => $sourceId,
  967. 'scene' => $scene,
  968. 'scene_str' => $sceneStr,
  969. 'ticket' => $ticket,
  970. 'expire_at' => $expire>0? date('Y-m-d H:i:s', time() + $expire) : null,
  971. 'url' => isset($result['url']) ? $result['url'] : '',
  972. ];
  973. if ($qrcodeId) {
  974. $qrData['updated_at'] = date('Y-m-d H:i:s');
  975. $qrcodeId = db('qrcode')->where(['id' => $qrcodeId])->update($qrData);
  976. } else {
  977. $qrData['created_at'] = date('Y-m-d H:i:s');
  978. $qrcodeId = db('qrcode')->insertGetId($qrData);
  979. $qrData['id'] = $qrcodeId;
  980. }
  981. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  982. $qrData['qrcode'] = Wechat::loadImage($qrcode, $scene, true);
  983. }
  984. return $qrcodeId > 0 ? $qrData : 1009;
  985. }
  986. /**
  987. * 下载图片
  988. * @param $file 远程文件
  989. * @param string $type 类型
  990. * @return bool|string
  991. */
  992. public static function loadImage($file, $type='qrcode', $refresh=false){
  993. if(empty($file)){
  994. return false;
  995. }
  996. $key = "members:{$type}:".md5($file);
  997. $qrcode = PRedis::get($key);
  998. if(empty($qrcode) || $refresh){
  999. $qrcodeContent = file_get_contents($file);
  1000. if($qrcodeContent){
  1001. if(!is_dir("upload/{$type}/weixin/")){
  1002. mkdir("upload/{$type}/weixin/", 0755, true);
  1003. }
  1004. $qrcode = "{$type}/weixin/QR_".md5($file).'.jpg';
  1005. file_put_contents("upload/".$qrcode, $qrcodeContent);
  1006. PRedis::set($key, $qrcode, 7 * 24 * 3600);
  1007. }
  1008. }
  1009. if(!file_exists('./upload/'.$qrcode)){
  1010. return false;
  1011. }
  1012. return cmf_get_image_preview_url($qrcode);
  1013. }
  1014. /**
  1015. * 获取微信二维码数据
  1016. * @param $where 条件
  1017. * @param string $field 返回字段
  1018. * @return bool
  1019. * @throws \think\db\exception\DataNotFoundException
  1020. * @throws \think\db\exception\ModelNotFoundException
  1021. * @throws \think\exception\DbException
  1022. */
  1023. public static function getQrcode($where, $field = '')
  1024. {
  1025. if (!is_array($where)) {
  1026. return false;
  1027. }
  1028. $where['status'] = 1;
  1029. $field = $field ? $field : 'id,source_id,scene,ticket,url';
  1030. $info = db('qrcode')
  1031. ->where($where)
  1032. ->where('expire_at', '>', date('Y-m-d H:i:s'))
  1033. ->field($field)
  1034. ->find();
  1035. $ticket = isset($info['ticket']) ? $info['ticket'] : '';
  1036. if ($info && $ticket) {
  1037. $info['qrcode'] = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  1038. }
  1039. return $info;
  1040. }
  1041. /**
  1042. * 处理扫码推荐关注
  1043. * @param $postObj
  1044. */
  1045. public static function catchEvent($postObj)
  1046. {
  1047. $contentStr = '';
  1048. $inviteData = [];
  1049. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  1050. $event = isset($postObj['Event']) ? $postObj['Event'] : '';
  1051. $eventKey = isset($postObj['EventKey']) ? $postObj['EventKey'] : '';
  1052. $lockKey = "weixin:lock:" . $openid . '_' . $event;
  1053. $lock = PRedis::get($lockKey);
  1054. if ($lock) {
  1055. return false;
  1056. }
  1057. PRedis::set($lockKey, $postObj, 8);
  1058. if ($event && $eventKey) {
  1059. // 未关注
  1060. if ($event == 'subscribe') {
  1061. $sceneStr = substr($eventKey, 8);
  1062. $sceneData = $sceneStr ? explode('_', $sceneStr) : [];
  1063. $scene = isset($sceneData[0]) ? $sceneData[0] : '';
  1064. $sceneValue = isset($sceneData[1]) ? $sceneData[1] : '';
  1065. // 用户信息注册或更新
  1066. $wxInfo = Wechat::getUserInfo($openid, false, true);
  1067. if ($wxInfo) {
  1068. $userData = [
  1069. 'sex' => $wxInfo['sex'],
  1070. 'openid' => $openid,
  1071. 'user_nickname' => $wxInfo['nickname'],
  1072. 'avatar' => $wxInfo['headimgurl'],
  1073. 'wxInfo' => $wxInfo,
  1074. ];
  1075. // 验证注册用户,并且推送关注信息
  1076. PRedis::set('members:invite:'.$openid, ['reg'=> $userData, 'params'=> $postObj], 600);
  1077. $res = Member::regMember($userData);
  1078. PRedis::set('members:register:'.$openid, ['reg'=> $userData, 'result'=> $res], 600);
  1079. // 注册奖励
  1080. $regUserId = isset($res['userId'])? $res['userId'] : 0;
  1081. $regType = isset($res['type'])? $res['type'] : 0;
  1082. if($regType == 2 && $regUserId){
  1083. $updateData = [];
  1084. switch ($scene) {
  1085. case 'qrcode': // 扫码推荐邀请
  1086. if ($sceneValue) {
  1087. // 验证推荐人
  1088. $inviteUserId = Member::where(['id' => $sceneValue, 'user_type' => 2])
  1089. ->value('id');
  1090. if ($inviteUserId) {
  1091. // 绑定上级推荐人
  1092. $updateData['parent_id'] = $inviteUserId;
  1093. $userData['id'] = $regUserId;
  1094. // 处理推荐奖励
  1095. PRedis::set('members:inviteAward:'.$openid, ['user'=> $userData,'inviteId'=> $inviteUserId], 600);
  1096. $inviteData = Award::inviteUser($inviteUserId, $userData);
  1097. }
  1098. }
  1099. break;
  1100. }
  1101. if($updateData){
  1102. Member::saveData(['id'=> $regUserId],$updateData);
  1103. }
  1104. }
  1105. $siteInfo = cmf_get_site_info();
  1106. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1107. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1108. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1109. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi{$wxInfo['nickname']},欢迎关注{$siteName}!";
  1110. }
  1111. }
  1112. }
  1113. // 已关注
  1114. if (in_array($event, ['SCAN', 'text', 'subscribe'])) {
  1115. if ($event === 'SCAN' || ($event === 'subscribe' && $contentStr == '') || $event == 'text') {
  1116. $wxInfo = Wechat::getUserInfo($openid, false, true);
  1117. if ($wxInfo) {
  1118. // 用户信息
  1119. $userData = [
  1120. 'sex' => $wxInfo['sex'],
  1121. 'openid' => $openid,
  1122. 'user_nickname' => $wxInfo['nickname'],
  1123. 'avatar' => $wxInfo['headimgurl'],
  1124. 'wxInfo' => $wxInfo,
  1125. ];
  1126. // 验证注册用户,并发送关注信息
  1127. PRedis::set('weixin:reg:'.$openid, ['info'=> $wxInfo, 'regInfo'=> $userData], 600);
  1128. Member::regMember($userData);
  1129. $siteInfo = cmf_get_site_info();
  1130. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1131. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1132. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1133. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi【{$nickname}】,欢迎关注{$siteName}!";
  1134. }
  1135. }
  1136. // 更新关注
  1137. Member::saveData(['openid'=> $openid],['is_follow'=> isset($wxInfo['subscribe'])? intval($wxInfo['subscribe']) : 0]);
  1138. $userInfo = Member::getInfo(['openid' => $openid]);
  1139. PRedis::set('follow:'.$openid, $wxInfo, 600);
  1140. session('userInfo', $userInfo);
  1141. // 推送用户注册消息
  1142. $contentStr = $contentStr ? $contentStr : '您好,欢迎关注本公众号';
  1143. // $info = Member::where(['openid' => $openid])->field('id,real_name,mobile')->find();
  1144. $replyUrl = config('weixin.reply_url');
  1145. if ($replyUrl) {
  1146. $url = Wechat::makeRedirectUrl(url('/weixin/match/index', '', '', true));
  1147. $contentStr .= "\n\n<a href='{$url}'>点击开启你的脱单之旅</a>";
  1148. }
  1149. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1150. // 推送邀请注册奖励消息
  1151. if ($inviteData) {
  1152. $inviteOpenid = isset($inviteData['openid']) ? $inviteData['openid'] : '';
  1153. $message = isset($inviteData['message']) ? $inviteData['message'] : '';
  1154. if ($inviteOpenid && $message) {
  1155. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1156. }
  1157. }
  1158. }else if($event == 'unsubscribe'){
  1159. $cacheKey = "weixin:auth:".$openid;
  1160. PRedis::del($cacheKey);
  1161. session('userInfo', null);
  1162. }
  1163. // 删除缓存锁
  1164. PRedis::del($lockKey);
  1165. exit;
  1166. }
  1167. /**
  1168. * 响应消息
  1169. * @param $postObj
  1170. */
  1171. public static function responseText($postObj)
  1172. {
  1173. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  1174. $msgId = isset($postObj['MsgId']) ? $postObj['MsgId'] : '';
  1175. $keyword = isset($postObj['Content']) ? trim($postObj['Content']) : '';
  1176. $cacheKey = "messages:replys:{$msgId}";
  1177. if(PRedis::get($cacheKey)){
  1178. return false;
  1179. }
  1180. // 验证关键词回复
  1181. PRedis::set($cacheKey, $postObj, 300);
  1182. if($keyword){
  1183. $replyData = Reply::where(['keyword'=> $keyword, 'status'=> 1])
  1184. ->field('type,reply_type,title,media_id,content')
  1185. ->find();
  1186. if($replyData){
  1187. $msgData = [];
  1188. $type = isset($replyData['type'])? intval($replyData['type']) : 1;
  1189. $replyType = isset($replyData['reply_type'])? intval($replyData['reply_type']) : 1;
  1190. switch($type){
  1191. case 1: // 图片
  1192. // 文字回复
  1193. $content = isset($replyData['content'])? trim($replyData['content']) : '';
  1194. // 二维码回复
  1195. $mediaId = isset($replyData['media_id'])? trim($replyData['media_id']) : '';
  1196. if($mediaId){
  1197. $msgData = ['media_id'=> $mediaId];
  1198. }
  1199. // 回复图片
  1200. if($msgData){
  1201. // 回复文字
  1202. if($content){
  1203. Wechat::sendCustomMsg($openid, ['content' => $content]);
  1204. }
  1205. PRedis::set('message:temp:'.$openid, ['text'=> $content, 'media'=> $msgData], 600);
  1206. Wechat::sendCustomMsg($openid, $msgData,'image');
  1207. //Wechat::rebackOk();
  1208. exit;
  1209. }
  1210. break;
  1211. case 2: // 文字
  1212. $content = isset($replyData['content'])? trim($replyData['content']) : '';
  1213. // 回复文字
  1214. if($content){
  1215. Wechat::sendCustomMsg($openid, ['content' => $content]);
  1216. exit;
  1217. }
  1218. break;
  1219. case 3: // 图文
  1220. break;
  1221. }
  1222. }
  1223. }
  1224. // 通用回复
  1225. /*
  1226. $siteInfo = cmf_get_site_info();
  1227. $wxInfo = Wechat::getUserInfo($openid);
  1228. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1229. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1230. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1231. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi{$nickname},欢迎关注{$siteName}!";
  1232. $replyUrl = config('weixin.reply_url');
  1233. if ($replyUrl) {
  1234. $url = Wechat::makeRedirectUrl(url('/weixin/match/index', '', '', true));
  1235. $contentStr .= "\n\n<a href='{$url}'>点击开启你的脱单之旅</a>";
  1236. }
  1237. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1238. */
  1239. //Wechat::rebackOk();
  1240. echo ' ';
  1241. exit;
  1242. }
  1243. /**
  1244. * 响应消息
  1245. * @param $fromUsername 发送用户
  1246. * @param $toUsername 接收用户
  1247. * @param $contentStr 发送内容
  1248. * @param string $msgType 消息类型
  1249. */
  1250. public static function responseTplMsg($fromUsername, $toUsername, $contentStr, $msgType = 'text')
  1251. {
  1252. $textTpl = "<xml>
  1253. <ToUserName><![CDATA[%s]]></ToUserName>
  1254. <FromUserName><![CDATA[%s]]></FromUserName>
  1255. <CreateTime>%s</CreateTime>
  1256. <MsgType><![CDATA[%s]]></MsgType>
  1257. <Content><![CDATA[%s]]></Content>
  1258. </xml>";
  1259. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
  1260. echo $resultStr;
  1261. exit;
  1262. }
  1263. /**
  1264. * 创建菜单
  1265. * @param array $menus 菜单数组数据
  1266. * @params $delete 是否删除就菜单
  1267. * @return bool
  1268. */
  1269. public static function createMenu($menus = [], $delete = false)
  1270. {
  1271. $weixinConfig = config('weixin.');
  1272. $menus = $menus ? $menus : (isset($weixinConfig['menus']) ? $weixinConfig['menus'] : []);
  1273. if (empty($menus)) {
  1274. return false;
  1275. }
  1276. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1277. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1278. if (empty($token)) {
  1279. return false;
  1280. }
  1281. // 删除菜单
  1282. if ($delete) {
  1283. Wechat::delMenu();
  1284. }
  1285. $url = sprintf(self::$apiUrl['createMenu'], $token);
  1286. $result = httpRequest($url, json_encode(['button' => $menus], 256));
  1287. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1288. if ($errorCode != 0) {
  1289. return false;
  1290. }
  1291. return $result;
  1292. }
  1293. /**
  1294. * 删除菜单
  1295. * @return bool
  1296. */
  1297. public static function delMenu()
  1298. {
  1299. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1300. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1301. $url = sprintf(self::$apiUrl['delMenu'], $token);
  1302. $result = httpRequest($url);
  1303. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1304. if ($errorCode == 0) {
  1305. return false;
  1306. }
  1307. return true;
  1308. }
  1309. /**
  1310. * 查询菜单
  1311. * @return bool
  1312. */
  1313. public static function getMenu()
  1314. {
  1315. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1316. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1317. $url = sprintf(self::$apiUrl['getMenu'], $token);
  1318. $result = httpRequest($url);
  1319. return $result;
  1320. }
  1321. /**
  1322. * 发送客服消息
  1323. * @param $openid 接受用户OPENID
  1324. * @param $content 消息内容:数组
  1325. * @param string $msgType 消息类型
  1326. * @return mixed
  1327. */
  1328. public static function sendCustomMsg($openid, $content, $msgType = 'text')
  1329. {
  1330. $data = [
  1331. 'touser' => $openid,
  1332. 'msgtype' => $msgType,
  1333. $msgType => $content
  1334. ];
  1335. $lockKey = 'weixin:custonLock:' . $openid . '_' . md5(json_encode($data));
  1336. if (PRedis::get($lockKey)) {
  1337. return false;
  1338. }
  1339. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1340. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1341. PRedis::set($lockKey, $data, 5);
  1342. $url = sprintf(self::$apiUrl['customMessage'], $token);
  1343. $result = httpRequest($url, json_encode($data, 256));
  1344. PRedis::set('weixin:customLock:' . $openid . '_' . date('YmdHis'), ['data' => $data, 'tokenData' => $tokenData, 'result' => $result], 3);
  1345. return $result;
  1346. }
  1347. /**
  1348. * 发送模板消息
  1349. * @param $openid OPENID
  1350. * @param $params 参数:title-标题(必填),type-模板类型标识字符串(必填),keywords-模板字段数据(必填),url-模板跳转链接,remark-模板备注信息
  1351. * @return array|int
  1352. */
  1353. public static function sendTplMsg($openid, $params, $formatUrl=true)
  1354. {
  1355. $title = isset($params['title']) ? $params['title'] : '';
  1356. $remark = isset($params['remark']) ? $params['remark'] : '';
  1357. $type = isset($params['type']) ? $params['type'] : 'default';
  1358. $keywords = isset($params['keywords']) ? $params['keywords'] : [];
  1359. $keywords = $keywords ? $keywords : [];
  1360. if ($title) {
  1361. $keywords['first'] = ['value' => $title, 'color' => '#173177'];
  1362. }
  1363. if ($remark) {
  1364. $keywords['remark'] = ['value' => $remark, 'color' => '#173177'];
  1365. }
  1366. $templates = cmf_get_option('templates');
  1367. $templateId = isset($templates[$type . '_template']) ? trim($templates[$type . '_template']) : '';
  1368. if (empty($templateId)) {
  1369. return 2110;
  1370. }
  1371. ksort($keywords);
  1372. $tplData = [
  1373. 'touser' => $openid,
  1374. 'template_id' => $templateId,
  1375. 'data' => $keywords,
  1376. ];
  1377. $url = isset($params['url']) ? trim($params['url']) : '';
  1378. if ($url) {
  1379. $tplData['url'] = $formatUrl? Wechat::makeRedirectUrl($url) : $url;
  1380. }
  1381. // 删除旧数据,新增消息记录
  1382. $expire = config('weixin.message_expire');
  1383. $expire = $expire? $expire : 7;
  1384. $day = date('Y-m-d H:i:s', strtotime("-{$expire} days"));
  1385. $deleteKey = "messages:delete:".$openid;
  1386. if(!PRedis::get($deleteKey)){
  1387. Message::where('created_at','<=', $day)->delete();
  1388. PRedis::set($deleteKey, $day, 120);
  1389. }
  1390. $data = [
  1391. 'title' => $title,
  1392. 'type' => 2,
  1393. 'msg_tpl' => $type,
  1394. 'openid' => $openid,
  1395. 'content' => json_encode($tplData, 256),
  1396. 'created_at' => date('Y-m-d H:i:s'),
  1397. 'updated_at' => date('Y-m-d H:i:s'),
  1398. 'status' => 1,
  1399. ];
  1400. $id = Message::insertGetId($data);
  1401. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1402. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1403. if (empty($token)) {
  1404. return 1010;
  1405. }
  1406. $url = sprintf(self::$apiUrl['tplMessage'], $token);
  1407. $result = httpRequest($url, json_encode($tplData, 256));
  1408. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1409. PRedis::set('messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1410. if ($code == 'ok') {
  1411. Message::where(['id' => $id])
  1412. ->update(['send_at' => date('Y-m-d H:i:s'), 'status' => 2]);
  1413. return ['id' => $id, 'message' => 2112];
  1414. } else {
  1415. $result = httpRequest($url, json_encode($tplData, 256));
  1416. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1417. PRedis::set('messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1418. if ($code === 0) {
  1419. Message::where(['id' => $id])
  1420. ->update(['send_at' => date('Y-m-d H:i:s'), 'status' => 2]);
  1421. return ['id' => $id, 'message' => 2112];
  1422. }
  1423. }
  1424. return 2113;
  1425. }
  1426. /**
  1427. * 获取消息模板列表
  1428. * @return int|mixed
  1429. */
  1430. public static function getTemplateList(){
  1431. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1432. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1433. if (empty($token)) {
  1434. return 1010;
  1435. }
  1436. $url = sprintf(self::$apiUrl['templateList'], $token);
  1437. $result = httpRequest($url);
  1438. PRedis::set('messages:templates', $result, 600);
  1439. return $result;
  1440. }
  1441. /**
  1442. * 上传媒体素材
  1443. * @param $file 素材文件本地相对路径
  1444. * @param int $title 素材名称或标题
  1445. * @param int $type 素材类型:1-图片,2-语音,3-视频,4-缩略图
  1446. * @param bool $refresh 是否刷新缓存重新上传
  1447. * @return bool|int|mixed
  1448. */
  1449. public static function uploadMedia($file, $title='', $type=1, $refresh=false){
  1450. $mediaFile = 'upload/'.$file;
  1451. if(!file_exists($mediaFile)){
  1452. return false;
  1453. }
  1454. $types = [1=>'image',2=>'voice',3=>'video',4=>'thumb'];
  1455. $typeValue = isset($types[$type])? $types[$type] : '';
  1456. if(!$typeValue){
  1457. return false;
  1458. }
  1459. $cacheKey = "medias:{$typeValue}:".md5($mediaFile);
  1460. $mediaData = PRedis::get($cacheKey);
  1461. if($mediaData && !$refresh){
  1462. return $mediaData;
  1463. }
  1464. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1465. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1466. if (empty($token)) {
  1467. return false;
  1468. }
  1469. @chmod($mediaFile, 0755);
  1470. $url = sprintf(self::$apiUrl['uploadMedia'], $token, $typeValue);
  1471. if(class_exists('CURLFile')){
  1472. $postData = ['media'=> new \CURLFile(realpath($mediaFile))];
  1473. }else{
  1474. $postData = ['media'=> '@'.realpath($mediaFile)];
  1475. }
  1476. $result = httpFilePost($url, $postData);
  1477. $mediaId = isset($result['media_id'])? $result['media_id'] : '';
  1478. $mediaUrl = isset($result['url'])? $result['url'] : '';
  1479. // 存库处理
  1480. if($result && $mediaId && $mediaUrl){
  1481. $data = [
  1482. 'type'=> $type,
  1483. 'title'=> $title? $title : '素材文件',
  1484. 'url'=> $file,
  1485. 'media_id'=> $mediaId,
  1486. 'media_url'=> $mediaUrl,
  1487. 'updated_at'=> date('Y-m-d H:i:s'),
  1488. ];
  1489. $id = Medias::insertGetId($data);
  1490. if(!$id){
  1491. return false;
  1492. }
  1493. $result['id'] = $id;
  1494. PRedis::set($cacheKey, $result);
  1495. return $result;
  1496. }
  1497. return false;
  1498. }
  1499. public static function makeShortUrl($url){
  1500. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1501. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1502. //$token = '30_WxzS6qNfeaIr1v3Rx_0Ons1D54Usci17_pVyeQGWJbarCZQNV-lo6nD3IKEJmzY_8ZHClzno32BQhNXzfIF-cu_5DMDnqBV9FtnjUXL4k0zD6oskOXj7I6WNuDDjxTz20P_EELHJrbphEDJ6TRWdAAALJO';
  1503. if (empty($token)) {
  1504. return $url;
  1505. }
  1506. $apiUrl = sprintf(self::$apiUrl['shortUrl'], $token);
  1507. $result = httpFilePost($apiUrl, json_encode(['action'=> 'long2short','long_url'=> $url], 256));
  1508. $shortUrl = isset($result['short_url'])? trim($result['short_url']) : '';
  1509. return $shortUrl? $shortUrl : $url;
  1510. }
  1511. /**
  1512. * 生成普通参数二维码
  1513. * @param $str 参数
  1514. * @param bool $refresh 是否重新生成
  1515. * @return bool
  1516. */
  1517. public static function makeNormalQrcode($str, $refresh = false, $size = 8, $margin=2)
  1518. {
  1519. $qrFile = '/upload/qrcode/member/';
  1520. if (!is_dir($qrFile)) {
  1521. @mkdir('.' . $qrFile, 0755, true);
  1522. }
  1523. $qrFile = $qrFile . 'U_' . strtoupper(md5($str . '_' . $size)) . '.jpg';
  1524. if (is_file($qrFile) && !$refresh) {
  1525. return false;
  1526. }
  1527. QRcode::png($str, '.' . $qrFile, 2, $size, $margin);
  1528. if(!file_exists('.'.$qrFile)){
  1529. return false;
  1530. }
  1531. return $qrFile;
  1532. }
  1533. /**
  1534. * 返回给微信
  1535. */
  1536. public static function rebackOk(){
  1537. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  1538. exit;
  1539. }
  1540. }
  1541. ?>