一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Thinkphp的微信API-缓存access token的方法详解

时间:2016-05-09 编辑:简简单单 来源:一聚教程网

本身在用微信API的类时(即大家所称的高级接口),就推荐大家根据实际环境实现缓存过程,因为获取access_token 微信官方每天只有2000次,获取一次有效时间是7200秒,这样我们就要有必要在有效时间内,重复使用access_token值,直到判断过期失效再重新获取!下面我就用TP(thinkphp3.2.3)框架写下:

cache_access_token

一、用memcached时(注因为我下的TP版本是core版,请自行官方下载memcached类库):
namespace Wx;
class WechatApi extends WechatJSON{
 
    public function cache($key, $value = null, $timeout = 7000) {
        $accessToken = S($key,'', array('type' => 'memcached'));
        $expires_time = S("{$key}_time",'', array('type' => 'memcached'));
        if (empty($value)) {
            if ($accessToken && $expires_time > time()) {
                return $accessToken;
            }
            return false;
        }
        S($key,$value, array('type' => 'memcached'));
        S("{$key}_time",time() + $timeout, array('type' => 'memcached'));
        return false;
    }
}
二、用数据库表时:
 
三、在新浪SAE时:
namespace Wx;
class WechatApi extends WechatJSON{
 
    public function cache($key, $value = null, $timeout = 7000) {
        $mmc = memcache_init();
        $accessToken = memcache_get($mmc, $key);
        $expires_time = memcache_get($mmc, $key.'_time');
        if (empty($value)) {
            if ($accessToken && $expires_time > time()) {
                return $accessToken;
            }
            return false;
        }
        memcache_set($mmc, $key, $value);
        memcache_set($mmc, $key.'_time', time() + $timeout);
        return false;
    }
}

文章开头图示的测试代码:
namespace Api\Controller;
use Think\Controller;
use Wx\WechatApi;
use Wx\WechatRequest;
 
class IndexController extends Controller {
    public function indexAction(){
        $id = I('get.user','');
        if($id) {
            $user = M('config')->where(array('uid' => $id))->find();
            if($user) {
                $config = json_decode($user['config']);
                $wechat = WechatRequest::getInstance($config);
                $wechat->parse();
            }
        }
    }
 
    public function testAction() {
        $config = C('WECHAT_CONF');
        echo 'access_token: '. S("{$config['appid']}:access_token",'', array('type' => 'memcached')).'
';
        echo 'expire_time: '. S("{$config['appid']}:access_token_time",'', array('type' => 'memcached')).'
';
        $api = WechatApi::getInstance(array(
            WechatApi::APP_ID => $config[WechatApi::APP_ID],
            WechatApi::APP_SECRET => $config[WechatApi::APP_SECRET]
        ));
        //$res = $api->call('/menu/get');
        $res = $api->call('/user/info', array('openid' => 'on0eVjnYStxkCSaaCamYCpMZDmwA', 'lang' => 'zh_CN'), WechatApi::GET);
        if (!$res) {
            var_dump($api->_error);
            var_dump($api->_error_number);
        }
        var_dump($res);
    }
}

热门栏目