zoukankan      html  css  js  c++  java
  • 【微信开发】2、全局Token获取

    Token就是应用服务器访问微信服务器的凭证,微信服务器对这个Token设置一个有效期。

    由于Token接口获取有一定的限制,不宜频繁获取,Token在一段时间内也有效,也没有必要不停的获取。

    按照官方文档建议,业务服务器保存到本地,有效期之前,各个业务模块本地获取即可。

    一、官方文档

    http GET方法获取

    http请求方式: GET
    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
     
    image
     
    JSON返回两个数据,token和有效期,expires_in的单位是s
    {"access_token":"ACCESS_TOKEN","expires_in":7200}
     

    二、代码实现

    这个还是比较简单,本地封装token获取函数,先判断本地Token是否有效

    有效则直接返回本地保存Token;否则使用httpget方法获取,并保存token和有效期

    所有应用组件均调用该方法获取Token即可,保证一致性。

    #获取微信应用Token, use the https GET method
    def get_access_token(refresh=False):
        try:
            global token_time,expires_in, access_token 
            #小于两小时,并且不需要强制刷新token
            if (datetime.now() - token_time).seconds < expires_in
                and not refresh and not access_token == '':
                #print 'get_access_token: now access_token is ',access_token
                pass
           
            #
            else: 
                debug( 'get_access_token:Get the access_token,now it is',access_token)
                url = wxHost + '/cgi-bin/token?grant_type=client_credential&appid='
                    + appid + '&secret=' + secret
                #更新token和时间戳
                #{"access_token":"ACCESS_TOKEN","expires_in":7200}
                errorcode,responseJson = https_get(url)
                access_token = responseJson.get('access_token','')
                expires_in = int(responseJson.get('expires_in','7200'))
                token_time = datetime.now()
               
            return access_token
               
        except:
            print 'get_access_token:except.'
            return 'access_token:except'

    好记性不如烂笔头
  • 相关阅读:
    hdu 携程全球数据中心建设 (球面距离 + 最小生成树)
    next_permutation()函数 和 prev_permutation() 按字典序求全排列
    poj 3792 Area of Polycubes (简单模拟)
    poj 3790 Recursively Palindromic Partitions (递推)
    hdu 1575 Tr A (矩阵快速幂入门题)
    hdu 2986 Ballot evaluation (模拟)
    sscanf() 和 sprintf()的用法。
    Codeforces Round #239 (Div. 2)
    hdu 2372 El Dorado (dp)
    hdu 3433 A Task Process(dp+二分)
  • 原文地址:https://www.cnblogs.com/inns/p/5510905.html
Copyright © 2011-2022 走看看