Although I am very rookie, but I also want to share CSDN points download needs of the students, comments concern reply I can, free to everyone download ⚽ I firmly believe that love to share luck must not be bad, progress is very happy, share more happy 😬

GitHub

First give monkey anxious guest officer dry goods code, access to wechat JSSDK GitHub address

preface

The cause was that the epidemic was serious, and the leader asked to make a special page to help the people in need as much as possible. As a result, the dog and colleagues burn the midnight oil, overtime work out. After the deployment is online and shared with the built-in browser of wechat, the ideal state should be like this, as shown below ⬇️


However, the result was not ideal, silently leaving tears without technology, as shown below ⬇️



Unexpectedly there are no keywords and display pictures, in the unremitting efforts of the dog, finally admitted that the technology is not good, to consult the big guy, the following conclusions.

  • 1. If you need to customize the display description and the right cover image to share by the built-in browser of wechat, you must be connected to the wechat JSSDK, and you must have the wechat public number (appId and appSecret) matching the site to customize the share, remember that small programs (appId and appSecret) are not allowed
  • 2. Non-wechat sharing, such as QQ Browser, UC browser and other major manufacturers, will obtain TDK(title, description, keyword) in HTML pages according to their own definitions, for example, UC browser sharing ⬇️



    Insert a picture description here


    Therefore, docking wechat JSSDK is imperative!


Tip

In the history of the most detailed access to wechat JSSDK rookie tutorial, this article comprehensively recorded access to wechat JSSDK steps, specific code and encountered pits, and show the release of the final effect, and the code release GitHub. Along with the longer, but the most complete history. Big guy do not spray, novice, pro test available!!

Trial population

  • Students who need to access wechat JSSDK but do not understand the document
  • Those of you who can read the documentation but don’t know how to do it
  • Under the hand but do not know how to debug and modify the students
  • Those of you who have successfully logged in but want to go over the process

In this paper, the target

  • Practice H5 website wechat custom sharing
  • Actual H5 site access album selection pictures

Relax and take your time


The body of the

The official documentation

For any platform access, the official document is the benchmark. Although some key points have been passed over, we should also read through and get an impression. Click the official document of wechat to open the document, as follows: ⬇️

Insert a picture description here
The overview
  • 1. X is a key step for access, which needs to be read carefully and is related to access
  • 2. X-12. For details about how to connect to the x-12
  • 13. X needs to pay attention to the api_ticket wechat temporary ticket, which is related to access
  • 16-22 are all appendixes. You can check the meanings of error lists and interface menu lists

Real operating steps

Use IDEA to create a SpringBoot project named springboot-wexin. The directory structure is as follows

Insert a picture description here



AjaxJson.java– Custom interface returns a wrapper class for foreground data format

/ * *

 * Copyright &copy; 2005-2020 <a href="http://www.jhmis.com/">jhmis</a> All rights reserved.

* /


package net.javadog.springbootwexin.common;



import com.fasterxml.jackson.annotation.JsonIgnore;



import java.util.LinkedHashMap;

import java.util.List;





/ * *

* $. JSON needs to be accepted after ajax

 *

* /


public class AjaxJson {



    private boolean success = true;// Check whether it succeeds

    private String errorCode = "1";// Error code

    private String msg = "Operation successful";// Prompt message

    private Long count;             // Return the number of table records

    privateList<? > data;// Return table data

    private LinkedHashMap<String, Object> body = new LinkedHashMap<String, Object>();// Encapsulates the JSON map



    public static AjaxJson ok(a){

        AjaxJson j = new AjaxJson();

        return j;

    }



    public static AjaxJson ok(String msg){

        AjaxJson j = new AjaxJson();

        j.setMsg(msg);

        return j;

    }



    public static AjaxJson ok(String msg, Object object){

        AjaxJson j = new AjaxJson();

        j.setMsg(msg);

        j.setResult(object);

        return j;

    }



    public static AjaxJson ok(Object object){

        AjaxJson j = new AjaxJson();

        j.setResult(object);

        return j;

    }



    public static AjaxJson fail(String errorMsg){

        AjaxJson j = new AjaxJson();

        j.setSuccess(false);

        j.setErrorCode("999");// Default error code

        j.setMsg(errorMsg);

        return j;

    }



