微信开发 - 获取基础接口 access_token

Access Token

 

access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。

 

access_token的存储至少要保留512个字符空间,有效期目前为7200秒,需定时刷新,重复获取将导致上次获取的access_token失效。

 

公众号可以使用AppID和AppSecret调用微信接口来获取access_token。AppID和AppSecret可在微信公众平台官网-开发-基本配置中获取(需要已经成为开发者,且帐号没有异常状态)。调用所有微信接口时均需使用https协议。

 

特别说明

本文获取的是调用基础接口需要的Access Token,而非网页授权(通过OAuth2.0机制实现)所使用的Access Token,请注意区别。

 



获取Access Token

 

方法一:

 

def getAccessToken()
{
    def APPID = "wxe49d******43c1cd"
    def SECRET = "217c05ff85************db8f4c9371"
    def requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET"
    
    URL url = new URL(requestUrl)
    def params = "APPID=" + URLEncoder.encode(APPID, 'UTF-8') + 
                 "&SECRET=" + URLEncoder.encode(SECRET, 'UTF-8')

    HttpURLConnection connection = (HttpURLConnection) url.openConnection()
    connection.setDoOutput(true)
    connection.setRequestMethod("POST")
    connection.outputStream.withWriter { Writer writer -> writer.write params }
    def response = connection.inputStream.withReader { Reader reader -> reader.text }
    def accessToken = JSON.parse(response).getAt("access_token")
    
    return accessToken
}

 

方法二:

 

可以直接通过浏览器获取Access Token






方法三:

 

通过微信公众平台接口调用工具获取Access Token

https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E5%9F%BA%E7%A1%80%E6%94%AF%E6%8C%81&form=%E8%8E%B7%E5%8F%96access_token%E6%8E%A5%E5%8F%A3%20/token

 


 

接口频率限制说明

 

公众号调用接口并不是无限制的。为了防止公众号的程序错误而引发微信服务器负载异常,默认情况下,每个公众号调用接口都不能超过一定限制,当超过一定限制时,调用对应接口会收到如下错误返回码:

{"errcode":45009,"errmsg":"api freq out of limit"}

各接口限制的调用次数可通过微信公众平台官网-开发-接口权限 中查询到。



 

 

猜你喜欢

转载自hellolove.iteye.com/blog/2333874