共计 1695 个字符,预计需要花费 5 分钟才能阅读完成。
access_token
是公众号的全局唯一票据,公众号调用各接口时都需使用 access_token
。开发者需要进行妥善保存。access_token
的存储至少要保留 512 个字符空间。access_token
的有效期目前为 2 个小时,需定时刷新,重复获取将导致上次获取的 access_token
失效
原理:
对 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
发起 GET 请求
正确的返回值
{"access_token":"ACCESS_TOKEN",
"expires_in":7200
}
错误的返回值
{"errcode":40013,
"errmsg":"invalid appid"
}
DJango 服务代码实现
myApp/accessToken.py
import time
import requests
import json
class AccessToken:
_access_token = {"token":"",
"updatatime":time.time()}
@classmethod
def updateAccessToken(cls, grant_type, appid, secret):
url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=%s&appid=%s&secret=%s"%(grant_type, appid, secret)
res = requests.get(url)
resDit = json.loads(res.content)
if resDit["access_token"]:
cls._access_token["token"] = resDit["access_token"]
cls._access_token["updatatime"] = time.time()
@classmethod
def getAccessToken(cls, grant_type, appid, secret):
if not cls._access_token["token"] or (time.time() - cls._access_token["updatatime"]) >= 6500:
# 更新 token
cls.updateAccessToken(grant_type, appid, secret)
return cls._access_token["token"]
myApp/urls.py
from django.urls import path, re_path
from myApp import views
urlpatterns = [path(r'index/', views.index),
path(r'weixin/', views.weixin),
path(r'access/', views.access),
]
myApp/views.py
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import hashlib
from myApp.accessToken import AccessToken
def index(request):
return HttpResponse("sunck is a good man")
@csrf_exempt
def weixin(request):
pass
def access(request):
access_token = AccessToken.getAccessToken("client_credential", "wxffde55b11cc79754", "84e86527f090d6238ea1c0b96f5fc753")
return HttpResponse(access_token)
自有平台获取参数:
测试平台获取参数:
浏览器地址栏输入:http://39.107.226.105/access/
正文完
星哥玩云-微信公众号