django --生成微信小程序二维码

该代码示例展示了如何利用Python请求微信API来生成小程序二维码,包括获取access_token,生成v3和v1版本的二维码,并将二维码图片保存到本地。代码中定义了一个SingletonType元类,用于确保CreateQrCode类只有一个实例。创建二维码时,可以指定场景值、页面路径和版本类型。
摘要由CSDN通过智能技术生成

官文:

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

像风一样的男人@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值