python调用微信JS_SDK及使用redis缓存access_token 和jsapi_ticket
from flask import Flask, make_response,request import json import string import hashlib import random import time import urllib import redis r = redis.Redis(host='0.0.0.0', port=6379) # 创建redis对象 app = Flask(__name__) appid = '微信公众号的appid' sceret = '微信公众号的sceret' class Sign: def __init__(self, jsapi_ticket, url): self.ret = { 'nonceStr': self.__create_nonce_str(), 'jsapi_ticket': jsapi_ticket, 'timestamp': self.__create_timestamp(), 'url': url } def __create_nonce_str(self): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15)) #创建随机字符串 def __create_timestamp(self): return int(time.time()) # 创建一个时间戳 def sign(self): string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)]) # 根据字符的ASCII值进行排序,拼接 self.ret['signature'] = hashlib.sha1(string.encode('utf-8')).hexdigest() # 对字符串进行sha1加密 return self.ret def get__token() ACCESS_TOKEN = r.get('wx:ACCESS_TOKEN') # 从redis中获取ACCESS_TOKEN if ACCESS_TOKEN: return ACCESS_TOKEN try: token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(appid, sceret) # 创建获取token的url response = urllib.request.urlopen(token_url) b = response.read().decode('utf-8') token = json.loads(b) ACCESS_TOKEN = token.get("access_token") r.setex('wx:ACCESS_TOKEN', ACCESS_TOKEN, 7200) # 将获取到的 ACCESS_TOKEN 存入redis中并且设置过期时间为7200s return ACCESS_TOKEN except Exception as e: return e def get_ticket(): ticket = r.get('wx:ticket') # 获取redis数据库中ticket if ticket: tic = str(ticket, encoding='utf-8') return tic else: try: token = get__token() ticket_url = " https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={}&type=jsapi".format(token) get_ticket = urllib.request.urlopen(ticket_url) c = get_ticket.read().decode("utf-8") js_ticket = json.loads(c) ticket = js_ticket.get("ticket") r.setex('wx:ticket', ticket, 7200) return ticket except Exception as e: return e #flask请求路由方法 @app.route('/jssdkconfig', methods=['GET']) def jssdk_config(): url = request.form.get("url") #url = "https://www.baidu.com" ticket = get_ticket() sign = Sign(ticket, url) result = { "appid": appid, "result": sign.sign() } # 响应头允许跨域访问 response_heade = { 'Access-Control-Allow-Origin': '*' } return make_response(json.dumps(result).encode("utf-8"), 200, response_heade) if __name__ == '__main__': app.run()
致:有需要者,如果有疑问的,可以评论区下留言。我会尽快回复,希望共同进步。