Summary of customization of angular 2 + JSSDK

Keywords: Javascript angular SDK Web Development

Open any web page in the Wechat browser. If the sharing interface is not configured, Wechat will default to use the following information as sharing information:

  • Default title: HTML title

  • Default connection: the address of the current page, location.href

  • Default image: The front eligible image in the current page body will be taken (size must be greater than 300 PX * 300 px)

  • Default Summary: The address of the current page, location.href

That is to say, open a website in Wechat that does not do special treatment to Wechat browser, click on the upper right corner to share, and share out the news as follows:

In many cases, the default shared pictures and summaries are not up to expectations. This article is a summary of my process of customizing information sharing and trampling on the pit.

I. Necessary preparations

  • Wechat Certified Public Number

  • A registered domain name

  • Necessary back-end services (for obtaining initial signature information for Wechat jssdk)

Note: Both appId and signature should be available in the background. Specific writing can be referred to official documents.

Reference resources: https://mp.weixin.qq.com/wiki (Wechat Web Development - > Wechat JS-SDK Description Document - > Appendix 6-DEMO Page and Example Code)

II. Configuration process

Step 1: Binding domain names

First login to the Wechat Public Platform and enter the "Functional Settings" of "Public Number Settings" to fill in the "JS Interface Security Domain Name".

Step 2: Introduce JS files

Introduce the following JS files (support https) to pages that need to call the JS interface: http://res.wx.qq.com/open/js/...

Note: In angular 2, it can be directly introduced into index.html pages, so that each page will be introduced.

Step 3: Inject permission validation configuration through config interface

All pages that need to use JS-SDK must first inject configuration information, otherwise they will not be invoked.

wx.config({
    debug: true, // Turn on debugging mode, and the return values of all APIs invoked will appear in alert on the client side to view the incoming parameters
    appId: '', // Mandatory, Unique Identification of Public Number
    timestamp: , // Mandatory, time stamp for signature generation
    nonceStr: '', // Compulsory, generating random strings of signatures
    signature: '',// It must be filled. Note that signature s should be returned from the background
    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ'] // Must fill
});
Step 4: Configure Wechat Sharing Interface in ready Interface
 wx.ready(function () {
    wx.onMenuShareAppMessage({              //Configuration Sharing to Friends Interface
        title: 'Shared Titles', // Share title
        desc: 'This is a test sharing', // Sharing description
        link: location.href, // Share links
        imgUrl: '', // Share Icon
        type: '', // Sharing type, music, video or link, not default to link
        dataUrl: '', // If type is music or video, provide data links, which are empty by default
        success: function () { 
            // Callback function executed after user confirms sharing
        },
        cancel: function () { 
            // Callback functions executed after users cancel sharing
        }
    })
 });
Step 5: Optimize with angular 2

So far, the sharing function has been successful. However, this requires that Weichat share code in each component, which will lead to maintenance difficulties.

Since each component loaded by Angular 2 is packaged in the root component, it is possible to configure only the common shared configuration information in the root component to add optimized sharing operations to all pages. The idea of configuration is as follows:

  1. Configuring common initialization sharing interface information in the root component;

  2. Each time a page is loaded, initialization sharing is added to the page.

  3. There is a set of default sharing configuration, and the id configuration is used to configure the information shared in the page. If the page does not configure sharing information, the default configuration is used.

Based on the above ideas, the final implementation code is as follows:

//* Note: AppComponent must be the root component
export class AppComponent implements OnInit,AfterViewInit {

  ...
  
  ngAfterViewInit() {
    this.configWXShare();   //Configure Sharing in the Root Component
  }
  
  //Configuration sharing
  private configWX() {
    this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {       //Bind routing change events, each time new to a page
        let page = this;
        page.commonService.getWXJsInitConfig().then(obj => {
          page.commonService.configWXJs(obj, [
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ']);
        });

        setTimeout(function () {
          //Default Sharing Information
          let shareData = {title: 'Shared Titles'
            , link: location.href
            , desc: 'Description of Sharing'
            , imgUrl: page.getShareImgUrl()
          };

          //Get the shared information configured in the page, and use the default information if not configured
          shareData['title'] = document.getElementById('shareTitle') ?document.getElementById('shareTitle').innerText : shareData.title;
          shareData['imgUrl'] = document.getElementById('shareImg') ? document.getElementById('shareImg').getAttribute('src') : shareData.imgUrl;
          shareData['desc'] = document.getElementById('shareDesc') ? document.getElementById('shareDesc').innerText : shareData.desc;

          wx.ready(function () {
            wx.onMenuShareAppMessage(shareData);  // Share WeChat
            wx.onMenuShareTimeline(shareData);    // Share in the circle of friends
            wx.onMenuShareQQ(shareData);          // Share to QQ
          });
        }, 2000);    //Note: Initialization of the root component is complete, and asynchronous request data of the sub-component may not be returned, so registration and sharing will take 2 seconds.
      }
    });
  }
  
  //Automated access to shared thumbnails
  private getDefaultShareImgUrl() {
    let shareImg = document.getElementById('shareImg');
    if (shareImg) {
      return shareImg.getAttribute('src');
    }

    let imgList = document.querySelectorAll('img');
    for (let i = 0; imgList[i]; i++) {
      var imgSrc = imgList[i].getAttribute('src');
      if (imgSrc.startsWith('http://') || imgSrc.startsWith('https://')) {
        return imgSrc
      }
    }
  }

So far, only in one configuration, can flexibly configure the sharing completed.

Completion: The ultimate sharing is as follows:

Appendix. Trampling records

  • Tip {"errMsg": "config:invalid signature"}

There are many possibilities for this. However, there are three main reasons:

  1. Verify that the signature algorithm is correct and available http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign Page tool for verification.

  2. Determine whether the letters of nonceStr and timestamp in wx.config are capitalized correctly [common errors]

  3. Verify that the appid in config is the same as the appid used to obtain jsapi_ticket

Posted by dezkit on Fri, 12 Apr 2019 23:06:32 -0700