123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- namespace Cas\Controller\CmdLine;
- use KIF\Core\Controller;
- use KIF\Cache\Memcached;
- use KIF\Core\Config;
- /**
- * 获取微信Token
- * 执行:php /www/index.php -cCmdLine_GetWeixinToken
- * @author lihuanchun
- */
- class GetWeixinToken extends Controller{
-
- private $accessTokenCacheName ;
- private $jsApiTicketCacheName ;
- private $appId ;
- private $appSecret ;
- private $thisTime ;
- private $objMemcached;
-
- public function run() {
- $action = $this->action;
- $this->$action();
- }
-
-
- /**
- * 初始化
- *
- */
- public function __construct(){
- $this->objMemcached = new Memcached();
- $this->thisTime = time();
- $wechat_cfg = Config::getInstance()->get('wechat_cfg');
- $this->appSecret = $wechat_cfg['appSecret'];
- $this->appId = $wechat_cfg['appId'];
- $this->jsApiTicketCacheName ='weixin_jsApiTicke';
- $this->accessTokenCacheName = 'weixin_AccessToken';
- }
-
- /**
- * 每小时执一次:php /www/index.php -cCmdLine_GetWeixinToken
- */
- public function doDefault(){
- # 统一执行
- $accessToken = $this->getAccessToken();
- $jsApiTicket = $this->getJsApiTicket($accessToken);
-
- print "
- 时间:".date("Y-m-d H:i:s")."
- 计算结果:\n
- accessToken: {$accessToken}\n
- jsApiTicket: {$jsApiTicket}\n
- ";
-
- }
-
-
- /**
- * 获取微信 AccessToken 存入 Memcached
- */
- public function getAccessToken(){
- $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
- $res = json_decode($this->httpGet($url));
- $accessToken = $res->access_token;
- $this->objMemcached -> set($this->accessTokenCacheName, $accessToken);
- return $accessToken;
- }
-
- /**
- * 获取微信 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;
- $this->objMemcached -> set($this->jsApiTicketCacheName, $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;
- }
-
-
- }
|