tool

微信小程序--使用getWXACodeUnlimit生成海报时包

2018-11-16  本文已影响114人  小钟钟同学

说明

关于微信小程序二维码的生成,官方文档有记载,这里仅作为个人笔记。纯属虾扯蛋一下! image.png

官网访问地址:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

小程序二维码生成步骤:

依据实际情况,后续生成的海报数量是无法预估的,所以我们使用的方案是:


image.png

生成步骤:

第一步:获取access_token

官网文档地址:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/access-token/getAccessToken.html

测试获取access_token 地址:
https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E5%9F%BA%E7%A1%80%E6%94%AF%E6%8C%81&form=%E8%8E%B7%E5%8F%96access_token%E6%8E%A5%E5%8F%A3%20/token&token=&lang=zh_CN

image.png
第二步:提交access_token到获取二维码接口

官网文档地址:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/qr-code/getWXACodeUnlimit.html

image.png
第三步:保存二维码到自己的服务器上面,返回二维码地址
第四步:canvas合成海报二维码地址

代码示例:

#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
#        ┏┓   ┏┓+ +
#    ┏┛┻━━━┛┻┓ + +
#    ┃       ┃  
#    ┃   ━   ┃ ++ + + +
#    ████━████ ┃+
#    ┃       ┃ +
#    ┃   ┻   ┃
#    ┃       ┃ + +
#    ┗━┓   ┏━┛
#      ┃   ┃           
#      ┃   ┃ + + + +
#      ┃   ┃    Codes are far away from bugs with the animal protecting   
#      ┃   ┃ +     神兽保佑,代码无bug  
#      ┃   ┃
#      ┃   ┃  +         
#      ┃    ┗━━━┓ + +
#      ┃        ┣┓
#      ┃        ┏┛
#      ┗┓┓┏━┳┓┏┛ + + + +
#       ┃┫┫ ┃┫┫
#       ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
Author = zyx
@Create_Time: 2018/11/16 16:30
@version: v1.0.0
@Contact: 308711822@qq.com
@File: get_ compose_acode.py
@文件功能描述:合并获取小程序二维码
"""
from business.logic.api_third_inter import _request
from basic.cache import redis_cache_helper
import json
import requests
from PIL import Image
from io import BytesIO
from basic.utils import file_helper


def get_wx_accesstoken(appid='', secret=''):
    """
      获取小程序授权码
    """
    # 缓存key
    cache_key = 'wx_access_token:' + str(appid)
    # 获取缓存值
    result = redis_cache_helper.get(cache_key)
    # 判断是否有值
    if result:
        return result

    # 设置参数
    params = {
        'appid': appid,
        'secret': secret,
        'grant_type': 'client_credential'
    }
    # 直接访问接口
    url = 'https://api.weixin.qq.com/cgi-bin/token'
    # 提交微信服务器
    _result = _request.get_direct(url, params)

    # 处理结果
    if not _result:
        return ''

    if _result.get('access_token'):
        expires_in = _result.get('expires_in')
        access_token = _result.get('access_token')
        # 设置缓存过期的时间
        redis_cache_helper.set(cache_key, access_token, timeout=int(expires_in) - 100)
        return access_token
    else:
        return ''


def action(host_name='', cp_appid='', openid='', appid='', secret='', scene='', page='', width=280, is_hyaline=True, auto_color=True, line_color=''):
    '''
    二维码生成的参数信息
    :param cp_appid: 分配合作的放的APID.用于组合生成的图片明名称
     :param openid: 永固的openID.用于组合生成的图片明名称
    :param appid: 小程序唯一凭证,即 AppID,可在「微信公众平台 - 设置 - 开发设置」页中获得
    :param secret: 小程序唯一凭证密钥,即 AppSecret,获取方式同 appid
    :param scene: 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符
    :param page:已经发布的小程序存在的页面(否则报错),例如 pages/index/index, 根路径前不要填加 /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面
    :param width: 二维码的宽度,默认为 430px,最小 280px,最大 1280px
    :param is_hyaline: 是否需要透明底色,为 true 时,生成透明底色的小程序码,默认 false
    :param auto_color: 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
    :param line_color: auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示,默认全 0
    :return:
    '''

    # 文件的名称
    file_name = str(cp_appid) + str(openid)
    # 保存的文件的路径
    file_path = "static/tmpfiles/wxcode_%s.jpg" % file_name

    # 先判断本地文件是否已经存在
    if file_helper.exists(file_path):
        # 直接的返回图片的地址
        return str(host_name) + str(file_path)

    # 需要添加到二维码的地址后面的授权码
    access_token = get_wx_accesstoken(appid=appid, secret=secret)

    if not access_token:
        # 抛出异常
        raise Exception("access_token is None")

    # 需要提交的参数
    params = {'access_token': access_token}

    # json数据值
    json_data = {"scene": scene,
                 "page": page,
                 "width": width,
                 "auto_color": auto_color,
                 "is_hyaline": is_hyaline}
    # 转化
    json_data = json.dumps(json_data).encode(encoding='utf-8')
    # 生成二维码地址
    url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode'
    # 提交到微信地址
    _result = requests.post(url, params=params, json=json_data, timeout=3, verify=False)

    if _result.status_code == 502 or _result.status_code == 500:
        # return return_msg(r.status_code, '服务器内部错误', result)
        return False

    if _result.status_code >= 400 and _result.status_code <= 499:
        # return return_msg(r.status_code, '语法格式有误,服务器无法理解此请求', result)
        return False

    # 判断返回的内容类型 如果是返回的 JSON 数据包
    if 'json' in _result.headers.get('content-type'):
        # 返回微信的错误描述信息
        return _result.json().get('errmsg')

    # 否则说明 请成功 以请求返回的二进制数据创建一张图片
    img = Image.open(BytesIO(_result.content))

    # 保存文件
    img.save(file_path, "jpg")  # 保存图像为gif格式

    return str(host_name) + str(file_path)

小程序的获取:


image.png

实际获取的方式可能和官方的文档是是有些出路的。

官网的文档是:

 onLoad (query) {
    // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    const scene = decodeURIComponent(query.scene)
  }

正确的方式应该是:

  onLaunch: function (options) {
    console.log("options", options)

    this.wxshare.getShareTicketDecryptData(options)
    // 从ops提取相关参数信息
    // 用户场景来源
    // let where_from_scene_id = options.scene
    // 场景值
    var where_from_scene_id = decodeURIComponent(options.query.scene)
上一篇下一篇

猜你喜欢

热点阅读