You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

102 lines
2.4 KiB

  1. <?php
  2. namespace Kuxin\Weixin;
  3. use Kuxin\Config;
  4. use Kuxin\DI;
  5. use Kuxin\Helper\Http;
  6. use Kuxin\Helper\Json;
  7. use Kuxin\Loader;
  8. class Weixin
  9. {
  10. /**
  11. * 是否需要access_token
  12. *
  13. * @var bool
  14. */
  15. protected $token = false;
  16. /**
  17. * appid
  18. *
  19. * @var string
  20. */
  21. protected $appId;
  22. /**
  23. * @var string
  24. */
  25. protected $appSecret;
  26. /**
  27. * @var string
  28. */
  29. protected $access_token;
  30. const API_TOKEN_GET = 'https://api.weixin.qq.com/cgi-bin/token';
  31. public function __construct($appId, $appSecret)
  32. {
  33. $this->appId = $appId ?: Config::get('weixin.appid');
  34. $this->appSecret = $appSecret ?: Config::get('weixin.appsecret');
  35. }
  36. /**
  37. * @param $appId
  38. * @param $appSecret
  39. * @return static
  40. */
  41. public static function I($appId = null, $appSecret = null)
  42. {
  43. $class = static::class;
  44. return Loader::instance($class, [$appId, $appSecret]);
  45. }
  46. public function getToken($forceRefresh = 0)
  47. {
  48. $cacheKey = 'kuxin.weixin.accesstoken_' . $this->appId;
  49. $data = DI::Cache()->get($cacheKey);
  50. if ($forceRefresh || empty($data)) {
  51. $token = $this->_getTokenFromServer();
  52. // XXX: T_T... 7200 - 1500
  53. DI::Cache()->set($cacheKey, $token['access_token'], $token['expires_in'] - 1500);
  54. return $token['access_token'];
  55. }
  56. return $data;
  57. }
  58. protected function _getTokenFromServer()
  59. {
  60. $params = [
  61. 'appid' => $this->appId,
  62. 'secret' => $this->appSecret,
  63. 'grant_type' => 'client_credential',
  64. ];
  65. $token = $this->parseJSON(Http::get(self::API_TOKEN_GET, $params));
  66. if (empty($token['access_token'])) {
  67. trigger_error('Request AccessToken fail. response: ' . json_encode($token, JSON_UNESCAPED_UNICODE), E_USER_ERROR);
  68. }
  69. return $token;
  70. }
  71. protected function parseJSON($data)
  72. {
  73. if ($data{0} == '{') {
  74. return Json::decode($data, true);
  75. } else {
  76. return null;
  77. }
  78. }
  79. public static function getNonceStr($length = 32)
  80. {
  81. $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  82. $str = "";
  83. for ($i = 0; $i < $length; $i++) {
  84. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  85. }
  86. return $str;
  87. }
  88. }