1

A WeChat scan code H5 page to play video/audio

First of all, WeChat does not support automatic video playback.

When the H5 page is accessed through WeChat, when the video/audio of the H5 page is played, it will only take effect after the WeChat jssdk is loaded and then listen to onplay/onloadedmetadata/onend and other events, and it will not take effect until it is loaded.
So if you have audio and video event monitoring and want to support opening pages in WeChat, you need to pay attention when writing code:

  • Introduce WeChat jssdk
  • After the jssdk is loaded, the event is processed

2 WeChat custom sharing form

When you share a page address with your WeChat friends or group chat, you can customize the content displayed in the WeChat chat, such as our common card form instead of a link text.

Official document: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

Prepare

  1. A corporate WeChat official account is required. Many functions on the personal official account are not open.
  2. Set JS interface security domain name: call WeChat SDK interface under this domain name

image.png

  1. Need to use the JS-SDK provided by WeChat: WeChat JS-SDK is a WeChat-based web development toolkit provided by the WeChat public platform for web developers.

Officially begin

  1. Introduce jssdk:

    // index.html
    <script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  2. Inject sdk permission verification configuration through the config interface
// 引入jssdk之后,全局变量中会有wx
// wx sdk 权限验证配置
wx.config({
    // 开启调试模式,调用的所有api的返回值会在客户端alert出来
    debug: false, 
    // 必填,公众号的唯一标识
    appId: wxdata.appid, 
    // 必填,生成签名的时间戳
    timestamp: wxdata.timestamp, 
    // 必填,生成签名的随机串
    nonceStr: wxdata.noncestr, 
    // 必填,签名,见附录1
    signature: wxdata.signature, 
    // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    jsApiList: [
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "updateAppMessageShareData",
        "updateTimelineShareData",
    ] 
});
// sdk 权限验证配置成功回调
wx.ready(function() {
    console.log('wx.ready success');
})
// sdk 权限验证配置失败回调
wx.error(function(res) {
    console.log('wx.error', res);
});
  1. The server generates a signature (for security, it needs to be generated on the server), and obtain the wxdata data in step 2:
const sha1 = require('sha1'); 

async function getWXConfig() {
    let [appid, appsecret] = ['your appid', 'your appsecret']; // 公众号平台获取此信息
    // 获取 access_token
    const accessTokenUrl = 
  `https://api.weixin.qq.com/cgi-bin/token?grant_type=${'client_credential'}&appid=${appid}&secret=${appsecret}`;
    const r = await axios.get(accessTokenUrl);
    const access_token = r.data;

    // 获取 jsapi_ticket
    const ticketUrl =
        `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
    const res = await axios.get(ticketUrl);
    let { errcode, ticket, expires_in } = res.data;

    const LINK = 'xx.xx.com'; 
  // 在上面设置 JS 接口安全域名时的参数 //当然也可以在前端定义此参数进行传递
    const timestamp = +new Date(); // 签名的时间戳
    const noncestr = time + 's'; // 签名的随机串
    const url = LINK;

    const encodeStr = 
  `jsapi_ticket=${ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`;
    // 生成签名
    const signature = sha1(encodeStr);

    return {
        appid,
        signature,
        noncestr,
        timestamp,
        url,
    }
}
  1. Invoke WeChat SDK capabilities (mainly used here to share with friends, share to Moments, etc.)

refer to

Three generation of WeChat applet QR code

introduce

Call the WeChat API to generate a QR code for the mini program. Supports being directed to a specific page and passing in parameters. But this interface should be server, and the data returned by the call cannot be processed by the front end yet!
Official Introduction>>
image.png

How to use

Documentation

Calling method:

POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN

The following is copied from the official document, and the official version shall prevail.

AttributestypeDefaultsRequiredillustrate
access_tokenstring YesInterface call credentials
scenestring YesMaximum 32 visible characters , only supports numbers, uppercase and lowercase English and some special characters: !#$&'()*+,/:;=?@-._~ , please encode other characters as legal characters (because% is not supported, Chinese cannot be processed by urlencode, please use other encoding methods)
pagestringHome pagenoIt must be a page of a published applet (otherwise an error will be reported), such as pages/index/index before the root path, and cannot carry parameters (please put the parameters in the scene field) , if this field is not filled in, the homepage will be skipped by default noodle
widthnumber430noThe width of the QR code, the unit is px, the minimum is 280px, the maximum is 1280px
auto_colorbooleanfalsenoAutomatically configure the line color, if the color is still black, it means that it is not recommended to configure the main color, the default is false
line_colorObject{"r":0,"g":0,"b":0}noIt takes effect when auto_color is false. Use rgb to set the color. For example, {"r":"xxx","g":"xxx","b":"xxx"} Decimal representation
is_hyalinebooleanfalsenoWhether you need a transparent background color, when it is true, a small program that generates a transparent background color

Precautions

  • Usually we only need to pay attention to access_token , page , scene
  • scene used to pass parameters. The self-characters we usually use generally do not need to be encoded by themselves, and the WeChat API will encode them. Format: u=123&m=456 equivalent to pages/xxx/index?scene=(encodeURLComponent(u=123&m=456)) .
  • scene has a length limit. In order to avoid exceeding the length limit, it is recommended to compress the parameter content:

    • Use position markers instead of kv, for example: userId=${userId}&missionId=${missionId}&idSign=${idSign(32bits)} becomes ${userId}_${missionId} _${idSign(6bits) )}
    • Pass in a voucher, and then write an interface parameter query through this voucher after reaching the applet
  • page: The path of the applet page, do not add / before the root path, and cannot carry parameters

Buffer file processing

Since the applet returns a buffer file, additional processing is required to get the image file available on the front end.
The following is the processing in node: upload the buffer file and get the file address.

const bufferArrary = [137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,1,3,0,0,0,37,219,86,202,0,0,0,6,80,76,84,69,0,0,255,128,128,128,76,108,191,213,0,0,0,9,112,72,89,115,0,0,14,196,0,0,14,196,1,149,43,14,27,0,0,0,10,73,68,65,84,8,153,99,96,0,0,0,2,0,1,244,113,100,166,0,0,0,0,73,69,78,68,174,66,96,130];
const array = Uint8Array.from(bufferArrary);
const blob = new Blob([array], {type: 'image/png'});
const form = new FormData();
form.append('file', blob, '1.png');
axios.post('http://localhost:7787/files', form);

Mini terminal use

If the applet terminal wants to get the parameters, it needs to parse query in scene .

Parameter receiving

Parse storeNo:
image.png

onLoad(options) {
  const scene = decodeURIComponent(options.scene);
  const storeNo = scene.split('=')[1]
  if (storeNo) {
    console.log(storeNo); 
  } else {
    console.error('生成二维码出现问题');
  }
},

Multiple parameters

image.png

const scene = decodeURIComponent(options.scene)
scene.split('&').forEach((item) => {
  const key = item.split("=")[0]
  this.setData({
    [key]: item.split('=')[1]
  })
})

tool

WeChat built-in browser to clear cache

Android

1. Just open a chat window, enter debugx5.qq.com and send.
2. Click the address sent by yourself to open the debug page.
image.png

Insert picture description here
Pull to the bottom of the debugging page, check all cache items, and click Clear.

Apple

Open [Settings] → [General], → [Clean WeChat Cache], and finally [Logout] account to complete.


specialcoder
2.2k 声望170 粉丝

前端 设计 摄影 文学