Steps to use JS-SDK in the project

 

Steps to use JS-SDK in the project

Demand background: Open the website page in the WeChat browser, and share it with friends or friends through the share button that comes with the WeChat browser. You can customize the shared pictures, descriptions and other related information.

Implementation: Use JS-SDK, use the API provided by WeChat to configure the parameters. In fact, the whole process is very simple, mainly because this xiaobai has not used JS-SDK before, so it took some time to explore how to use it. JS-SDK official documentation

Step introduction:

  1. Bind the domain name, the document description is shown below.

     It should be noted that the domain name must be verified by ICP record . In addition, after downloading the certificate file, upload the file to the server, where the file can be uploaded to the front-end server or the back-end server, as long as it can be accessed, then fill in the corresponding upload path.

    2. Introduce JS files. There are two ways to introduce JS files:

        Method one: As shown in the official documentation, create a script tag and then reference the corresponding JS file. When in use, you can write a function specifically for importing JS files.

function importWx(callback) {
    if (window.wx) {
        callback && callback()
    } else {        
        var url = "/static/js/utils/jweixin-1.4.0.js";
        var script = document.createElement("script");
        script.src = url
        document.body.appendChild(script);
        if(script.addEventListener){
          script.addEventListener("load", callback, false);
        } else if (script.attachEvent){
          script.attachEvent("onreadystatechange", function(){
        
            var target = window.event.srcElement;
        
             if(target.readyState == "loaded" || target.readyState == "complete"){
              callback && callback.call(target);
            }
        
          });
        }
    }
}

        Method 2: Use a third-party library that encapsulates js-sdk.

       

//安装
npm install weixin-js-sdk

//使用
const wx = require("weixin-js-sdk");

    3. Perform interface permission authentication, the official document description is shown in the following figure:

Detailed steps of the signature algorithm . Because the interface permission authentication needs to obtain the signature first, and the process of obtaining the signature involves obtaining sensitive information such as access_token, so this process is carried out in the backend, and then the backend classmates provide an interface for returning timestamp, nonceStr, The signature, jsapi_ticket and other fields allow the front-end students to authenticate.

    4. After verification, you can call the API interface of WeChat.

//wx-share.js
export const initWx = (wxConfig, shareConfig, cb) => {
  if (typeof window != "undefined") {
    const wx = require("weixin-js-sdk");
    wx.config(
      Object.assign(
        {
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          appId: "", // 必填,公众号的唯一标识
          timestamp: "", // 必填,生成签名的时间戳
          nonceStr: "", // 必填,生成签名的随机串
          signature: "", // 必填,签名
          jsApiList: [
            "updateTimelineShareData",
            "onMenuShareTimeline",
            "updateAppMessageShareData",
            "onMenuShareAppMessage"
          ] // 必填,需要使用的JS接口列表
        },
        wxConfig
      )
    );

    wx.ready(function() {
      //需在用户可能点击分享按钮前就先调用
      //分享到朋友圈
      wx.updateTimelineShareData &&
        wx.updateTimelineShareData(
          Object.assign(
            {
              title: "", // 分享标题
              link: "", // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: "" // 分享图标
            },
            shareConfig
          ),
          function(res) {
            //这里是回调函数
            cb && cb(res);
          }
        );
      wx.onMenuShareTimeline &&
        wx.onMenuShareTimeline(
          Object.assign(
            {
              title: "", // 分享标题
              link: "", // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: "", // 分享图标
              success: function() {
                // 用户点击了分享后执行的回调函数
              }
            },
            shareConfig
          )
        );
      //分享给朋友
      wx.updateAppMessageShareData &&
        wx.updateAppMessageShareData(
          Object.assign(
            {
              title: "", // 分享标题
              desc: "", // 分享描述
              link: "", // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: "", // 分享图标
              success: function() {
                // 设置成功
              }
            },
            shareConfig
          )
        );
      wx.onMenuShareAppMessage &&
        wx.onMenuShareAppMessage(
          Object.assign(
            {
              title: "", // 分享标题
              desc: "", // 分享描述
              link: "", // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: "", // 分享图标
              type: "", // 分享类型,music、video或link,不填默认为link
              dataUrl: "", // 如果type是music或video,则要提供数据链接,默认为空
              success: function() {
                // 用户点击了分享后执行的回调函数
              }
            },
            shareConfig
          )
        );
    });

    wx.error(function(res) {
      console.log(res);
      // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
    });
  }
};

    5. Method of use: InitWx can be introduced on the page where WeChat sharing is required. E.g:

import React, { Component } from "react";
import axios from 'axios';
import { initWx } from "../../../../utils/wx-share";

class NewsArticleComponent extends Component {
    componentDidMount() {
        axios({
        	method: 'get',
       		url: "后端提供的返回签名接口"
    	}).then(res => {
            if(res && res.code === 0 && res.data){
                initWx({
                    ...res.data
                },{
                    title:"自定义title",
                    keywords:"自定义keywords",
            	    desc: "自定义描述内容",
            	    imgUrl: "自定义图片"
                })
            }
        });
    }
    render() {
        return (
        	<div>我要分享啦~~~</div>
        )
    }
}

Effect picture:

        Success here! In fact, this part of the logic and code are very simple, mainly because it takes time to explore how to use it, so I hope that this post will reduce everyone's exploration time and make progress together with you!

Published 50 original articles · Likes5 · Visits 20,000+

Guess you like

Origin blog.csdn.net/qq_31207499/article/details/102664651