Wechat.php 63 KB

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