Wechat.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  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. //禁止引用外部xml实体
  649. libxml_disable_entity_loader(true);
  650. $result = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
  651. $result = (array)$result;
  652. PRedis::set('orders:'.$scene.':'.$openid.':unifiedResult', ['data'=> $result,'result'=> $data], 600);
  653. if ($result === false) {
  654. return ['code' => 'exception', 'message' => 'parase xml error'];
  655. }
  656. if (isset($result['return_code']) && $result['return_code'] != 'SUCCESS') {
  657. return ['code' => 'error', 'message' => $result['return_msg'],'type'=>'return_code'];
  658. }
  659. if (isset($result['result_code']) && $result['result_code'] != 'SUCCESS') {
  660. return ['code' => 'error', 'message' => $result['err_code'],'type'=>'result_code'];
  661. }
  662. return $result;
  663. }
  664. /**
  665. * 退款订单
  666. */
  667. public static function refundOrder(){
  668. }
  669. /**
  670. * 获取JSAPI支付签名参数
  671. * @param $unifiedOrder 统一下单结果
  672. * @param array $unified 提交统一下单参数
  673. * @return array
  674. */
  675. public static function getJsapiPareams($unifiedOrder, $unified = [])
  676. {
  677. $time = time();
  678. $prepayId = isset($unifiedOrder['prepay_id']) ? $unifiedOrder['prepay_id'] : '';
  679. $params = array(
  680. "appId" => Wechat::getConfigs('appid'),
  681. "timeStamp" => "$time", //这里是字符串的时间戳,不是int,所以需加引号
  682. "nonceStr" => isset($unified['nonce_str']) ? trim($unified['nonce_str']) : Wechat::createNonceStr(),
  683. "package" => "prepay_id=" . $prepayId,
  684. "signType" => 'MD5',
  685. );
  686. // 重签名
  687. $params['sign'] = Wechat::getPaySign($params);
  688. $params['prepay_id'] = $prepayId;
  689. return $params;
  690. }
  691. /**
  692. * 查询订单
  693. * @param $outTradeNo 单号
  694. * @return bool|\SimpleXMLElement
  695. */
  696. public static function queryOrder($outTradeNo)
  697. {
  698. $params['appid'] = Wechat::getConfigs('appid');
  699. $params['mch_id'] = Wechat::getConfigs('mch_id');
  700. $params['nonce_str'] = Wechat::createNonceStr();
  701. $params['out_trade_no'] = $outTradeNo;
  702. //获取签名数据
  703. $params['sign'] = Wechat::getPaySign($params);
  704. $responseXml = Wechat::curlPost(self::$apiUrl['queryOrder'], Wechat::arrayToXml($params));
  705. $result = Wechat::xmlToArray($responseXml);
  706. saveLogCache('OrderPay:jsapiPay:query:' . $outTradeNo, json_encode($result, 256));
  707. $returnCode = isset($result['return_code']) ? $result['return_code'] : '';
  708. $tradState = isset($result['trade_state']) ? $result['trade_state'] : '';
  709. $resultCode = isset($result['result_code']) ? $result['result_code'] : '';
  710. if ($resultCode && $returnCode && $tradState) {
  711. return $result;
  712. } else {
  713. return false;
  714. }
  715. }
  716. /**
  717. * XML转数组
  718. * @param $xml
  719. * @return bool|\SimpleXMLElement
  720. */
  721. private static function xmlToArray($xml)
  722. {
  723. if (empty($xml)) return false;
  724. libxml_disable_entity_loader(true);
  725. return simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  726. }
  727. /**
  728. * 生成随机字符串
  729. * @param int $length 长度
  730. * @return string
  731. */
  732. public static function createNonceStr($length = 16)
  733. {
  734. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  735. $str = '';
  736. for ($i = 0; $i < $length; $i++) {
  737. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  738. }
  739. return $str;
  740. }
  741. /**
  742. * @param $params
  743. * @param $key
  744. * @return string
  745. */
  746. public static function getPaySign($params, $key = '')
  747. {
  748. ksort($params, SORT_STRING);
  749. $key = $key ? $key : Wechat::getConfigs('key');
  750. $taskNo = isset($params['out_trade_no']) ? trim($params['out_trade_no']) : md5(json_encode($params));
  751. $unSignParaString = Wechat::formatParams($params, false);
  752. saveLogCache('OrderPay:jsapiPay:makeSign:' . $taskNo, '签名字符串:' . $unSignParaString . "\n密钥:" . $key);
  753. $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
  754. return $signStr;
  755. }
  756. /**
  757. * 验证JSAPI回调
  758. * @param $notifyData
  759. * @return array|bool
  760. */
  761. public static function checkJsapiNotify($notifyData)
  762. {
  763. if (empty($notifyData)) {
  764. return ['code' => 'error', 'message' => 'parse xml error'];
  765. }
  766. $orderNo = isset($notifyData['out_trade_no']) ? trim($notifyData['out_trade_no']) : '';
  767. $returnCode = isset($notifyData['return_code']) ? trim($notifyData['return_code']) : '';
  768. $resultCode = isset($notifyData['result_code']) ? trim($notifyData['result_code']) : '';
  769. $nofitySign = isset($notifyData['sign']) ? trim($notifyData['sign']) : '';
  770. if ($returnCode != 'SUCCESS') {
  771. $error = isset($notifyData['return_msg']) ? $notifyData['return_msg'] : '';
  772. return ['code' => 'error', 'message' => $error];
  773. }
  774. if ($resultCode != 'SUCCESS') {
  775. $error = isset($notifyData['err_code']) ? $notifyData['err_code'] : '';
  776. return ['code' => 'error', 'message' => $error];
  777. }
  778. // 验证签名
  779. unset($notifyData['sign']);
  780. $sign = Wechat::getPaySign($notifyData);
  781. saveLogCache('OrderPay:jsapiNotify:checkSign:' . $orderNo, '返回签名:' . $nofitySign . "\n当前签名:" . $sign);
  782. if ($nofitySign == $sign) {
  783. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  784. }
  785. return true;
  786. }
  787. /**
  788. * 请求接口
  789. * @param string $url 地址
  790. * @param string $postData xml参数
  791. * @param array $options
  792. * @return mixed
  793. */
  794. public static function curlPost($url = '', $postData = '', $options = array(), $cert=[])
  795. {
  796. if (is_array($postData)) {
  797. $postData = http_build_query($postData);
  798. }
  799. $ch = curl_init();
  800. curl_setopt($ch, CURLOPT_URL, $url);
  801. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  802. curl_setopt($ch, CURLOPT_POST, 1);
  803. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  804. curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
  805. if (!empty($options)) {
  806. curl_setopt_array($ch, $options);
  807. }
  808. var_dump($cert);
  809. if($cert){
  810. if(isset($cert['cert_path']) && $cert['cert_path']){
  811. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  812. curl_setopt($ch,CURLOPT_SSLCERT, $cert['cert_path']);
  813. }
  814. if(isset($cert['key_path']) && $cert['key_path']) {
  815. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  816. curl_setopt($ch, CURLOPT_SSLKEY, $cert['key_path']);
  817. }
  818. }
  819. //https请求 不验证证书和host
  820. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  821. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  822. $data = curl_exec($ch);
  823. curl_close($ch);
  824. return $data;
  825. }
  826. /**
  827. * 数组转XML
  828. * @param $arr 数组数据
  829. * @return string
  830. */
  831. public static function arrayToXml($arr)
  832. {
  833. $xml = "<xml>";
  834. foreach ($arr as $key => $val) {
  835. if ($key == 'detail') {
  836. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  837. } else {
  838. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  839. }
  840. }
  841. $xml .= "</xml>";
  842. return $xml;
  843. }
  844. /**
  845. * 签名参数格式化
  846. * @param $paraMap 参数
  847. * @param bool $urlEncode 是否编码
  848. * @return bool|string
  849. */
  850. protected static function formatParams($paraMap, $urlEncode = false)
  851. {
  852. $buff = "";
  853. ksort($paraMap);
  854. foreach ($paraMap as $k => $v) {
  855. if (null != $v && "null" != $v) {
  856. if ($urlEncode) {
  857. $v = urlencode($v);
  858. }
  859. $buff .= $k . "=" . $v . "&";
  860. }
  861. }
  862. $reqPar = '';
  863. if (strlen($buff) > 0) {
  864. $reqPar = substr($buff, 0, strlen($buff) - 1);
  865. }
  866. return $reqPar;
  867. }
  868. /**
  869. * 生成微信二维码
  870. * @param int $sourceId 来源ID
  871. * @param $sceneStr 场景参数字符串或ID
  872. * @param $scene 场景标识:qrcode-用户二维码
  873. * @param string $qrType 二维码生成类型:QR_SCENE, QR_STR_SCENE, QR_LIMIT_SCENE, QR_LIMIT_STR_SCENE
  874. * @param int $expire 有效期,配合场景类型使用,临时二维码最长30天有效期
  875. * @return array|bool
  876. * @throws \think\Exception
  877. * @throws \think\db\exception\DataNotFoundException
  878. * @throws \think\db\exception\ModelNotFoundException
  879. * @throws \think\exception\DbException
  880. * @throws \think\exception\PDOException
  881. */
  882. public static function makeQrcode($sourceId = 0, $sceneStr = '', $scene = 'qrcode', $qrType = 'QR_STR_SCENE', $expire = 0)
  883. {
  884. $expire = $expire ? $expire : 24 * 3600 * 20;
  885. $tokenData = Wechat::getAccessToken('', 'accessToken');
  886. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  887. $qrData = db('qrcode')
  888. ->where(['source_id' => $sourceId, 'scene' => $scene, 'status' => 1])
  889. ->field('id,source_id,ticket,url,expire_at')
  890. ->find();
  891. $qrcodeId = isset($qrData['id']) ? $qrData['id'] : 0;
  892. $qrcodeExpire = isset($qrData['expire_at']) ? strtotime($qrData['expire_at']) : 0;
  893. if ($qrcodeExpire > time() && $qrcodeId) {
  894. $ticket = isset($qrData['ticket']) ? $qrData['ticket'] : '';
  895. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  896. $qrData['qrcode'] = Wechat::loadImage($qrcode, 'qrcode');
  897. if($qrData['qrcode']){
  898. return $qrData;
  899. }
  900. }
  901. if (empty($token)) {
  902. $tokenData = Wechat::getAccessToken('', 'accessToken', true);
  903. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  904. if (empty($token)) {
  905. return 1010;
  906. }
  907. }
  908. if (!in_array($qrType, ['QR_SCENE', 'QR_STR_SCENE', 'QR_LIMIT_SCENE', 'QR_LIMIT_STR_SCENE'])) {
  909. return 2111;
  910. }
  911. $data = [
  912. 'expire_seconds' => $expire,
  913. 'action_name' => $qrType,
  914. ];
  915. if (in_array($qrType, ['QR_SCENE', 'QR_LIMIT_SCENE'])) {
  916. $data['action_info'] = ['scene' => ['scene_id' => $sceneStr]];
  917. } else {
  918. $data['action_info'] = ['scene' => ['scene_str' => $scene . '_' . $sceneStr]];
  919. }
  920. $url = sprintf(self::$apiUrl['makeQrcode'], $token);
  921. $result = httpRequest($url, json_encode($data, 256));
  922. $ticket = isset($result['ticket']) ? $result['ticket'] : '';
  923. PRedis::set('qrcodes:result', ['url'=> $url, 'params'=> $data, 'result'=> $result], 600);
  924. if ($result && $ticket) {
  925. $qrData = [
  926. 'source_id' => $sourceId,
  927. 'scene' => $scene,
  928. 'scene_str' => $sceneStr,
  929. 'ticket' => $ticket,
  930. 'expire_at' => date('Y-m-d H:i:s', time() + $expire),
  931. 'url' => isset($result['url']) ? $result['url'] : '',
  932. ];
  933. if ($qrcodeId) {
  934. $qrData['updated_at'] = date('Y-m-d H:i:s');
  935. $qrcodeId = db('qrcode')->where(['id' => $qrcodeId])->update($qrData);
  936. } else {
  937. $qrData['created_at'] = date('Y-m-d H:i:s');
  938. $qrcodeId = db('qrcode')->insertGetId($qrData);
  939. $qrData['id'] = $qrcodeId;
  940. }
  941. $qrcode = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  942. $qrData['qrcode'] = Wechat::loadImage($qrcode, 'qrcode', true);
  943. }
  944. return $qrcodeId > 0 ? $qrData : 1009;
  945. }
  946. /**
  947. * 下载图片
  948. * @param $file 远程文件
  949. * @param string $type 类型
  950. * @return bool|string
  951. */
  952. public static function loadImage($file, $type='qrcode', $refresh=false){
  953. if(empty($file)){
  954. return false;
  955. }
  956. $key = "members:{$type}:".md5($file);
  957. $qrcode = PRedis::get($key);
  958. if(empty($qrcode) || $refresh){
  959. $qrcodeContent = file_get_contents($file);
  960. if($qrcodeContent){
  961. if(!is_dir("upload/{$type}/weixin/")){
  962. mkdir("upload/{$type}/weixin/", 0755, true);
  963. }
  964. $qrcode = "{$type}/weixin/QR_".md5($file).'.jpg';
  965. file_put_contents("upload/".$qrcode, $qrcodeContent);
  966. PRedis::set($key, $qrcode, 7 * 24 * 3600);
  967. }
  968. }
  969. if(!file_exists('./upload/'.$qrcode)){
  970. return false;
  971. }
  972. return cmf_get_image_preview_url($qrcode);
  973. }
  974. /**
  975. * 获取微信二维码数据
  976. * @param $where 条件
  977. * @param string $field 返回字段
  978. * @return bool
  979. * @throws \think\db\exception\DataNotFoundException
  980. * @throws \think\db\exception\ModelNotFoundException
  981. * @throws \think\exception\DbException
  982. */
  983. public static function getQrcode($where, $field = '')
  984. {
  985. if (!is_array($where)) {
  986. return false;
  987. }
  988. $where['status'] = 1;
  989. $field = $field ? $field : 'id,source_id,scene,ticket,url';
  990. $info = db('qrcode')
  991. ->where($where)
  992. ->where('expire_at', '>', date('Y-m-d H:i:s'))
  993. ->field($field)
  994. ->find();
  995. $ticket = isset($info['ticket']) ? $info['ticket'] : '';
  996. if ($info && $ticket) {
  997. $info['qrcode'] = sprintf(self::$apiUrl['getQrcodeByTicket'], $ticket);
  998. }
  999. return $info;
  1000. }
  1001. /**
  1002. * 处理扫码推荐关注
  1003. * @param $postObj
  1004. */
  1005. public static function catchEvent($postObj)
  1006. {
  1007. $contentStr = '';
  1008. $inviteData = [];
  1009. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  1010. $event = isset($postObj['Event']) ? $postObj['Event'] : '';
  1011. $eventKey = isset($postObj['EventKey']) ? $postObj['EventKey'] : '';
  1012. $lockKey = "weixin:lock:" . $openid . '_' . $event;
  1013. $lock = PRedis::get($lockKey);
  1014. if ($lock) {
  1015. return false;
  1016. }
  1017. PRedis::set($lockKey, $postObj, 8);
  1018. if ($event && $eventKey) {
  1019. // 未关注
  1020. if ($event == 'subscribe') {
  1021. $sceneStr = substr($eventKey, 8);
  1022. $sceneData = $sceneStr ? explode('_', $sceneStr) : [];
  1023. $scene = isset($sceneData[0]) ? $sceneData[0] : '';
  1024. $sceneValue = isset($sceneData[1]) ? $sceneData[1] : '';
  1025. // 用户信息注册或更新
  1026. $wxInfo = Wechat::getUserInfo($openid, false, true);
  1027. if ($wxInfo) {
  1028. $userData = [
  1029. 'sex' => $wxInfo['sex'],
  1030. 'openid' => $openid,
  1031. 'user_nickname' => $wxInfo['nickname'],
  1032. 'avatar' => $wxInfo['headimgurl'],
  1033. 'wxInfo' => $wxInfo,
  1034. ];
  1035. // 验证注册用户,并且推送关注信息
  1036. PRedis::set('members:invite:'.$openid, ['reg'=> $userData, 'params'=> $postObj], 600);
  1037. $res = Member::regMember($userData);
  1038. PRedis::set('members:register:'.$openid, ['reg'=> $userData, 'result'=> $res], 600);
  1039. // 注册奖励
  1040. $regUserId = isset($res['userId'])? $res['userId'] : 0;
  1041. $regType = isset($res['type'])? $res['type'] : 0;
  1042. if($regType == 2 && $regUserId){
  1043. $updateData = [];
  1044. switch ($scene) {
  1045. case 'qrcode': // 扫码推荐邀请
  1046. if ($sceneValue) {
  1047. // 验证推荐人
  1048. $inviteUserId = Member::where(['id' => $sceneValue, 'user_type' => 2])
  1049. ->value('id');
  1050. if ($inviteUserId) {
  1051. // 绑定上级推荐人
  1052. $updateData['parent_id'] = $inviteUserId;
  1053. $userData['id'] = $regUserId;
  1054. // 处理推荐奖励
  1055. PRedis::set('members:inviteAward:'.$openid, ['user'=> $userData,'inviteId'=> $inviteUserId], 600);
  1056. $inviteData = Award::inviteUser($inviteUserId, $userData);
  1057. }
  1058. }
  1059. break;
  1060. }
  1061. if($updateData){
  1062. Member::saveData(['id'=> $regUserId],$updateData);
  1063. }
  1064. }
  1065. $siteInfo = cmf_get_site_info();
  1066. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1067. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1068. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1069. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi{$wxInfo['nickname']},欢迎关注{$siteName}!";
  1070. }
  1071. }
  1072. }
  1073. // 已关注
  1074. if (in_array($event, ['SCAN', 'text', 'subscribe'])) {
  1075. if ($event === 'SCAN' || ($event === 'subscribe' && $contentStr == '') || $event == 'text') {
  1076. $wxInfo = Wechat::getUserInfo($openid, false, true);
  1077. if ($wxInfo) {
  1078. // 用户信息
  1079. $userData = [
  1080. 'sex' => $wxInfo['sex'],
  1081. 'openid' => $openid,
  1082. 'user_nickname' => $wxInfo['nickname'],
  1083. 'avatar' => $wxInfo['headimgurl'],
  1084. 'wxInfo' => $wxInfo,
  1085. ];
  1086. // 验证注册用户,并发送关注信息
  1087. PRedis::set('weixin:reg:'.$openid, ['info'=> $wxInfo, 'regInfo'=> $userData], 600);
  1088. Member::regMember($userData);
  1089. $siteInfo = cmf_get_site_info();
  1090. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1091. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1092. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1093. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi【{$nickname}】,欢迎关注{$siteName}!";
  1094. }
  1095. }
  1096. // 更新关注
  1097. Member::saveData(['openid'=> $openid],['is_follow'=> isset($wxInfo['subscribe'])? intval($wxInfo['subscribe']) : 0]);
  1098. $userInfo = Member::getInfo(['openid' => $openid]);
  1099. PRedis::set('follow:'.$openid, $wxInfo, 600);
  1100. session('userInfo', $userInfo);
  1101. // 推送用户注册消息
  1102. $contentStr = $contentStr ? $contentStr : '您好,欢迎关注本公众号';
  1103. // $info = Member::where(['openid' => $openid])->field('id,real_name,mobile')->find();
  1104. $replyUrl = config('weixin.reply_url');
  1105. if ($replyUrl) {
  1106. $url = Wechat::makeRedirectUrl(url('/weixin/match/index', '', '', true));
  1107. $contentStr .= "\n\n<a href='{$url}'>点击开启你的脱单之旅</a>";
  1108. }
  1109. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1110. // 推送邀请注册奖励消息
  1111. if ($inviteData) {
  1112. $inviteOpenid = isset($inviteData['openid']) ? $inviteData['openid'] : '';
  1113. $message = isset($inviteData['message']) ? $inviteData['message'] : '';
  1114. if ($inviteOpenid && $message) {
  1115. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1116. }
  1117. }
  1118. }else if($event == 'unsubscribe'){
  1119. $cacheKey = "weixin:auth:".$openid;
  1120. PRedis::del($cacheKey);
  1121. session('userInfo', null);
  1122. }
  1123. // 删除缓存锁
  1124. PRedis::del($lockKey);
  1125. exit;
  1126. }
  1127. /**
  1128. * 响应消息
  1129. * @param $postObj
  1130. */
  1131. public static function responseText($postObj)
  1132. {
  1133. $openid = isset($postObj['FromUserName']) ? $postObj['FromUserName'] : '';
  1134. $msgId = isset($postObj['MsgId']) ? $postObj['MsgId'] : '';
  1135. $keyword = isset($postObj['Content']) ? trim($postObj['Content']) : '';
  1136. $cacheKey = "messages:replys:{$msgId}";
  1137. if(PRedis::get($cacheKey)){
  1138. return false;
  1139. }
  1140. // 验证关键词回复
  1141. PRedis::set($cacheKey, $postObj, 300);
  1142. if($keyword){
  1143. $replyData = Reply::where(['keyword'=> $keyword, 'status'=> 1])
  1144. ->field('type,reply_type,title,media_id,content')
  1145. ->find();
  1146. if($replyData){
  1147. $msgData = [];
  1148. $type = isset($replyData['type'])? intval($replyData['type']) : 1;
  1149. $replyType = isset($replyData['reply_type'])? intval($replyData['reply_type']) : 1;
  1150. switch($type){
  1151. case 1: // 图片
  1152. // 文字回复
  1153. $content = isset($replyData['content'])? trim($replyData['content']) : '';
  1154. // 二维码回复
  1155. $mediaId = isset($replyData['media_id'])? trim($replyData['media_id']) : '';
  1156. if($mediaId){
  1157. $msgData = ['media_id'=> $mediaId];
  1158. }
  1159. // 回复图片
  1160. if($msgData){
  1161. // 回复文字
  1162. if($content){
  1163. Wechat::sendCustomMsg($openid, ['content' => $content]);
  1164. }
  1165. PRedis::set('message:temp:'.$openid, ['text'=> $content, 'media'=> $msgData], 600);
  1166. Wechat::sendCustomMsg($openid, $msgData,'image');
  1167. //Wechat::rebackOk();
  1168. exit;
  1169. }
  1170. break;
  1171. case 2: // 文字
  1172. $content = isset($replyData['content'])? trim($replyData['content']) : '';
  1173. // 回复文字
  1174. if($content){
  1175. Wechat::sendCustomMsg($openid, ['content' => $content]);
  1176. exit;
  1177. }
  1178. break;
  1179. case 3: // 图文
  1180. break;
  1181. }
  1182. }
  1183. }
  1184. // 通用回复
  1185. /*
  1186. $siteInfo = cmf_get_site_info();
  1187. $wxInfo = Wechat::getUserInfo($openid);
  1188. $nickname = isset($wxInfo['nickname']) ? $wxInfo['nickname'] : '';
  1189. $siteName = isset($siteInfo['site_name']) ? $siteInfo['site_name'] : '本公众号';
  1190. $followMsg = isset($siteInfo['follow_msg']) ? $siteInfo['follow_msg'] : '';
  1191. $contentStr = $followMsg ? str_replace('{nickname}', $nickname, $followMsg) : "Hi{$nickname},欢迎关注{$siteName}!";
  1192. $replyUrl = config('weixin.reply_url');
  1193. if ($replyUrl) {
  1194. $url = Wechat::makeRedirectUrl(url('/weixin/match/index', '', '', true));
  1195. $contentStr .= "\n\n<a href='{$url}'>点击开启你的脱单之旅</a>";
  1196. }
  1197. Wechat::sendCustomMsg($openid, ['content' => $contentStr]);
  1198. */
  1199. //Wechat::rebackOk();
  1200. echo ' ';
  1201. exit;
  1202. }
  1203. /**
  1204. * 响应消息
  1205. * @param $fromUsername 发送用户
  1206. * @param $toUsername 接收用户
  1207. * @param $contentStr 发送内容
  1208. * @param string $msgType 消息类型
  1209. */
  1210. public static function responseTplMsg($fromUsername, $toUsername, $contentStr, $msgType = 'text')
  1211. {
  1212. $textTpl = "<xml>
  1213. <ToUserName><![CDATA[%s]]></ToUserName>
  1214. <FromUserName><![CDATA[%s]]></FromUserName>
  1215. <CreateTime>%s</CreateTime>
  1216. <MsgType><![CDATA[%s]]></MsgType>
  1217. <Content><![CDATA[%s]]></Content>
  1218. </xml>";
  1219. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
  1220. echo $resultStr;
  1221. exit;
  1222. }
  1223. /**
  1224. * 创建菜单
  1225. * @param array $menus 菜单数组数据
  1226. * @params $delete 是否删除就菜单
  1227. * @return bool
  1228. */
  1229. public static function createMenu($menus = [], $delete = false)
  1230. {
  1231. $weixinConfig = config('weixin.');
  1232. $menus = $menus ? $menus : (isset($weixinConfig['menus']) ? $weixinConfig['menus'] : []);
  1233. if (empty($menus)) {
  1234. return false;
  1235. }
  1236. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1237. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1238. if (empty($token)) {
  1239. return false;
  1240. }
  1241. // 删除菜单
  1242. if ($delete) {
  1243. Wechat::delMenu();
  1244. }
  1245. $url = sprintf(self::$apiUrl['createMenu'], $token);
  1246. $result = httpRequest($url, json_encode(['button' => $menus], 256));
  1247. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1248. if ($errorCode != 0) {
  1249. return false;
  1250. }
  1251. return $result;
  1252. }
  1253. /**
  1254. * 删除菜单
  1255. * @return bool
  1256. */
  1257. public static function delMenu()
  1258. {
  1259. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1260. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1261. $url = sprintf(self::$apiUrl['delMenu'], $token);
  1262. $result = httpRequest($url);
  1263. $errorCode = isset($result['errcode']) ? $result['errcode'] : true;
  1264. if ($errorCode == 0) {
  1265. return false;
  1266. }
  1267. return true;
  1268. }
  1269. /**
  1270. * 查询菜单
  1271. * @return bool
  1272. */
  1273. public static function getMenu()
  1274. {
  1275. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1276. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1277. $url = sprintf(self::$apiUrl['getMenu'], $token);
  1278. $result = httpRequest($url);
  1279. return $result;
  1280. }
  1281. /**
  1282. * 发送客服消息
  1283. * @param $openid 接受用户OPENID
  1284. * @param $content 消息内容:数组
  1285. * @param string $msgType 消息类型
  1286. * @return mixed
  1287. */
  1288. public static function sendCustomMsg($openid, $content, $msgType = 'text')
  1289. {
  1290. $data = [
  1291. 'touser' => $openid,
  1292. 'msgtype' => $msgType,
  1293. $msgType => $content
  1294. ];
  1295. $lockKey = 'weixin:custonLock:' . $openid . '_' . md5(json_encode($data));
  1296. if (PRedis::get($lockKey)) {
  1297. return false;
  1298. }
  1299. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1300. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1301. PRedis::set($lockKey, $data, 5);
  1302. $url = sprintf(self::$apiUrl['customMessage'], $token);
  1303. $result = httpRequest($url, json_encode($data, 256));
  1304. PRedis::set('weixin:customLock:' . $openid . '_' . date('YmdHis'), ['data' => $data, 'tokenData' => $tokenData, 'result' => $result], 3);
  1305. return $result;
  1306. }
  1307. /**
  1308. * 发送模板消息
  1309. * @param $openid OPENID
  1310. * @param $params 参数:title-标题(必填),type-模板类型标识字符串(必填),keywords-模板字段数据(必填),url-模板跳转链接,remark-模板备注信息
  1311. * @return array|int
  1312. */
  1313. public static function sendTplMsg($openid, $params, $formatUrl=true)
  1314. {
  1315. $title = isset($params['title']) ? $params['title'] : '';
  1316. $remark = isset($params['remark']) ? $params['remark'] : '';
  1317. $type = isset($params['type']) ? $params['type'] : 'default';
  1318. $keywords = isset($params['keywords']) ? $params['keywords'] : [];
  1319. $keywords = $keywords ? $keywords : [];
  1320. if ($title) {
  1321. $keywords['first'] = ['value' => $title, 'color' => '#173177'];
  1322. }
  1323. if ($remark) {
  1324. $keywords['remark'] = ['value' => $remark, 'color' => '#173177'];
  1325. }
  1326. $templates = cmf_get_option('templates');
  1327. $templateId = isset($templates[$type . '_template']) ? trim($templates[$type . '_template']) : '';
  1328. if (empty($templateId)) {
  1329. return 2110;
  1330. }
  1331. ksort($keywords);
  1332. $tplData = [
  1333. 'touser' => $openid,
  1334. 'template_id' => $templateId,
  1335. 'data' => $keywords,
  1336. ];
  1337. $url = isset($params['url']) ? trim($params['url']) : '';
  1338. if ($url) {
  1339. $tplData['url'] = $formatUrl? Wechat::makeRedirectUrl($url) : $url;
  1340. }
  1341. // 删除旧数据,新增消息记录
  1342. $expire = config('weixin.message_expire');
  1343. $expire = $expire? $expire : 7;
  1344. $day = date('Y-m-d H:i:s', strtotime("-{$expire} days"));
  1345. $deleteKey = "messages:delete:".$openid;
  1346. if(!PRedis::get($deleteKey)){
  1347. Message::where('created_at','<=', $day)->delete();
  1348. PRedis::set($deleteKey, $day, 120);
  1349. }
  1350. $data = [
  1351. 'title' => $title,
  1352. 'type' => 2,
  1353. 'msg_tpl' => $type,
  1354. 'openid' => $openid,
  1355. 'content' => json_encode($tplData, 256),
  1356. 'created_at' => date('Y-m-d H:i:s'),
  1357. 'updated_at' => date('Y-m-d H:i:s'),
  1358. 'status' => 1,
  1359. ];
  1360. $id = Message::insertGetId($data);
  1361. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1362. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1363. if (empty($token)) {
  1364. return 1010;
  1365. }
  1366. $url = sprintf(self::$apiUrl['tplMessage'], $token);
  1367. $result = httpRequest($url, json_encode($tplData, 256));
  1368. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1369. PRedis::set('messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1370. if ($code == 'ok') {
  1371. Message::where(['id' => $id])
  1372. ->update(['send_at' => date('Y-m-d H:i:s'), 'status' => 2]);
  1373. return ['id' => $id, 'message' => 2112];
  1374. } else {
  1375. $result = httpRequest($url, json_encode($tplData, 256));
  1376. $code = isset($result['errcode']) ? $result['errcode'] : true;
  1377. PRedis::set('messages:result:'.$openid.'_'.date('YmdHi'), ['url'=> $url,'params'=> $tplData,'result'=> $result], 600);
  1378. if ($code === 0) {
  1379. Message::where(['id' => $id])
  1380. ->update(['send_at' => date('Y-m-d H:i:s'), 'status' => 2]);
  1381. return ['id' => $id, 'message' => 2112];
  1382. }
  1383. }
  1384. return 2113;
  1385. }
  1386. /**
  1387. * 获取消息模板列表
  1388. * @return int|mixed
  1389. */
  1390. public static function getTemplateList(){
  1391. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1392. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1393. if (empty($token)) {
  1394. return 1010;
  1395. }
  1396. $url = sprintf(self::$apiUrl['templateList'], $token);
  1397. $result = httpRequest($url);
  1398. PRedis::set('messages:templates', $result, 600);
  1399. return $result;
  1400. }
  1401. /**
  1402. * 上传媒体素材
  1403. * @param $file 素材文件本地相对路径
  1404. * @param int $title 素材名称或标题
  1405. * @param int $type 素材类型:1-图片,2-语音,3-视频,4-缩略图
  1406. * @param bool $refresh 是否刷新缓存重新上传
  1407. * @return bool|int|mixed
  1408. */
  1409. public static function uploadMedia($file, $title='', $type=1, $refresh=false){
  1410. $mediaFile = 'upload/'.$file;
  1411. if(!file_exists($mediaFile)){
  1412. return false;
  1413. }
  1414. $types = [1=>'image',2=>'voice',3=>'video',4=>'thumb'];
  1415. $typeValue = isset($types[$type])? $types[$type] : '';
  1416. if(!$typeValue){
  1417. return false;
  1418. }
  1419. $cacheKey = "medias:{$typeValue}:".md5($mediaFile);
  1420. $mediaData = PRedis::get($cacheKey);
  1421. if($mediaData && !$refresh){
  1422. return $mediaData;
  1423. }
  1424. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1425. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1426. if (empty($token)) {
  1427. return false;
  1428. }
  1429. @chmod($mediaFile, 0755);
  1430. $url = sprintf(self::$apiUrl['uploadMedia'], $token, $typeValue);
  1431. if(class_exists('CURLFile')){
  1432. $postData = ['media'=> new \CURLFile(realpath($mediaFile))];
  1433. }else{
  1434. $postData = ['media'=> '@'.realpath($mediaFile)];
  1435. }
  1436. $result = httpFilePost($url, $postData);
  1437. $mediaId = isset($result['media_id'])? $result['media_id'] : '';
  1438. $mediaUrl = isset($result['url'])? $result['url'] : '';
  1439. // 存库处理
  1440. if($result && $mediaId && $mediaUrl){
  1441. $data = [
  1442. 'type'=> $type,
  1443. 'title'=> $title? $title : '素材文件',
  1444. 'url'=> $file,
  1445. 'media_id'=> $mediaId,
  1446. 'media_url'=> $mediaUrl,
  1447. 'updated_at'=> date('Y-m-d H:i:s'),
  1448. ];
  1449. $id = Medias::insertGetId($data);
  1450. if(!$id){
  1451. return false;
  1452. }
  1453. $result['id'] = $id;
  1454. PRedis::set($cacheKey, $result);
  1455. return $result;
  1456. }
  1457. return false;
  1458. }
  1459. public static function makeShortUrl($url){
  1460. $tokenData = Wechat::getAccessToken('', 'accessToken');
  1461. $token = isset($tokenData['token']) ? trim($tokenData['token']) : '';
  1462. //$token = '30_WxzS6qNfeaIr1v3Rx_0Ons1D54Usci17_pVyeQGWJbarCZQNV-lo6nD3IKEJmzY_8ZHClzno32BQhNXzfIF-cu_5DMDnqBV9FtnjUXL4k0zD6oskOXj7I6WNuDDjxTz20P_EELHJrbphEDJ6TRWdAAALJO';
  1463. if (empty($token)) {
  1464. return $url;
  1465. }
  1466. $apiUrl = sprintf(self::$apiUrl['shortUrl'], $token);
  1467. $result = httpFilePost($apiUrl, json_encode(['action'=> 'long2short','long_url'=> $url], 256));
  1468. $shortUrl = isset($result['short_url'])? trim($result['short_url']) : '';
  1469. return $shortUrl? $shortUrl : $url;
  1470. }
  1471. /**
  1472. * 生成普通参数二维码
  1473. * @param $str 参数
  1474. * @param bool $refresh 是否重新生成
  1475. * @return bool
  1476. */
  1477. public static function makeNormalQrcode($str, $refresh = false, $size = 8, $margin=2)
  1478. {
  1479. $qrFile = '/upload/qrcode/member/';
  1480. if (!is_dir($qrFile)) {
  1481. @mkdir('.' . $qrFile, 0755, true);
  1482. }
  1483. $qrFile = $qrFile . 'U_' . strtoupper(md5($str . '_' . $size)) . '.jpg';
  1484. if (is_file($qrFile) && !$refresh) {
  1485. return false;
  1486. }
  1487. QRcode::png($str, '.' . $qrFile, 2, $size, $margin);
  1488. if(!file_exists('.'.$qrFile)){
  1489. return false;
  1490. }
  1491. return $qrFile;
  1492. }
  1493. /**
  1494. * 返回给微信
  1495. */
  1496. public static function rebackOk(){
  1497. echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  1498. exit;
  1499. }
  1500. }
  1501. ?>