Wechat.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace addons\ddrive\library;
  3. use think\Cache;
  4. class Wechat
  5. {
  6. /**
  7. * 内容安全
  8. *
  9. * @return void
  10. */
  11. public static function msgSecCheck($content, $isRef = false)
  12. {
  13. $accessToken = self::getAccessToken();
  14. if (!$accessToken) {
  15. return true;
  16. }
  17. $headers = ['Content-type: application/json'];
  18. $options = [
  19. CURLOPT_HTTPHEADER => $headers,
  20. ];
  21. $api = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $accessToken;
  22. $res = \fast\Http::post($api, '{ "content":"' . $content . '" }', $options);
  23. $res = json_decode($res, true);
  24. // getAccessToken失效
  25. if ($res['errcode'] == 40001) {
  26. $accessToken = self::getAccessToken(true);
  27. if (!$isRef) {
  28. return self::msgSecCheck($content, true);
  29. } else {
  30. return true;
  31. }
  32. }
  33. return $res['errcode'] == '0';
  34. }
  35. /**
  36. * 获取access_token
  37. *
  38. * @return void
  39. */
  40. public static function getAccessToken($isRef = false)
  41. {
  42. if (!$isRef && Cache::get('access_token')) {
  43. return Cache::get('access_token');
  44. }
  45. $config = get_addon_config('ddrive');
  46. $appid = $config['wx_appid'];
  47. $secret = $config['wx_secret'];
  48. $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
  49. $res = \fast\Http::get($api);
  50. $res = json_decode($res, true);
  51. if ($res['access_token']) {
  52. Cache::set('access_token', $res['access_token'], $res['expires_in']);
  53. return $res['access_token'];
  54. }
  55. return false;
  56. }
  57. }