通过测试账号获取appID和appsecret
获取access_token(通过appID和appsecret)
def get_access_token():
appid = "wxbexxxxxxxxxxxxx"
appsercet = "e1c8cxxxxxxxxxxxxxxxxx"
url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (appid, appsercet)
req = requests.get(url=url).json()
access_token = req.get("access_token")
print(access_token)
return access_token
生成ticket
def get_ticket():
"""
生成带参数的二维码的ticket
:return:
"""
access_token = get_access_token()
sn = "gym is so beautiful"
data = {"expire_seconds": 604800, "action_name": "QR_STR_SCENE",
"action_info": {"scene": {"scene_str": sn}}}
url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s" % access_token
req = requests.post(url=url, data=json.dumps(data)).json()
ticket = req.get("ticket")
print(ticket)
return ticket
获取到ticket:
gQGM8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyejhkMkVMM1dmeUUxd2gzRzF2Yxxxxxxxxxxxxxxxxxx
官方文档:https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html
获取带ticket的二维码图片
img_adds = “/” # 保存图片的路径,请自定义
def get_qrcode_with_parameters():
"""
生成带参数的二维码
:return:
"""
ticket = get_ticket()
url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s" % ticket
try:
response = requests.get(url)
# 获取的文本实际上是图片的二进制文本
img = response.content
# 将他拷贝到本地文件 w 写 b 二进制 wb代表写入二进制文本
# 保存路径
path = img_adds
with open(path, 'wb') as f:
f.write(img)
except Exception as e:
print(e)
获取到的二维码如下:
和其他图片拼接一下,生成想要的专属二维码
logo_path = "/logo.png" # logo存放位置
pic_path = "/pict.png" # 二维码存放位置
def get_qrcode_content(img_adds):
""" 读取二维码的内容: img_adds:二维码地址(可以是网址也可是本地地址 """
if os.path.isfile(img_adds):
# 从本地加载二维码图片
img = Image.open(img_adds)
else:
# 从网络下载并加载二维码图片
rq_img = requests.get(img_adds).content
img = Image.open(BytesIO(rq_img))
# img.show() # 显示图片,测试用
txt_list = pyzbar.decode(img)
# print(txt_list)
barcodeData = None
for txt in txt_list:
barcodeData = txt.data.decode("utf-8")
print(barcodeData)
return barcodeData
def get_qrcode_with_picture():
"""
生成带图片的二维码
:return:
"""
from PIL import Image
import qrcode
content = get_qrcode_content(img_adds)
qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=8, border=4)
qr.add_data(content)
qr.make(fit=True)
img = qr.make_image()
img = img.convert("RGBA")
# logo="D:/favicon.jpg"
icon = Image.open(logo_path)
img_w, img_h = img.size
factor = 4
size_w = int(img_w / factor)
size_h = int(img_h / factor)
icon_w, icon_h = icon.size
if icon_w > size_w:
icon_w = size_w
if icon_h > size_h:
icon_h = size_h
icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
w = int((img_w - icon_w) / 2)
h = int((img_h - icon_h) / 2)
icon = icon.convert("RGBA")
img.paste(icon, (w, h), icon)
# img.show()
img.save(pic_path)