WechatBack.php 65 KB

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