123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace Cas\Module;
- use KIF\Core\Config;
- use KIF\String\String;
- use KIF\Curl;
- use KIF\Cache\Memcached;
- use KIF\Data\ResultWrapper;
- /**
- *
- * 刷新 access_token
- * @author lishumingoo@gmail.com
- */
- class RefreshAccessToken {
-
- /**
- * 获取access token接口地址
- * @var string
- */
- private $requestAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
-
- /**
- * 刷新access_token的key
- * @var string
- */
- const ACCESS_TOKEN_KEY = 'jyD#HNCB%2';
-
- /**
- * 刷新JsApiTicket的key
- * @var String
- */
- const JSAPI_TICKET_KEY = 'yD#sdfasd#asdfa%2';
-
-
- public function run() {
- $wechat_cfg = Config::getInstance()->get('wechat_cfg');
- if (!$wechat_cfg) {
- return ResultWrapper::fail('获取微信开发者ID失败');
- }
-
- $appid = $wechat_cfg['appId'];
- $secret = $wechat_cfg['appSecret'];
- $args = array(
- 'grant_type' => 'client_credential',
- 'appid' => $appid,
- 'secret' => $secret,
- );
-
- $url = String::jointUrl($this->requestAccessTokenUrl, $args);
-
- $objCurl = new Curl($url);
- $json = $objCurl->get();
- if (!$json) {
- return ResultWrapper::fail('接口未返回数据');
- }
-
- $result = json_decode($json, true);
- if ($result['errcode']) {
- return ResultWrapper::fail("原因:{$json}");
- }
-
- $access_token = $result['access_token'];
- $expires = $result['expires_in'];
-
- $objMemcached = new Memcached();
- $setResult = $objMemcached->set(self::ACCESS_TOKEN_KEY, $access_token);
- if (!$setResult) {
- return ResultWrapper::fail("将access_token存入memcache失败");
- }
-
- # 新增: 获取微信 JsApiTicket 存入 Memcached
- $this->getJsApiTicket($access_token);
-
- return ResultWrapper::success($access_token);
- }
-
-
- /**
- * 获取微信 JsApiTicket 存入 Memcached
- */
- public function getJsApiTicket($accessToken){
- $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
- $res = json_decode($this->httpGet($url));
- $jsApiTicket = $res->ticket;
- $objMemcached = new Memcached();
- $objMemcached->set(self::JSAPI_TICKET_KEY, $jsApiTicket);
- return $jsApiTicket;
- }
-
-
- /**
- * curl 请求
- */
- private function httpGet($url) {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_TIMEOUT, 500);
- curl_setopt($curl, CURLOPT_URL, $url);
- $res = curl_exec($curl);
- curl_close($curl);
- return $res;
- }
-
-
-
- }
|