    public static AjaxJson fail(String errorCode,String errorMsg){

        AjaxJson j = new AjaxJson();

        j.setSuccess(false);

        j.setErrorCode(errorCode);

        j.setMsg(errorMsg);

        return j;

    }

    // Return non-paged layui table data

    public static AjaxJson layuiTable(List list){

        AjaxJson j = new AjaxJson();

        j.setSuccess(true);

        j.setCount(Long.valueOf(list.size()));

        j.setData(list);

        return j;

    }

    public LinkedHashMap<String, Object> getBody(a) {

        return body;

    }



    public void setBody(LinkedHashMap<String, Object> body) {

        this.body = body;

    }



    public void put(String key, Object value){// To add attributes to JSON and access them in JS, call data.map.key

        body.put(key, value);

    }



    public void remove(String key){

        body.remove(key);

    }



    / * *

* Set the result content directly

     * @param result

* /


    public void setResult(Object result){

        body.put("result", result);

    }

    @JsonIgnore// Ignore this property when returning an object

    public Object getResult(a){

        return body.get("result");

    }



    public String getMsg(a) {

        return msg;

    }



    public void setMsg(String msg) {// Add attributes to JSON and access them in JS by calling data.msg

        this.msg = msg;

    }





    public boolean isSuccess(a) {

        return success;

    }



    public void setSuccess(boolean success) {

        this.success = success;

    }





    public void setErrorCode(String errorCode) {

        this.errorCode = errorCode;

    }



    public String getErrorCode(a) {

        return errorCode;

    }



    public Long getCount(a) {

        return count;

    }



    public void setCount(Long count) {

        this.count = count;

    }



    publicList<? > getData() {

        return data;

    }



    public void setData(List data) {

        this.data = data;

    }

}

Copy the code

Wxinitcontroller. Java – initializes wechat access Controller

package net.javadog.springbootwexin.controller;

import net.javadog.springbootwexin.common.AjaxJson;

import net.javadog.springbootwexin.service.WxService;

import net.javadog.springbootwexin.utils.WxUtil;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import java.util.Map;



/ * *

* A low-end cheap and classless program dog JavaDog

 * blog.javadog.net

 *

 * @BelongsProject: springboot-wexin

 * @BelongsPackage: net.javadog.springbootwexin.controller

 * @Author: hdx

 * @CreateTime: 2020-02-14 any valiant man

 * @Description: wechat initializes access Controller Controller

* /


@RestController

@RequestMapping("/weixin")

public class WxInitController {

    protected Logger logger = LoggerFactory.getLogger(getClass());



    @Autowired

    private WxService wxService;



    / * *

    *@Author: hdx

    *@CreateTime: the men 2020/2/14

    *@param: shareUrl shareUrl

    *@Description: Initializes the wechat JSSDK Config information

1. Obtain AccessToken by requesting the specified wechat address using appId and appSecret parameters

2. Request wechat address to obtain jSAPi_ticket temporary ticket through AccessToken as parameter in the first step (call frequency is not taken into account here, users put it into cache or scheduled task according to the situation)

3. Use JssdkGetticket and timestamp,nonceStr and URL as parameters in step 2 to request the wechat address and obtain the signature

4. Will get the signature of the third step and jsapi_ticket nonceStr, timestamp, url is returned to the front, as the Config initialization validation information

* /


    @RequestMapping("/initWXJSSDKConfigInfo")

    public AjaxJson initWXJSConfig (@RequestParam(required = false) String url) throws Exception{

        logger.info("url=" + url);

        String json = "";

        try {

            Map map = wxService.initJSSDKConfig(url);

            json = WxUtil.mapToJson(map);

        }catch (Exception e){

            AjaxJson.fail(e.getMessage());

        }

        return AjaxJson.ok(json);

    }



}

Copy the code

Wxservice. Java – Initialize JSSDKConfig

package net.javadog.springbootwexin.service;



import lombok.Getter;

import net.javadog.springbootwexin.utils.WxUtil;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import java.util.HashMap;

import java.util.Map;

import java.util.UUID;



/ * *

* A low-end cheap and classless program dog JavaDog

 * blog.javadog.net

 *

 * @BelongsProject: springboot-wexin

 * @BelongsPackage: net.javadog.springbootwexin.service

 * @Author: hdx

 * @CreateTimeThus 2020-02-14:

 * @Description: Wechat related services

* /


@Service

public class WxService {

