Wechat.php 68 KB

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