>  기사  >  위챗 애플릿  >  Python을 사용하여 WeChat 미니 프로그램에서 QR 코드를 생성하는 두 가지 방법

Python을 사용하여 WeChat 미니 프로그램에서 QR 코드를 생성하는 두 가지 방법

不言
不言원래의
2018-09-10 14:33:547993검색

이 글은 Python을 사용하여 WeChat 미니 프로그램에서 QR 코드를 생성하는 두 가지 방법을 제공합니다. 이는 특정 참조 가치가 있습니다. 도움이 필요한 친구가 도움이 되기를 바랍니다.

WeChat 애플릿은 QR 코드를 생성합니다.

사용되는 언어는 Python이며 두 가지 방법이 있습니다.

1: 백엔드가 문자열을 프런트엔드에 전달하고 프런트엔드가 이를 표시합니다.

2: 백엔드가 직접 그림을 생성합니다

1: 문자열을 프런트엔드에 전달한 후 프런트엔드에 표시

def get_wxCode(Request, UserInfo):
    try:
        scene = Request["scene"]
        access_token = get_wxCode_token()
        if not access_token:
            return False
        textmod = {"scene": scene, "page": "pages/index/main", "width": 430, "auto_color": True, "is_hyaline": False}
        textmod = json.dumps(textmod).encode(encoding='utf-8')
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                       "Content-Type": "application/json"}
        url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token
        req = request.Request(url=url, data=textmod, headers=header_dict)
        res = request.urlopen(req)
        res = res.read()
        b64str = base64.b64encode(res)
        return b64str
    except Exception as e:
        print(e)
        return False
var getWXcode2 = function(hostname){  //获取管理端小程序码

    //动态获取域名,若为本地环境,则默认携带参数为wx-test
    //示例:londex.i-plc.cn
    var hostname1 =  window.location.host;
    hostname1 = hostname1.split('.')[0];
    if(hostname1 == '127' || hostname1 == 'localhost'){
        hostname1 = hostname;
    }
    if(window.localStorage.getItem('wxcode2')){
        $('#wxcodeImg2').attr('src','data:image/png;base64,'+ window.localStorage.getItem('wxcode2'));
        $('#wxCodeModal2').modal('show');
        return;
    }
    var params = {
        "scene":hostname1,
    };
    $.ajax({
        type:'post',
        url:'/request?rname=i_plc.Page.wechat_api.wechat.get_wxCode',
        data:params,
        success:function (res) {
            console.log(res)

            if(res === false){
                $.MessageBox.notify('warn', '获取失败,请稍后再试!');
            }else{
                console.log(res)
                $('#wxcodeImg2').attr('src','data:image/png;base64,'+res);
                $('#wxCodeModal2').modal('show');
                window.localStorage.setItem('wxcode2',res)
            }

        }
    });
};

2: 백엔드에서 직접 그림 생성

def get_wxCode(Request, UserInfo):
    """
        生成小程序二维码
    :param Request:
    :param UserInfo:
    :return:
    """
    result = {"success": False}
    try:
        # scene = Request["scene"]
        access_token = get_wxCode_token()
        if not access_token:
            raise Exception("access_token")
        compid = Request["compid"]
        sql = "select compIndex from company where operationFlag=9 and compID=%s" % compid
        Result = SqlRun(sql)
        if Result["Data"] and Result["Data"][0] and Result["Data"][0][0]:
            scene = Result["Data"][0][0]

            textmod = {"scene": scene, "page": "pages/index/main", "width": 430, "auto_color": True, "is_hyaline": False}
            textmod = json.dumps(textmod).encode(encoding='utf-8')
            header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                           "Content-Type": "application/json"}
            url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token
            req = request.Request(url=url, data=textmod, headers=header_dict)
            res = request.urlopen(req)
            res = res.read()
            b64str = base64.b64encode(res)
            imgdata=base64.b64decode(b64str)

            path = "static/tmpfiles/scan_%s.png" % file_name
            file = open(os.path.join(settings.BASE_DIR, path,), 'wb+')
            file.write(imgdata)
            file.close()

            result["code_url"] = path
            result["success"] = True
    except Exception as e:
        result["error_msg"] = str(e)
    return json.dumps(result)


def get_wxCode_token():
    try:
        textmod = {"grant_type": "client_credential",
            "appid": "wx44a452fb08b0a990",
            "secret": "9aedb0a274027bdd09612fbde3298129"
        }
        textmod = parse.urlencode(textmod)
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'}
        url = 'https://api.weixin.qq.com/cgi-bin/token'
        req = request.Request(url='%s%s%s' % (url, '?', textmod), headers=header_dict)
        res = request.urlopen(req)
        res = res.read().decode(encoding='utf-8')
        res = json.loads(res)
        access_token = res["access_token"]
        return access_token
    except Exception as e:
        print(e)
        return False

관련 권장사항:

WeChat 애플릿 PHP는 매개변수를 사용하여 QR 코드를 생성합니다

WeChat 애플릿 사용자가 매개변수가 포함된 버튼 생성 QR 코드용 샘플 코드를 클릭합니다

위 내용은 Python을 사용하여 WeChat 미니 프로그램에서 QR 코드를 생성하는 두 가지 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.