Wechat.php 60 KB

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