该代码示例展示了如何利用Python请求微信API来生成小程序二维码,包括获取access_token,生成v3和v1版本的二维码,并将二维码图片保存到本地。代码中定义了一个SingletonType元类,用于确保CreateQrCode类只有一个实例。创建二维码时,可以指定场景值、页面路径和版本类型。
官文:
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html#%E8%8E%B7%E5%8F%96-scene-%E5%80%BC
代码:
- import time
-
- import requests
-
- from product_qrcode.settings import MEDIA_URL, BASE_DIR, appid, appsecret
-
-
- class CreateQrCode(metaclass=SingletonType):
- '''生成小程序二维码'''
-
- def __init__(self, product_id: int) -> None:
- self.product_id = product_id
- self.__url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}'
- super().__init__()
-
- @property
- def params(self):
- return {
- 'scene': self.product_id,
- 'env_version': 'trial', # 正式版为 "release",体验版为 "trial",开发版为 "develop"
- # 'is_hyaline': True,
- 'page': 'pages/index/index',
- 'check_path': False,
- }
-
- @property
- def get_access_token(self) -> str:
- '''获取临时凭证'''
- return requests.get(url=self.__url).json().get('access_token')
-
- def create_qrcode_v3(self) -> str:
- '''生成二维码v3'''
- print(self.params)
- res = requests.post(url=f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={self.get_access_token}',
- json=self.params).content
- url_path = f'{MEDIA_URL}{time.strftime("%Y%m%d%H%M%S")}.png'
-
- CreateQrCode.write_qrcode(url_path, res)
- return url_path
-
- def create_qrcode_v1(self) -> str:
- '''生成二维码v1'''
- data = {'path': f'pages/index/index?id={self.product_id}', 'width': 430} # 最小 280px,最大 1280px
- res = requests.post(
- url=f'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={self.get_access_token}',
- json=data).content
- url_path = f'{MEDIA_URL}{time.strftime("%Y%m%d%H%M%S")}.png'
- CreateQrCode.write_qrcode(url_path, res)
- return url_path
-
- @staticmethod
- def write_qrcode(path: str, result: bytes) -> bool:
- '''存人二维码'''
- try:
- with open(f'{BASE_DIR}{path}', 'wb') as f:
- f.write(result)
- return True
-
- except Exception as ext:
- print(ext)
- return False
-
-
- if __name__ == '__main__':
- pass
- # qr = CreateQrCode(1)
- # qr.create_qrcode_v3()
- # qr.create_qrcode_v1()
-