    @Getter

    private static String AppId;

    @Value("${wx.appId}")

    public void setAppId(String appId) {

        AppId = appId;

    }

    / * *

    *@Author: hdx

    *@CreateTime: who fell 2020/2/14

    *@param: shareUrl shareUrl

    *@Description: Initializes JSSDKConfig

* /


    public Map initJSSDKConfig(String url) throws Exception {

        / / get AccessToken

        String accessToken = WxUtil.getJSSDKAccessToken();

        / / get JssdkGetticket

        String jsapiTicket = WxUtil.getJssdkGetticket(accessToken);

        String timestamp = Long.toString(System.currentTimeMillis() / 1000);

        String nonceStr = UUID.randomUUID().toString();

        String signature = WxUtil.buildJSSDKSignature(jsapiTicket,timestamp,nonceStr,url);

        Map<String,String> map = new HashMap<String,String>();

        map.put("url", url);

        map.put("jsapi_ticket", jsapiTicket);

        map.put("nonceStr", nonceStr);

        map.put("timestamp", timestamp);

        map.put("signature", signature);

        map.put("appid", AppId);

        return map;

    }

}

Copy the code

Wxutil. Java – wechat tool class

package net.javadog.springbootwexin.utils;



import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

import lombok.Getter;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Component;

import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;

import java.util.Map;



/ * *

* A low-end cheap and classless program dog JavaDog

 * blog.javadog.net

 *

 * @BelongsProject: springboot-wexin

 * @BelongsPackage: net.javadog.springbootwexin.utils

 * @Author: hdx

 * @CreateTimeAll the 2020-02-14:

 * @Description: Wechat tool class

* /


@Component

public class WxUtil {

    @Getter

    protected static String AppId;

    @Getter

    protected static String AppSecret;

    @Getter

    protected static String JssdkAccesstokenUrl;

    @Getter

    protected static String JssdkGetticketUrl;



    @Value("${wx.appId}")

    public void setAppId(String appId) {

        AppId = appId;

    }



    @Value("${wx.appSecret}")

    public void setAppSecret(String appSecret) {

        AppSecret = appSecret;

    }



    @Value("${wx.jssdk_accesstoken_url}")

    public void setJssdkAccesstokenUrl(String jssdkAccesstokenUrl) {

        JssdkAccesstokenUrl = jssdkAccesstokenUrl;

    }



    @Value("${wx.jssdk_getticket_url}")

    public void setJssdkGetticketUrl(String jssdkGetticketUrl) {

        JssdkGetticketUrl = jssdkGetticketUrl;

    }



    / * *

    *@Author: hdx

    *@CreateTime: then 2020/2/14

    *@param:  * @param null

    *@Description:



* /


    public static String getJSSDKAccessToken(a) {

        String token = null;

        String url = JssdkAccesstokenUrl.replaceAll("APPID".

                AppId).replaceAll("APPSECRET".

                AppSecret);

        String json = postRequestForWeiXinService(url);

        Map map = jsonToMap(json);

        if(map ! =null) {

            token = (String) map.get("access_token");

        }

        return token;

    }



    / * *

    *@Author: hdx

    *@CreateTime: "2020/2/14

    *@param:  * @param null

    *@Description: Obtain the JssdkGetticket based on accessToken



* /


    public static String getJssdkGetticket(String accessToken) {

        String url = JssdkGetticketUrl.replaceAll("ACCESS_TOKEN", accessToken);

        String json = postRequestForWeiXinService(url);

        Map map = jsonToMap(json);

        String jsapi_ticket = null;

        if(map ! =null) {

            jsapi_ticket = (String) map.get("ticket");

        }

        return jsapi_ticket;

    }



    / * *

    *@Author: hdx

    *@CreateTime: all 2020/2/14

    *@param:ticket Indicates the JssdkGetticket generated based on the accessToken

    *@param:timestamp indicates the timestamp of the payment signature. Note that all timestamp fields used in wechat JSSDK are lowercase. But the latest version of the payment background generated signature timeStamp field name needs to capitalize the S character

    *@param:nonceStr Random character string

    *@param: URL Indicates the URL of the current web page

    *@Description: Builds the signature to share the link



* /


    public static String buildJSSDKSignature(String ticket,String timestamp,String nonceStr ,String url) throws Exception {

        String orderedString = "jsapi_ticket=" + ticket

                + "&noncestr=" + nonceStr + "&timestamp=" + timestamp

                + "&url=" + url;



        return sha1(orderedString);

    }



