python3生成微信帶參數的小程序碼

根據AppID和AppSecret獲取Token,而後根據token再生成帶參數的小程序碼。
官方文檔以下:
https://developers.weixin.qq.com/minigame/dev/tutorial/open-ability/qrcode.htmlhtml

我用pyton3實現了一下,貼上來,方便你們使用,代碼以下:json

import urllib.request
import urllib.parse
import json

appid = ''
appsecret=''



#獲取TOKEN
def getToken(appid,appsecret):
	#這個是微信獲取小程序碼的接口
	url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}'.format(appid=appid,appsecret=appsecret)
	#準備一下頭
	headers = {
		'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
	}

	request = urllib.request.Request(url,headers=headers)
	response = urllib.request.urlopen(request)
	readData = response.read()
	readData = readData.decode('utf-8')
	obj = json.loads(readData)
	print(obj)
	print(obj['access_token'])
	return obj['access_token']
	

#獲取小程序碼
def getACodeImage(token,file):
	#這個是微信獲取小程序碼的接口
	url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token={token}'.format(token=token)
	#準備一下頭
	headers = {
		'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
	}
	#用Post傳值,這裏值用JSON的形式
	values = {"path": "?from=1"}
	#將字典格式化成能用的形式,urlencode不能用
	#data = urllib.parse.urlencode(values).encode('utf-8')
	#使用json.dumps的方式序列化爲字符串,而後bytes進行編碼
	data = json.dumps(values)
	data=bytes(data,'utf8')
	#建立一個request,放入咱們的地址、數據、頭
	request = urllib.request.Request(url, data, headers)
	#將獲取的數據存在本地文件
	readData = urllib.request.urlopen(request).read()
	f=open(file,"wb")
	f.write(readData)
	f.close()

	
token = getToken(appid,appsecret)
getACodeImage(token,'wxCode.jpg')
相關文章
相關標籤/搜索