Wechat.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  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. curl_close($ch);
  863. return $data;
  864. }
  865. /**
  866. * 数组转XML
  867. * @param $arr 数组数据
  868. * @return string
  869. */
  870. public static function arrayToXml($arr)
  871. {
  872. $xml = "<xml>";
  873. foreach ($arr as $key => $val) {
  874. if ($key == 'detail') {
  875. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  876. } else {
  877. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  878. }
  879. }
  880. $xml .= "</xml>";
  881. return $xml;
  882. }
  883. /**
  884. * 签名参数格式化
  885. * @param $paraMap 参数
  886. * @param bool $urlEncode 是否编码
  887. * @return bool|string
  888. */
  889. protected static function formatParams($paraMap, $urlEncode = false)
  890. {
  891. $buff = "";
  892. ksort($paraMap);
  893. foreach ($paraMap as $k => $v) {
  894. if (null != $v && "null" != $v) {
  895. if ($urlEncode) {
  896. $v = urlencode($v);
  897. }
  898. $buff .= $k . "=" . $v . "&";
  899. }
  900. }
  901. $reqPar = '';
  902. if (strlen($buff) > 0) {
  903. $reqPar = substr($buff, 0, strlen($buff) - 1);
  904. }
  905. return $reqPar;
  906. }
  907. /**
  908. * 生成微信二维码
  909. * @param int $sourceId 来源ID
  910. * @param $sceneStr 场景参数字符串或ID
  911. * @param $scene 场景标识:qrcode-用户二维码
  912. * @param string $qrType 二维码生成类型:QR_SCENE, QR_STR_SCENE, QR_LIMIT_SCENE, QR_LIMIT_STR_SCENE
  913. * @param int $expire 有效期,配合场景类型使用,临时二维码最长30天有效期,0-永久
  914. * @return array|bool
  915. * @throws \think\Exception
  916. * @throws \think\db\exception\DataNotFoundException
  917. * @throws \think\db\exception\ModelNotFoundException
  918. * @throws \think\exception\DbException
  919. * @throws \think\exception\PDOException
  920. */
  921. public static function makeQrcode($sourceId = 0, $sceneStr = '', $scene = 'qrcode', $qrType = 'QR_STR_SCENE', $expire = -1)
  922. {
  923. $expire = $expire>=0 ? $expire : 24 * 3600 * 20;
  924. $tokenData = Wechat::getAccessToken('', 'accessToken');
  925. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  926. $qrData = db('qrcode')
  927. ->where(['source_id' => $sourceId, 'scene' => $scene, 'status' => 1])
  928. ->field('id,source_id,ticket,url,expire_at')
  929. ->find();
  930. $qrcodeId = isset($qrData['id']) ? $qrData['id'] : 0;
  931. $qrcodeExpire = isset($qrData['expire_at']) ? strtotime($qrData['expire_at']) : 0;
  932. if (($expire==0 && $qrcodeId) || $qrcodeExpire > time() && $qrcodeId) {
  933. $ticket = isset($qrData['ticket']) ? $qrData['ticket'] : '';
  934. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  935. $qrData['qrcode'] = Wechat::loadImage($qrcode, $scene);
  936. if($qrData['qrcode']){
  937. return $qrData;
  938. }
  939. }
  940. if (empty($token)) {
  941. $tokenData = Wechat::getAccessToken('', 'accessToken', true);
  942. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  943. if (empty($token)) {
  944. return 1010;
  945. }
  946. }
  947. if (!in_array($qrType, ['QR_SCENE', 'QR_STR_SCENE', 'QR_LIMIT_SCENE', 'QR_LIMIT_STR_SCENE'])) {
  948. return 2111;
  949. }
  950. $data = [
  951. 'expire_seconds' => $expire,
  952. 'action_name' => $qrType,
  953. ];
  954. if (in_array($qrType, ['QR_SCENE', 'QR_LIMIT_SCENE'])) {
  955. $data['action_info'] = ['scene' => ['scene_id' => $sceneStr]];
  956. } else {
  957. $data['action_info'] = ['scene' => ['scene_str' => $scene . '_' . $sceneStr]];
  958. }
  959. $url = sprintf(self::$apiUrl['makeQrcode'], $token);
  960. $result = httpRequest($url, json_encode($data, 256));
  961. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  962. PRedis::set('qrcodes:result', ['url'=> $url, 'params'=> $data, 'result'=> $result], 600);
  963. if ($result && $ticket) {
  964. $qrData = [
  965. 'source_id' => $sourceId,
  966. 'scene' => $scene,
  967. 'scene_str' => $sceneStr,
  968. 'ticket' => $ticket,
  969. 'expire_at' => $expire>0? date('Y-m-d H:i:s', time() + $expire) : null,
  970. 'url' => isset($result['url']) ? $result['url'] : '',
  971. ];
  972. if ($qrcodeId) {
  973. $qrData['updated_at'] = date('Y-m-d H:i:s');
  974. $qrcodeId = db('qrcode')->where(['id' => $qrcodeId])->update($qrData);
  975. } else {
  976. $qrData['created_at'] = date('Y-m-d H:i:s');
  977. $qrcodeId = db('qrcode')->insertGetId($qrData);
  978. $qrData['id'] = $qrcodeId;
  979. }
  980. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  981. $qrData['qrcode'] = Wechat::loadImage($qrcode, $scene, true);
  982. }
  983. return $qrcodeId > 0 ? $qrData : 1009;
  984. }
  985. /**
  986. * 下载图片
  987. * @param $file 远程文件
  988. * @param string $type 类型
  989. * @return bool|string
  990. */
  991. public static function loadImage($file, $type='qrcode', $refresh=false){
  992. if(empty($file)){
  993. return false;
  994. }
  995. $key = "members:{$type}:".md5($file);
  996. $qrcode = PRedis::get($key);
  997. if(empty($qrcode) || $refresh){
  998. $qrcodeContent = file_get_contents($file);
  999. if($qrcodeContent){
  1000. if(!is_dir("upload/{$type}/weixin/")){
  1001. mkdir("upload/{$type}/weixin/", 0755, true);
  1002. }
  1003. $qrcode = "{$type}/weixin/QR_".md5($file).'.jpg';
  1004. file_put_contents("upload/".$qrcode, $qrcodeContent);
  1005. PRedis::set($key, $qrcode, 7 * 24 * 3600);
  1006. }
  1007. }
  1008. if(!file_exists('./upload/'.$qrcode)){
  1009. return false;
  1010. }
  1011. return cmf_get_image_preview_url($qrcode);
  1012. }
  1013. /**
  1014. * 获取微信二维码数据
  1015. * @param $where 条件
  1016. * @param string $field 返回字段
  1017. * @return bool
  1018. * @throws \think\db\exception\DataNotFoundException
  1019. * @throws \think\db\exception\ModelNotFoundException
  1020. * @throws \think\exception\DbException
  1021. */
  1022. public static function getQrcode($where, $field = '')
  1023. {
  1024. if (!is_array($where)) {
  1025. return false;
  1026. }
  1027. $where['status'] = 1;
  1028. $field = $field ? $field : 'id,source_id,scene,ticket,url';
  1029. $info = db('qrcode')
  1030. ->where($where)
  1031. ->where('expire_at', '>', date('Y-m-d H:i:s'))
  1032. ->field($field)
  1033. ->find();
  1034. $ticket = isset($info['ticket']) ? $info['ticket'] : '';
  1035. if ($info && $ticket) {
  1036. $info['qrcode'] = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  1037. }
  1038. return $info;
  1039. }
  1040. /**
  1041. * 处理扫码推荐关注
  1042. * @param $postObj
  1043. */
  1044. public static function catchEvent($postObj)
  1045. {
  1046. $contentStr = '';
  1047. $inviteData = [];
  1048. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  1049. $event = isset($postObj['Event']) ? $postObj['Event'] : '';
  1050. $eventKey = isset($postObj['EventKey']) ? $postObj['EventKey'] : '';
  1051. $lockKey = "weixin:lock:" . $openid . '_' . $event;
  1052. $lock = PRedis::get($lockKey);
  1053. if ($lock) {
  1054. return false;
  1055. }
  1056. PRedis::set($lockKey, $postObj, 8);
  1057. PRedis::set('weixin:events:'.$openid,$postObj, 3600);
  1058. if ($event && $eventKey) {
  1059. // 未关注
  1060. if ($event == 'subscribe' || $event == 'SCAN') {
  1061. $sceneStr = $event == 'subscribe'? substr($eventKey, 8) : $eventKey;
  1062. $sceneData = $sceneStr ? explode('_', $sceneStr) : [];
  1063. $scene = isset($sceneData[0]) ? $sceneData[0] : '';
  1064. $sceneValue = isset($sceneData[2]) ? $sceneData[2] : '';
  1065. $sceneValue = $sceneValue? $sceneValue : (isset($sceneData[1]) ? $sceneData[1] : '');
  1066. // 用户信息注册或更新
  1067. $wxInfo = Wechat::getUserInfo($openid, false, true);
  1068. if ($wxInfo) {
  1069. $userData = [
  1070. 'sex' => $wxInfo['sex'],
  1071. 'openid' => $openid,
  1072. 'user_nickname' => $wxInfo['nickname'],
  1073. 'avatar' => $wxInfo['headimgurl'],
  1074. 'wxInfo' => $wxInfo,
  1075. ];
  1076. // 验证注册用户,并且推送关注信息
  1077. PRedis::set('members:invite:'.$openid, ['reg'=> $userData, 'params'=> $postObj,'scene'=> $scene, 'inviteId'=> $sceneValue], 600);
  1078. $res = Member::regMember($userData);
  1079. PRedis::set('members:register:'.$openid, ['reg'=> $userData, 'result'=> $res], 600);
  1080. // 注册奖励
  1081. $regUserId = isset($res['userId'])? $res['userId'] : 0;
  1082. $regType = isset($res['type'])? $res['type'] : 0;
  1083. if($regType == 2 && $regUserId){
  1084. $updateData = [];
  1085. switch ($scene) {
  1086. case 'qrcode': // 扫码推荐邀请
  1087. if ($sceneValue) {
  1088. // 验证推荐人
  1089. $inviteUserId = Member::where(['id' => $sceneValue, 'user_type' => 2])
  1090. ->value('id');
  1091. if ($inviteUserId) {
  1092. // 绑定上级推荐人
  1093. $updateData['parent_id'] = $inviteUserId;
  1094. $userData['id'] = $regUserId;
  1095. // 处理推荐奖励
  1096. PRedis::set('members:inviteAward:'.$openid, ['user'=> $userData,'inviteId'=> $inviteUserId], 600);
  1097. if($event == 'subscribe'){
  1098. $inviteData = Award::inviteUser($inviteUserId, $userData);
  1099. }
  1100. }
  1101. }
  1102. break;
  1103. }
  1104. if($updateData){
  1105. Member::saveData(['id'=> $regUserId],$updateData);
  1106. }
  1107. }
  1108. $siteInfo = cmf_get_site_info();
  1109. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1110. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1111. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1112. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi{$wxInfo['nickname']},欢迎关注{$siteName}!";
  1113. }
  1114. }
  1115. }
  1116. // 已关注
  1117. if (in_array($event, ['SCAN', 'text', 'subscribe'])) {
  1118. if ($event === 'SCAN' || ($event === 'subscribe' && $contentStr == '') || $event == 'text') {
  1119. $wxInfo = Wechat::getUserInfo($openid, false, true);
  1120. if ($wxInfo) {
  1121. // 用户信息
  1122. $userData = [
  1123. 'sex' => $wxInfo['sex'],
  1124. 'openid' => $openid,
  1125. 'user_nickname' => $wxInfo['nickname'],
  1126. 'avatar' => $wxInfo['headimgurl'],
  1127. 'wxInfo' => $wxInfo,
  1128. ];
  1129. // 验证注册用户,并发送关注信息
  1130. PRedis::set('weixin:reg:'.$openid, ['info'=> $wxInfo, 'invite'=> $postObj, 'regInfo'=> $userData], 600);
  1131. Member::regMember($userData);
  1132. $siteInfo = cmf_get_site_info();
  1133. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1134. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1135. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1136. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi【{$nickname}】,欢迎关注{$siteName}!";
  1137. }
  1138. }
  1139. // 更新关注
  1140. Member::saveData(['openid'=> $openid],['is_follow'=> isset($wxInfo['subscribe'])? intval($wxInfo['subscribe']) : 0]);
  1141. $userInfo = Member::getInfo(['openid' => $openid]);
  1142. PRedis::set('follow:'.$openid, $wxInfo, 600);
  1143. session('userInfo', $userInfo);
  1144. // 推送用户注册消息
  1145. $contentStr = $contentStr ? $contentStr : '您好,欢迎关注本公众号';
  1146. // $info = Member::where(['openid' => $openid])->field('id,real_name,mobile')->find();
  1147. $replyUrl = config('weixin.reply_url');
  1148. if ($replyUrl) {
  1149. $url = Wechat::makeRedirectUrl(url('/weixin/match/index', '', '', true));
  1150. $contentStr .= "\n\n<a href='{$url}'>点击开启你的脱单之旅</a>";
  1151. }
  1152. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1153. // 推送邀请注册奖励消息
  1154. if ($inviteData) {
  1155. $inviteOpenid = isset($inviteData['openid']) ? $inviteData['openid'] : '';
  1156. $message = isset($inviteData['message']) ? $inviteData['message'] : '';
  1157. if ($inviteOpenid && $message) {
  1158. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1159. }
  1160. }
  1161. }else if($event == 'unsubscribe'){
  1162. $cacheKey = "weixin:auth:".$openid;
  1163. PRedis::del($cacheKey);
  1164. session('userInfo', null);
  1165. }
  1166. // 删除缓存锁
  1167. PRedis::del($lockKey);
  1168. exit;
  1169. }
  1170. /**
  1171. * 响应消息
  1172. * @param $postObj
  1173. */
  1174. public static function responseText($postObj)
  1175. {
  1176. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  1177. $msgId = isset($postObj['MsgId']) ? $postObj['MsgId'] : '';
  1178. $keyword = isset($postObj['Content']) ? trim($postObj['Content']) : '';
  1179. $cacheKey = "messages:replys:{$msgId}";
  1180. if(PRedis::get($cacheKey)){
  1181. return false;
  1182. }
  1183. // 验证关键词回复
  1184. PRedis::set($cacheKey, $postObj, 300);
  1185. if($keyword){
  1186. $replyData = Reply::where(['keyword'=> $keyword, 'status'=> 1])
  1187. ->field('type,reply_type,title,media_id,content')
  1188. ->find();
  1189. if($replyData){
  1190. $msgData = [];
  1191. $type = isset($replyData['type'])? intval($replyData['type']) : 1;
  1192. $replyType = isset($replyData['reply_type'])? intval($replyData['reply_type']) : 1;
  1193. switch($type){
  1194. case 1: // 图片
  1195. // 文字回复
  1196. $content = isset($replyData['content'])? trim($replyData['content']) : '';
  1197. // 二维码回复
  1198. $mediaId = isset($replyData['media_id'])? trim($replyData['media_id']) : '';
  1199. if($mediaId){
  1200. $msgData = ['media_id'=> $mediaId];
  1201. }
  1202. // 回复图片
  1203. if($msgData){
  1204. // 回复文字
  1205. if($content){
  1206. Wechat::sendCustomMsg($openid, ['content' => $content]);
  1207. }
  1208. PRedis::set('message:temp:'.$openid, ['text'=> $content, 'media'=> $msgData], 600);
  1209. Wechat::sendCustomMsg($openid, $msgData,'image');
  1210. //Wechat::rebackOk();
  1211. exit;
  1212. }
  1213. break;
  1214. case 2: // 文字
  1215. $content = isset($replyData['content'])? trim($replyData['content']) : '';
  1216. // 回复文字
  1217. if($content){
  1218. Wechat::sendCustomMsg($openid, ['content' => $content]);
  1219. exit;
  1220. }
  1221. break;
  1222. case 3: // 图文
  1223. break;
  1224. }
  1225. }
  1226. }
  1227. // 通用回复
  1228. /*
  1229. $siteInfo = cmf_get_site_info();
  1230. $wxInfo = Wechat::getUserInfo($openid);
  1231. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1232. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1233. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1234. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi{$nickname},欢迎关注{$siteName}!";
  1235. $replyUrl = config('weixin.reply_url');
  1236. if ($replyUrl) {
  1237. $url = Wechat::makeRedirectUrl(url('/weixin/match/index', '', '', true));
  1238. $contentStr .= "\n\n<a href='{$url}'>点击开启你的脱单之旅</a>";
  1239. }
  1240. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1241. */
  1242. //Wechat::rebackOk();
  1243. echo ' ';
  1244. exit;
  1245. }
  1246. /**
  1247. * 响应消息
  1248. * @param $fromUsername 发送用户
  1249. * @param $toUsername 接收用户
  1250. * @param $contentStr 发送内容
  1251. * @param string $msgType 消息类型
  1252. */
  1253. public static function responseTplMsg($fromUsername, $toUsername, $contentStr, $msgType = 'text')
  1254. {
  1255. $textTpl = "<xml>
  1256. <ToUserName><![CDATA[%s]]></ToUserName>
  1257. <FromUserName><![CDATA[%s]]></FromUserName>
  1258. <CreateTime>%s</CreateTime>
  1259. <MsgType><![CDATA[%s]]></MsgType>
  1260. <Content><![CDATA[%s]]></Content>
  1261. </xml>";
  1262. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
  1263. echo $resultStr;
  1264. exit;
  1265. }
  1266. /**
  1267. * 创建菜单
  1268. * @param array $menus 菜单数组数据
  1269. * @params $delete 是否删除就菜单
  1270. * @return bool
  1271. */
  1272. public static function createMenu($menus = [], $delete = false)
  1273. {
  1274. $weixinConfig = config('weixin.');
  1275. $menus = $menus ? $menus : (isset($weixinConfig['menus']) ? $weixinConfig['menus'] : []);
  1276. if (empty($menus)) {
  1277. return false;
  1278. }
  1279. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1280. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1281. if (empty($token)) {
  1282. return false;
  1283. }
  1284. // 删除菜单
  1285. if ($delete) {
  1286. Wechat::delMenu();
  1287. }
  1288. $url = sprintf(self::$apiUrl['createMenu'], $token);
  1289. $result = httpRequest($url, json_encode(['button' => $menus], 256));
  1290. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1291. if ($errorCode != 0) {
  1292. return false;
  1293. }
  1294. return $result;
  1295. }
  1296. /**
  1297. * 删除菜单
  1298. * @return bool
  1299. */
  1300. public static function delMenu()
  1301. {
  1302. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1303. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1304. $url = sprintf(self::$apiUrl['delMenu'], $token);
  1305. $result = httpRequest($url);
  1306. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1307. if ($errorCode == 0) {
  1308. return false;
  1309. }
  1310. return true;
  1311. }
  1312. /**
  1313. * 查询菜单
  1314. * @return bool
  1315. */
  1316. public static function getMenu()
  1317. {
  1318. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1319. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1320. $url = sprintf(self::$apiUrl['getMenu'], $token);
  1321. $result = httpRequest($url);
  1322. return $result;
  1323. }
  1324. /**
  1325. * 发送客服消息
  1326. * @param $openid 接受用户OPENID
  1327. * @param $content 消息内容:数组
  1328. * @param string $msgType 消息类型
  1329. * @return mixed
  1330. */
  1331. public static function sendCustomMsg($openid, $content, $msgType = 'text')
  1332. {
  1333. $data = [
  1334. 'touser' => $openid,
  1335. 'msgtype' => $msgType,
  1336. $msgType => $content
  1337. ];
  1338. $lockKey = 'weixin:custonLock:' . $openid . '_' . md5(json_encode($data));
  1339. if (PRedis::get($lockKey)) {
  1340. return false;
  1341. }
  1342. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1343. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1344. PRedis::set($lockKey, $data, 5);
  1345. $url = sprintf(self::$apiUrl['customMessage'], $token);
  1346. $result = httpRequest($url, json_encode($data, 256));
  1347. PRedis::set('weixin:customLock:' . $openid . '_' . date('YmdHis'), ['data' => $data, 'tokenData' => $tokenData, 'result' => $result], 3);
  1348. return $result;
  1349. }
  1350. /**
  1351. * 发送模板消息
  1352. * @param $openid OPENID
  1353. * @param $params 参数:title-标题(必填),type-模板类型标识字符串(必填),keywords-模板字段数据(必填),url-模板跳转链接,remark-模板备注信息
  1354. * @return array|int
  1355. */
  1356. public static function sendTplMsg($openid, $params, $formatUrl=true)
  1357. {
  1358. $title = isset($params['title']) ? $params['title'] : '';
  1359. $remark = isset($params['remark']) ? $params['remark'] : '';
  1360. $type = isset($params['type']) ? $params['type'] : 'default';
  1361. $keywords = isset($params['keywords']) ? $params['keywords'] : [];
  1362. $keywords = $keywords ? $keywords : [];
  1363. if ($title) {
  1364. $keywords['first'] = ['value' => $title, 'color' => '#173177'];
  1365. }
  1366. if ($remark) {
  1367. $keywords['remark'] = ['value' => $remark, 'color' => '#173177'];
  1368. }
  1369. $templates = cmf_get_option('templates');
  1370. $templateId = isset($templates[$type . '_template']) ? trim($templates[$type . '_template']) : '';
  1371. if (empty($templateId)) {
  1372. return 2110;
  1373. }
  1374. ksort($keywords);
  1375. $tplData = [
  1376. 'touser' => $openid,
  1377. 'template_id' => $templateId,
  1378. 'data' => $keywords,
  1379. ];
  1380. $url = isset($params['url']) ? trim($params['url']) : '';
  1381. if ($url) {
  1382. $tplData['url'] = $formatUrl? Wechat::makeRedirectUrl($url) : $url;
  1383. }
  1384. // 删除旧数据,新增消息记录
  1385. $expire = config('weixin.message_expire');
  1386. $expire = $expire? $expire : 7;
  1387. $day = date('Y-m-d H:i:s', strtotime("-{$expire} days"));
  1388. $deleteKey = "messages:delete:".$openid;
  1389. if(!PRedis::get($deleteKey)){
  1390. Message::where('created_at','<=', $day)->delete();
  1391. PRedis::set($deleteKey, $day, 120);
  1392. }
  1393. $data = [
  1394. 'title' => $title,
  1395. 'type' => 2,
  1396. 'msg_tpl' => $type,
  1397. 'openid' => $openid,
  1398. 'content' => json_encode($tplData, 256),
  1399. 'created_at' => date('Y-m-d H:i:s'),
  1400. 'updated_at' => date('Y-m-d H:i:s'),
  1401. 'status' => 1,
  1402. ];
  1403. $id = Message::insertGetId($data);
  1404. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1405. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1406. if (empty($token)) {
  1407. return 1010;
  1408. }
  1409. $url = sprintf(self::$apiUrl['tplMessage'], $token);
  1410. $result = httpRequest($url, json_encode($tplData, 256));
  1411. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1412. PRedis::set('messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1413. if ($code == 'ok') {
  1414. Message::where(['id' => $id])
  1415. ->update(['send_at' => date('Y-m-d H:i:s'), 'status' => 2]);
  1416. return ['id' => $id, 'message' => 2112];
  1417. } else {
  1418. $result = httpRequest($url, json_encode($tplData, 256));
  1419. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1420. PRedis::set('messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1421. if ($code === 0) {
  1422. Message::where(['id' => $id])
  1423. ->update(['send_at' => date('Y-m-d H:i:s'), 'status' => 2]);
  1424. return ['id' => $id, 'message' => 2112];
  1425. }
  1426. }
  1427. return 2113;
  1428. }
  1429. /**
  1430. * 获取消息模板列表
  1431. * @return int|mixed
  1432. */
  1433. public static function getTemplateList(){
  1434. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1435. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1436. if (empty($token)) {
  1437. return 1010;
  1438. }
  1439. $url = sprintf(self::$apiUrl['templateList'], $token);
  1440. $result = httpRequest($url);
  1441. PRedis::set('messages:templates', $result, 600);
  1442. return $result;
  1443. }
  1444. /**
  1445. * 上传媒体素材
  1446. * @param $file 素材文件本地相对路径
  1447. * @param int $title 素材名称或标题
  1448. * @param int $type 素材类型:1-图片,2-语音,3-视频,4-缩略图
  1449. * @param bool $refresh 是否刷新缓存重新上传
  1450. * @return bool|int|mixed
  1451. */
  1452. public static function uploadMedia($file, $title='', $type=1, $refresh=false){
  1453. $mediaFile = 'upload/'.$file;
  1454. if(!file_exists($mediaFile)){
  1455. return false;
  1456. }
  1457. $types = [1=>'image',2=>'voice',3=>'video',4=>'thumb'];
  1458. $typeValue = isset($types[$type])? $types[$type] : '';
  1459. if(!$typeValue){
  1460. return false;
  1461. }
  1462. $cacheKey = "medias:{$typeValue}:".md5($mediaFile);
  1463. $mediaData = PRedis::get($cacheKey);
  1464. if($mediaData && !$refresh){
  1465. return $mediaData;
  1466. }
  1467. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1468. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1469. if (empty($token)) {
  1470. return false;
  1471. }
  1472. @chmod($mediaFile, 0755);
  1473. $url = sprintf(self::$apiUrl['uploadMedia'], $token, $typeValue);
  1474. if(class_exists('CURLFile')){
  1475. $postData = ['media'=> new \CURLFile(realpath($mediaFile))];
  1476. }else{
  1477. $postData = ['media'=> '@'.realpath($mediaFile)];
  1478. }
  1479. $result = httpFilePost($url, $postData);
  1480. $mediaId = isset($result['media_id'])? $result['media_id'] : '';
  1481. $mediaUrl = isset($result['url'])? $result['url'] : '';
  1482. // 存库处理
  1483. if($result && $mediaId && $mediaUrl){
  1484. $data = [
  1485. 'type'=> $type,
  1486. 'title'=> $title? $title : '素材文件',
  1487. 'url'=> $file,
  1488. 'media_id'=> $mediaId,
  1489. 'media_url'=> $mediaUrl,
  1490. 'updated_at'=> date('Y-m-d H:i:s'),
  1491. ];
  1492. $id = Medias::insertGetId($data);
  1493. if(!$id){
  1494. return false;
  1495. }
  1496. $result['id'] = $id;
  1497. PRedis::set($cacheKey, $result);
  1498. return $result;
  1499. }
  1500. return false;
  1501. }
  1502. public static function makeShortUrl($url){
  1503. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1504. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1505. //$token = '30_WxzS6qNfeaIr1v3Rx_0Ons1D54Usci17_pVyeQGWJbarCZQNV-lo6nD3IKEJmzY_8ZHClzno32BQhNXzfIF-cu_5DMDnqBV9FtnjUXL4k0zD6oskOXj7I6WNuDDjxTz20P_EELHJrbphEDJ6TRWdAAALJO';
  1506. if (empty($token)) {
  1507. return $url;
  1508. }
  1509. $apiUrl = sprintf(self::$apiUrl['shortUrl'], $token);
  1510. $result = httpFilePost($apiUrl, json_encode(['action'=> 'long2short','long_url'=> $url], 256));
  1511. $shortUrl = isset($result['short_url'])? trim($result['short_url']) : '';
  1512. return $shortUrl? $shortUrl : $url;
  1513. }
  1514. /**
  1515. * 生成普通参数二维码
  1516. * @param $str 参数
  1517. * @param bool $refresh 是否重新生成
  1518. * @return bool
  1519. */
  1520. public static function makeNormalQrcode($str, $refresh = false, $size = 8, $margin=2)
  1521. {
  1522. $qrFile = '/upload/qrcode/member/';
  1523. if (!is_dir($qrFile)) {
  1524. @mkdir('.' . $qrFile, 0755, true);
  1525. }
  1526. $qrFile = $qrFile . 'U_' . strtoupper(md5($str . '_' . $size)) . '.jpg';
  1527. if (is_file($qrFile) && !$refresh) {
  1528. return false;
  1529. }
  1530. QRcode::png($str, '.' . $qrFile, 2, $size, $margin);
  1531. if(!file_exists('.'.$qrFile)){
  1532. return false;
  1533. }
  1534. return $qrFile;
  1535. }
  1536. /**
  1537. * 返回给微信
  1538. */
  1539. public static function rebackOk(){
  1540. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  1541. exit;
  1542. }
  1543. }
  1544. ?>