    / * *

* SHA1 encryption JSSDK wechat configuration parameters to obtain signatures.

     *

     * @return

* /


    public static String sha1(String orderedString) throws Exception {

        String ciphertext = null;

        MessageDigest md = MessageDigest.getInstance("SHA-1");

        byte[] digest = md.digest(orderedString.getBytes());

        ciphertext = byteToStr(digest);

        return ciphertext.toLowerCase();

    }

    / * *

* Convert a byte array to a hexadecimal string

     *

     * @param byteArray

     * @return

* /


    private static String byteToStr(byte[] byteArray) {

        String strDigest = "";

        for (int i = 0; i < byteArray.length; i++) {

            strDigest += byteToHexStr(byteArray[i]);

        }

        return strDigest;

    }

    / * *

* Converts bytes to hexadecimal strings

     *

     * @param mByte

     * @return

* /


    private static String byteToHexStr(byte mByte) {

        char[] Digit = { '0'.'1'.'2'.'3'.'4'.'5'.'6'.'7'.'8'.'9'.'A'.'B'.'C'.'D'.'E'.'F' };

        char[] tempArr = new char[2];

        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];

        tempArr[1] = Digit[mByte & 0X0F];



        String s = new String(tempArr);

        return s;

    }

    / * *

    *@Author: hdx

    *@CreateTime: 21:49 2020/2/14

    *@param:  map

    *@Description:  mapToJson



* /


    public static String mapToJson(Map map){

        Gson gson = new Gson();

        String json = gson.toJson(map);

        return json;

    }



    / * *

    *@Author: hdx

    *@CreateTime: 21:37 2020/2/14

    *@param:  json

    *@Description: jsonToMap



* /


    private static Map jsonToMap(String json) {

        Gson gons = new Gson();

        Map map = gons.fromJson(json, new TypeToken<Map>(){}.getType());

        return map;

    }



    / * *

    *@Author: hdx

    *@CreateTime: accounted 2020/2/14

    *@param:  * @param null

    *@Description: Retrieve the wechat interface



* /


    private static String postRequestForWeiXinService(String getAccessTokenUrl) {

        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> postForEntity = restTemplate.postForEntity(getAccessTokenUrl, null, String.class);

        String json = postForEntity.getBody();

        return json;

    }



}

Copy the code

SpringbootWexinApplication. Java – SpringBoot start class

package net.javadog.springbootwexin;



import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;



@SpringBootApplication

public class SpringbootWexinApplication {



    public static void main(String[] args) {

        SpringApplication.run(SpringbootWexinApplication.class, args);

    }



}

Copy the code

Config /application.yml – Base configuration file

spring:

  profiles:

Activate the configuration file

    active: prod

Configure static resource paths

  resources:

    static-locations: classpath:/static/



# log correlation

logging:

Configuration file log path

  config: classpath:logback-spring.xml



# Wechat related configuration

wx:

#appId

  appId: wx4ad618620f8c3528

#appSecret

  appSecret: b772c7863b29e270aa86e40f9b9e6215

# Refer to the following documentation for access_token (valid for 7200 seconds, developers must cache access_token globally on their own services)

  jssdk_accesstoken_url: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

Jsapi_ticket (valid for 7200 seconds, developers must cache jsapi_ticket globally on their own services)

  jssdk_getticket_url: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

Copy the code

Application-dev.yml – Development profile (optional)

Configure the development environment

spring:

  profiles: dev



# Port Settings

server:

  port: 8000

Copy the code

Application-prod. yml – Production configuration file (formal production configuration due to JS interface security domain name limitation)

Production environment configuration

spring:

  profiles: prod



# Port Settings

server:

  port: 8002

Copy the code

Application-test.yml – Test configuration file (optional)

Production environment configuration

spring:

  profiles: prod



# Port Settings

server:

  port: 8002

Copy the code

**demo.html ** – Test h5 page


       

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Test JSSDK</title>

    <! -- Introduce wechat JS file -->

    <script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js" type="text/javascript"></script>

    <! - introduction of jquery - >

    <script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>

