WeChat Official Account Java Development Record (1) Access


Overview of WeChat Public Platform Development|WeChat Official Documents

1. Apply for a test number

First apply for a test official
account , because the official account we personally applied for cannot be authenticated, and there are many permissions that cannot be obtained. It is much more convenient to apply for a test account.
Apply for a test number

2. Intranet penetration access

We need to use intranet penetration to facilitate our testing, and it is also possible to deploy directly on the cloud server.
I use the free Sunny-Ngrok intranet forwarding . If it is unstable, try a few more times.
Insert picture description here

Three, cloud server access

To connect to cloud services, you need to configure nginx forwarding

  		location /wx {
    
              
             proxy_pass http://116.62.13.104:8083;
         }

Then restart the nginx ./nginx -s reload
URL: http://116.62.13.104/wx/
Insert picture description here

Insert picture description here

Insert picture description here

Three, code access

Insert picture description here
You can see that there is interface configuration information on the page: it
URLis the address we give to the WeChat server to access our project. Here I use the intranet penetration, so I use the domain name address assigned by others. (If only using the cloud server, fill in the normal Ip+port+path).
TokenWe define it at will.
Note: We need to be able to configure the WeChat server through the URL when our project (started locally to configure intranet penetration or deployed on the cloud service) can be successfully configured.

Project structure

Insert picture description here

application.yml

server:
  port: 8083
  tomcat:
    # tomcat的URI编码
    uri-encoding: UTF-8
    # tomcat最大线程数,默认为200
    # Tomcat启动初始化的线程数,默认值25
    threads:
      max: 800
      min-spare: 30
spring:
  datasource:
    url: jdbc:mysql://116.62.13.104:3306/countdown?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true
  redis:
    host: 116.62.13.104
    port: 6379
# token配置
token:
  # token 值
  value: liushihao123
  # 令牌自定义标识
  header: Authorization
  # 令牌秘钥
  secret: abcdefghijklmnopqrstuvwxyz
  # 令牌有效期(默认30分钟)
  expireTime: 30


logging:
  file:
    path: /data/wx/logs/

Controller

package com.wx.controller;

import com.wx.model.Param;
import com.wx.service.WXService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author :LiuShihao
 * @date :Created in 2020/9/28 2:49 下午
 * @desc :
 */
@RestController
@RequestMapping("/wx")
public class WXController {
    
    

    @Autowired
    WXService wxService;


    /**
     * signature	微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * timestamp	时间戳
     * nonce	随机数
     * echostr	随机字符串
     *
     * 开发者通过检验signature对请求进行校验(下面有校验方式)。
     * 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
     * @return
     */
    @GetMapping
    public String test1(Param param) throws IOException {
    
    
        System.out.println("param:"+param);
        if(wxService.check(param)){
    
    
            System.out.println("接入成功");
            //原样返回
            return param.getEchostr();
        }else {
    
    
            System.out.println("接入失败");
            return null;
        }
    }
}

ServiceImpl

service interface
Insert picture description here

package com.wx.service.Impl;

import com.wx.model.Param;
import com.wx.service.WXService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author :LiuShihao
 * @date :Created in 2020/10/2 1:12 下午
 * @desc :
 */
@Service
public class WXServiceImpl implements WXService {
    
    

    @Value("${token.value}")
    public String token;

    /**
     * 开发者通过检验signature对请求进行校验(下面有校验方式)。
     * 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
     *
     * 1)将token、timestamp、nonce三个参数进行字典序排序
     * 2)将三个参数字符串拼接成一个字符串进行sha1加密
     * 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
     * @param param
     * @return
     */
    @Override
    public boolean check(Param param) {
    
    
        //1)将token、timestamp、nonce三个参数进行字典序排序
        String[] strs = {
    
    token,param.getTimestamp(),param.getNonce()};
        Arrays.sort(strs);
        //2)将三个参数字符串拼接成一个字符串进行sha1加密
        String str = strs[0]+strs[1]+strs[2];
        String mysign = sha1(str);
        System.out.println("加密前:"+str);
        System.out.println("Signature:"+param.getSignature());
        System.out.println("mysign::"+mysign);
        //3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
        return  param.getSignature().equals(mysign);
    }

    private String sha1(String str) {
    
    
        StringBuilder sb = new StringBuilder();
        try {
    
    
            //获取一个加密对象
            MessageDigest md = MessageDigest.getInstance("sha1");
            //加密
            byte[] digest = md.digest(str.getBytes());
            char[] chars = {
    
    '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            
            //处理加密结果
            for (byte b : digest){
    
    
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }

        } catch (NoSuchAlgorithmException e) {
    
    
            e.printStackTrace();
        }
        return sb.toString();
    }
}

Entity class

package com.wx.model;

import lombok.Data;

/**
 * @author :LiuShihao
 * @date :Created in 2020/9/29 5:13 下午
 * @desc :
 */
@Data
public class Param {
    
    
    /**
     * signature	微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * timestamp	时间戳
     * nonce	随机数
     * echostr	随机字符串
     * @return
     */
    private String signature;
    private String timestamp;
    private String nonce;
    private String echostr;
}

Click Submit on the page
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/DreamsArchitects/article/details/108844525