Wechat.php 64 KB

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