RefreshAccessToken.class.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace Cas\Module;
  3. use KIF\Core\Config;
  4. use KIF\String\String;
  5. use KIF\Curl;
  6. use KIF\Cache\Memcached;
  7. use KIF\Data\ResultWrapper;
  8. /**
  9. *
  10. * 刷新 access_token
  11. * @author lishumingoo@gmail.com
  12. */
  13. class RefreshAccessToken {
  14. /**
  15. * 获取access token接口地址
  16. * @var string
  17. */
  18. private $requestAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
  19. /**
  20. * 刷新access_token的key
  21. * @var string
  22. */
  23. const ACCESS_TOKEN_KEY = 'jyD#HNC&#27B%2';
  24. /**
  25. * 刷新JsApiTicket的key
  26. * @var String
  27. */
  28. const JSAPI_TICKET_KEY = 'yD#sdfasd#asdfa%2';
  29. public function run() {
  30. $wechat_cfg = Config::getInstance()->get('wechat_cfg');
  31. if (!$wechat_cfg) {
  32. return ResultWrapper::fail('获取微信开发者ID失败');
  33. }
  34. $appid = $wechat_cfg['appId'];
  35. $secret = $wechat_cfg['appSecret'];
  36. $args = array(
  37. 'grant_type' => 'client_credential',
  38. 'appid' => $appid,
  39. 'secret' => $secret,
  40. );
  41. $url = String::jointUrl($this->requestAccessTokenUrl, $args);
  42. $objCurl = new Curl($url);
  43. $json = $objCurl->get();
  44. if (!$json) {
  45. return ResultWrapper::fail('接口未返回数据');
  46. }
  47. $result = json_decode($json, true);
  48. if ($result['errcode']) {
  49. return ResultWrapper::fail("原因:{$json}");
  50. }
  51. $access_token = $result['access_token'];
  52. $expires = $result['expires_in'];
  53. $objMemcached = new Memcached();
  54. $setResult = $objMemcached->set(self::ACCESS_TOKEN_KEY, $access_token);
  55. if (!$setResult) {
  56. return ResultWrapper::fail("将access_token存入memcache失败");
  57. }
  58. # 新增: 获取微信 JsApiTicket 存入 Memcached
  59. $this->getJsApiTicket($access_token);
  60. return ResultWrapper::success($access_token);
  61. }
  62. /**
  63. * 获取微信 JsApiTicket 存入 Memcached
  64. */
  65. public function getJsApiTicket($accessToken){
  66. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
  67. $res = json_decode($this->httpGet($url));
  68. $jsApiTicket = $res->ticket;
  69. $objMemcached = new Memcached();
  70. $objMemcached->set(self::JSAPI_TICKET_KEY, $jsApiTicket);
  71. return $jsApiTicket;
  72. }
  73. /**
  74. * curl 请求
  75. */
  76. private function httpGet($url) {
  77. $curl = curl_init();
  78. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  79. curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  80. curl_setopt($curl, CURLOPT_URL, $url);
  81. $res = curl_exec($curl);
  82. curl_close($curl);
  83. return $res;
  84. }
  85. }