Wechat.php 67 KB

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