步骤:先使用appid&secret获取access_token->再使用access_token获取ticket->获取时间戳->创建随机字符串—>将前面的后3个以及传值过来的实时url根据字符的ASCII值进行排序,拼接
->最后对拼接的字符串作sha1加密,字段名和字段值都采用原始值,不进行URL 转义对字符串作sha1加密,字段名和字段值都采用原始值,不进行URL 转义
参考链接:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @File : share
# @Author : moucong
# @Date : 2019/2/17 14:35
# @Software: PyCharm
import hashlib
import string
import urllib.request
import json
import time
import random
#获取token
def get_token(url):
res = urllib.request.urlopen(url=url)
page_source = res.read().decode(‘utf-8‘)
data = page_source.split(",")
token, value = data[0].split(":", 1)
token = token.replace("{", ‘‘).replace(‘"‘, ‘‘)
value = value.replace(‘"‘, ‘‘)
expires, value_time = data[1].split(":", 1)
value_time = value_time.replace("}", ‘‘).replace(‘"‘, ‘‘)
expires = expires.replace(‘"‘, ‘‘)
access_token = {token: value, expires: value_time}
print(access_token)
file_name = ‘access_token.json‘
with open(file_name, ‘w‘) as data_obj:
# 使用函数json.dump()将数字列表存储到文件中
json.dump(access_token, data_obj)
print("已经存入"+file_name)
#获取ticket
def get_ticket():
with open("access_token.json", ‘r‘) as load_f:
load_dict = json.load(load_f)
token =load_dict ["access_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)
ticket_data = get_ticket.read().decode("utf-8")
js_ticket = json.loads(ticket_data)
ticket = js_ticket.get("ticket")
print(ticket)
file_name = ‘jsapi_ticket.json‘
js_ticket = {‘ticket‘: ticket, "expires_in": "7200"}
with open(file_name, ‘w‘) as data_obj:
# 使用函数json.dump()将数字列表存储到文件中
json.dump(js_ticket, data_obj)
print("已经存入" + file_name)
# setex(‘wx:ticket‘, ticket, 7200) #ticket过期时间
# return ticket
# print(ticket_url)
#创建时间戳
def time_stamp():
timeStamp = int(time.time())
return timeStamp
#创建随机字符串
def create_nonce_str():
return ‘‘.join(random.choice(string.ascii_letters + string.digits) for _ in range(15)) # 创建随机字符串
#进行签名
def sign(url):
with open("./port/jsapi_ticket.json", ‘r‘) as load_f:
load_dict = json.load(load_f)
ticket = load_dict["ticket"]
noncestr = create_nonce_str()
timestamp = time_stamp()
resource = {
‘nonceStr‘: noncestr,
‘jsapi_ticket‘: ticket,
‘timestamp‘: timestamp,
‘url‘: url
}
str_url = ‘&‘.join([‘%s=%s‘ % (key.lower(), resource[key]) for key in sorted(resource)]) # 根据字符的ASCII值进行排序,拼接
signature = hashlib.sha1(str_url.encode(‘utf-8‘)).hexdigest()
resource_all ={
‘appId‘: ‘‘,
‘nonceStr‘: noncestr,
‘timestamp‘: timestamp,
‘url‘: url,
‘signature‘: signature
}
return resource_all
# if __name__ == ‘__main__‘:
# get_token(url)
# get_ticket()
# time_stamp()
# create_nonce_str()
# sign()
备注小笔记:我使用的是Django进行后端部署和传值,之后使用ajax进行前端获取和传url回到后端,后来遇到跨域问题,使用nginx转发端口解决了,获取ticket和token使用while true,time.sleep(7200)解决,存为json.
利用python开发微信JS-JDK(基于python3.6)