<script>

    // Get the current page address

    var url = (window.location.href).split(The '#') [0];

    // Retrieve the background interface to obtain permission authentication configuration

    $.ajax({

        type : "get".

        / *!!!!!! Remember to change to your own */

        url : "http://wxjssdk.javadog.net/weixin/initWXJSSDKConfigInfo?url="+url,// Replace url, XXX according to their own JSSDK file location modification

        success : function(data){

            console.log("Return value =" + data);

            var msg = "";

            if(data.success){

                msg = JSON.parse(data.msg);

            }

            // Verify the configuration through the config interface injection permission

            wx.config({

                debugtrue.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log

                appId: msg.appid,

                timestamp: msg.timestamp,

                nonceStr: msg.nonceStr,

                signature: msg.signature,

                / *!!!!!! Remember to choose according to your needs, refer to the document to fill in */

                jsApiList: [

                    "onMenuShareAppMessage".// Share with friends

                    "chooseImage"

                ]

            });

        },

        error:function(data){

            alert(JSON.stringify(data));

        }

    });



    // Successful verification through the ready interface processing

    wx.ready(function (){

        wx.checkJsApi({

            jsApiList: ['chooseImage'.'onMenuShareAppMessage'].

            successfunction (res{JSON.stringify(res)}

        });

        var shareData = {

            title'title'.

            desc'introduction'.// Be careful to remove HTML

            link: url,

            imgUrl'http://b2b.haier.com/shop/userfiles/sys/1/files/201912/af656b3a-8c2c-424d-937b-a8035deb78f5.jpg'

        };

        wx.onMenuShareAppMessage(shareData);





    });

    // Select an image from the album

    function wxchooseImage(){

        wx.chooseImage({

            count1./ / the default 9

            sizeType: ['original'.'compressed'].// You can specify whether the image is original or compressed. By default, both are available

            sourceType: ['album'.'camera'].// You can specify whether the source is photo album or camera, and default is both

            success: function (res{

                var localIds = res.localIds; // Returns a list of local ids for the selected photo. The localId can be used as the SRC attribute of the IMG tag to display the image

            }

        });

    }

</script>

</head>

<body>

<button onclick="wxchooseImage();">Click me Pick Album</button>

</body>

</html>

Copy the code

🔥nginx configuration, this is not code in the project!! Nginx. config – Nginx server configuration

 server

    {

listen 80; Set listening port to 80.

server_name wxjssdk.javadog.net; Please bind your own prefix domain name.

        location / {

        proxy_set_header HOST $host;

        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_set_header X-Real-IP $remote_addr;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Proxy_pass http://127.0.0.1:8002/;

      }

    }

Copy the code

Mp_verify_b0vmqlcguxrzp1rc. txt-js Interface security domain name authentication file (replaced with the public account), which must be accessible in the domain name root path

# be sure to put your own public number on the TXT verification file!!

B0vMQLCguxRzP1Rc

Copy the code

Steps,

Open the documentation JSSDK using the steps section, as follows ⬇️

Insert a picture description here
1. Bind the domain name
Insert a picture description here


Log on first
Wechat public platformEnter “Public account Settings” “Function Settings” and fill in “JS interface security domain name”. The following ⬇ ️


Insert a picture description here


Click on the Settings below ⬇️


Insert a picture description here
The key point
  • 1. The value can contain only three domain names or paths, such as Chinese names, IP addresses, and paths with ports
  • 2. The domain name must be ICP registered. Some students can not set JS secure domain name using Intranet penetrating peanut shell
  • 3. TXT file must be placed security domain name of the directory, such as wxjssdk.javadog.net/xxx.txt. Can be configured by nginx, as long as you can access it, if not, can not set JS secure domain name
2. Import the JS file
Insert a picture description here


The actual reference is in line 9 of our project demo.html page, as shown below


3. Use the injection permission of the Config interface to verify the configuration
Insert a picture description here
The key point

An interface must be opened in the background to obtain the injection permission for the config interface, corresponding to the initWXJSSDKConfigInfo() method in our code wxinitController.java. Returns the document required mandatory appId, timestamp, nonceStr, signature verification parameters

Insert a picture description here
Implementation steps
1. Obtain AccessToken by requesting the specified wechat address using appId and appSecret parameters

2. Request wechat address to obtain jSAPi_ticket temporary ticket through AccessToken as parameter in the first step (call frequency is not taken into account here, users put it into cache or scheduled task according to the situation)

3. Use JssdkGetticket and timestamp,nonceStr and URL as parameters in step 2 to request the wechat address and obtain the signature

4. Will get the signature of the third step and jsapi_ticket nonceStr, timestamp, url is returned to the front, as the Config initialization validation information

Copy the code
Insert a picture description here
  • 1. Obtain AccessToken by requesting the specified wechat address via the appId and appSecret parameters, which corresponds to the getJSSDKAccessToken() method in wxutil.java on line 61

    Insert a picture description here


    throughAppId and appSecret of your official accountcallWechat server Access_token Interface address to obtain a token, the address is as follows

    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

    APPID and APPSECRETReplace it with your public account appId and appSecret, returns the Json string result and obtains the access_token

  • 2. Obtain the jSAPi_ticket temporary ticket by requesting the wechat address with the AccessToken parameter in step 1, which corresponds to the getJssdkGetticket() method in line 81 of wxutil.java

    Insert a picture description here


    I got from the previous stepaccess_tokencallWechat server jSAPi_ticket Interface address Obtain jsapi_ticket, the address is as follows

    https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

    Will the ACCESS_TOKENReplace with the access_token obtained in the previous stepJsapi_ticket is returned

  • 3. Request wechat address by JssdkGetticket and TIMESTAMP,nonceStr, URL as parameters in step 2, and obtain signature corresponding to buildJSSDKSignature() method in line 102 of WxUtil

    Insert a picture description here


    I got from the previous stepjsapi_ticket, plus timestamp(payment signature timestamp),nonceStr(random string),url(url of current web page), sorted according to ASCII code of field name from small to large (lexicographical order), and signed through sha1 to generate the final signature data.

    Correspond to the sha1() method on line 115 of wxutil.java in our code

    Insert a picture description here
  • 4. The front end successfully receives the return value

This corresponds to the $.ajax method in line 16 of our demo.html code

Insert a picture description here


The interface return value is


Insert a picture description here


Parse (MSG) convert the JSON object, which corresponds to line 24 in demo.html of our code, and verify the wx.config interface injection permission of the converted data, which corresponds to line 37 of our code demo.html


Insert a picture description here
4. Verify the processing through the ready interface
Insert a picture description here
The key point

So if you need to call the related interface when the page loads, you need to call the related interface in the ready function to ensure that it executes correctly. In line 46 of our code in demo.html, the custom shared interface needs to be put in ready when the page loads initially

Insert a picture description here



Otherwise, user events trigger execution that do not require initial loading


In line 63 of our code in demo.html, the user clicks the button to trigger the interface – take a photo or select an image from the phone’s album


Insert a picture description here

release

I use IDEA plugin Alibaba Cloud Toolkit to deploy local applications to ECS server in one click. Baidu or wait for my next article to explain the use of this plugin.

Insert a picture description here


Insert a picture description here


Target ECS: I bought ali’s server, so I can search it directly.


Target Directory: indicates the Target Directory to which the jar package needs to be uploaded, for example, /usr/local/hdx/web/


Command: after upload operation Command execution Such as: nohup Java jar/usr/local/HDX/web/springboot – wexin. Jar

A success message is displayed on the terminal

Insert a picture description here


Then you’re done. Give it a try
wxjssdk.javadog.net/demo.html


Recommended for debugging
Wechat developer tools, that is,


Insert a picture description here


Bear in mind that
Configure nginxand
Server security port access permission!!!!!!!!! Otherwise 404 will be oh!!

test

  • 1. Test the interface for taking photos or selecting images from your phone’s album

    Insert a picture description here


    Debugging to normal

  • 2. Test the built-in sharing of wechat

    Insert a picture description here


    Debugging error, this is a small hole. This dog has been here for a long time, and the reason is personalThe subscription number does not have custom share permissionThe!!!!!

    Insert a picture description here

Small pit summary

  1. The subscription number and service number involve different permissions, so you need to check the wechat development document in detail to query the permissions of the public account
  2. If the IP address whitelist is not set, 40164 is reported


    Insert a picture description here


    IP whitelist needs to be in the public accountSecurity Center Settings

    Insert a picture description here
  3. Invalid signature Abnormal You are advised to use the wechat JSSDK signature verification tool to check whether errors are found

I am JavaDog, thank you for your patience, click a thumbs-up 👍 and walk again bai, not criticism comment on two lines!!