Wechat.php 67 KB

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