微信公众平台开发中,与微信服务器的交互都必须使用Access Token。因此相比之前介绍的接入,实现access_token的获取同样是非常重要而基础的。
请求access_token,需要以GET方式访问https://api.weixin.qq.com/cgi-bin/token这个接口,并附带如下参数:
grant_type:这个参数的值总是client_credential
appid:公众号的app_id
secret:公众好的凭证密钥
在开始之前,我们必须首先实现一个发送请求的方法send_request,其代码如下:
def send_request(self, host, path, method, port=443, params={}): client = httplib.HTTPSConnection(host, port) path = '?'.join([path, urllib.urlencode(params)]) client.request(method, path) res = client.getresponse() if not res.status == 200: return False, res.status return True, json.loads(res.read())
该函数一共接收5个参数:
host:主机地址(域名)
path:路径
method:请求方式
port:端口号(默认为443)
params:URL附带的参数
因为微信服务器要求必须所有接口调用都必须使用https协议,因此这里利用了httplib中的HTTPSConnection来创建一个实例,它可以用来建立SSL连接。之后我们将URL参数拼接到url的最后,即可向服务器发起请求,并将结果返回。
接下来,我们可以开始请求access_token了:
def get_access_token(self): params = { 'grant_type': 'client_credential', 'appid': self.app_id, 'secret': self.app_secret } host = 'api.weixin.qq.com' path = '/cgi-bin/token' method = 'GET' res = self._send_request(host, path, method, params=params) if not res[0]: log_error(res[1]) return False if res[1].get('errcode'): log_error(res[1].get('errmsg')) return False return res[1]
正常情况下,微信服务器会返回一个json数据,其中包含新的access_token和有效期expires_in:
{"access_token":"ACCESS_TOKEN","expires_in":7200}
如果请求失败,服务器会返回错误代码errcode和错误信息errmsg。
因此在上面的代码中,如果获取失败,就将错误信息记录到log中,并返回False;如果成功,则将新的access_token和expires_in返回。
Just do me a favor and keep writing such trhcneant analyses, OK?