Micro-channel public platform developer to configure

table of Contents

The first part to enable developers to configure

(1) Log in micro-channel public platform

(2) configure the IP whitelist

(3) enable developers to configure

(4) the specific code calling part

The second part of the event to receive push

(1) Interface

(2) business logic classes 

(3) MessageUtil

(4) print the results:

to sum up:


Preface:

Preparatory work today is to introduce micro-channel public platform receives event push part, can be seen from the official documents, micro-channel public platform provides event push, users concerned about the public number unfollow numbers can push content to developers in the micro-letter url public platform configurations, developers can hold this information for further logic judgment.

The first part to enable developers to configure

step:

(1) Log in micro-channel public platform

Need to log micro letter public platform account, become a micro-channel public platform for developers, click the next icon Note where developers can access the configuration page.

 

(2) configure the IP whitelist

When multiple IP direct line feed, this needs to be configured, very important , as shown below, I will have my own ip on the computer configuration go up.

 

(3) enable developers to configure

Note that Token which can be by the developer to customize, just make sure the code below Token Token and I can be consistent.

(4) the specific code calling part

  • 4.1 interface calls the method needs to get requests.
package com.bos.controller.wechat;

import com.bos.qiWechat.WXBizMsgCrypt;
import com.bos.service.WeiService;
import com.bos.util.WeiXinParamesUtil;
import com.bos.wechat.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author tanghh
 * @Date 2020/4/3 10:12
 */
@RestController
@RequestMapping(value = "/wechat")
public class WechatDeveloperController {
 

    /**
     * 确认请求来自微信服务器
     *
     * @param signature 微信加密签
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @RequestMapping(method = {RequestMethod.GET})
    public void doGet(
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestParam(value = "echostr", required = false) String echostr,
            HttpServletResponse response) throws Exception {

        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            response.getOutputStream().println(echostr);
            System.out.println("微信验证成功");
        }
    }


}
  • 4.2 Sign Util
package com.bos.wechat;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
 * @Author: tanghh
 *
 */
public class SignUtil {
    private static String token = "WinXinEBO";

    /**
     * 校验签名
     *
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return 布尔值
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String checktext = null;
        if (null != signature) {
            //对ToKen,timestamp,nonce 按字典排序
            String[] paramArr = new String[]{token, timestamp, nonce};
            Arrays.sort(paramArr);
            //将排序后的结果拼成一个字符串
            String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                //对接后的字符串进行sha1加密
                byte[] digest = md.digest(content.toString().getBytes());
                checktext = byteToStr(digest);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        //将加密后的字符串与signature进行对比
        return checktext != null ? checktext.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转化我16进制字符串
     *
     * @param byteArrays 字符数组
     * @return 字符串
     */
    private static String byteToStr(byte[] byteArrays) {
        String str = "";
        for (int i = 0; i < byteArrays.length; i++) {
            str += byteToHexStr(byteArrays[i]);
        }
        return str;
    }

    /**
     * 将字节转化为十六进制字符串
     *
     * @param myByte 字节
     * @return 字符串
     */
    private static String byteToHexStr(byte myByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tampArr = new char[2];
        tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
        tampArr[1] = Digit[myByte & 0X0F];
        String str = new String(tampArr);
        return str;
    }


}

These operations above can open developer configuration. ok

The second part of the event to receive push

Developers have configured the above configuration later, you can do a push receive event! I write in the WechatDeveloperController

Dopost method is used in the micro-channel to receive messages sent by the server

(1) Interface

package com.bos.controller.wechat;

import com.bos.qiWechat.WXBizMsgCrypt;
import com.bos.service.WeiService;
import com.bos.util.WeiXinParamesUtil;
import com.bos.wechat.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author tanghh
 * @Date 2020/4/3 10:12
 */
@RestController
@RequestMapping(value = "/wechat")
public class WechatDeveloperController {
    @Autowired
    private WeiService weiService;

    /**
     * 确认请求来自微信服务器
     *
     * @param signature 微信加密签
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @RequestMapping(method = {RequestMethod.GET})
    public void doGet(
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestParam(value = "echostr", required = false) String echostr,
            HttpServletResponse response) throws Exception {

        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            response.getOutputStream().println(echostr);
            System.out.println("微信验证成功");
        }
    }

    /**
     * 处理微信服务器发来的消息
     *
     * @return     
     */
    @RequestMapping(method = {RequestMethod.POST})
    public void dopost(HttpServletRequest request) {
        // 调用核心业务类接收消息、处理消息
        weiService.wechatReceiveEventChange(request);
    }

}

(2) business logic classes 

Note that: When I configured a developer configuration selected above is expressly mode, so I did not at the time of encryption and decryption processing messages sent from the micro-channel server, but directly to the xml converted into map.

  /**
     * 微信开放平台--接收事件推送
     * 文档地址:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html
     * @return
     */
    @Override
    public ResultData wechatReceiveEventChange(HttpServletRequest request) {
        ResultData resultData = new ResultData();
        try{
            //目前文档上记录的总共有6种事件类型
//            a.(扫描带参数二维码事件)
//            如果用户还未关注公众号,则用户可以关注公众号,关注后微信会将带场景值关注事件推送给开发者。
//            如果用户已经关注公众号,则微信会将带场景值扫描事件推送给开发者。

            //1.解析微信发来的请求,解析xml字符串
            Map<String, String> requestMap = MessageUtil.xmlToMap(request);
            //获取返回的数据
            String event = requestMap.get("Event");
            String eventKey = requestMap.get("EventKey");
            String ticket = requestMap.get("Ticket");
           
        }catch (Exception e){
            resultData.setResult("false");
            resultData.setMessage("微信接收事件推送失败");
            logger.error("微信接收事件推送失败",e);
        }
        return resultData;
    }

(3) MessageUtil

   /**
     * 将xml转换成map集合
     * @param request
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        Map<String, String> map = new HashMap<String, String>();
        //使用dom4j解析xml
        SAXReader reader = new SAXReader();
        //从request中获取输入流
        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);
        //获取根元素
        Element root = doc.getRootElement();
        //获取所有的节点
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
            System.out.println(e.getName() + "----->" + e.getText());
        }
        ins.close();   //关流
        return map;
    }

(4) print the results:

to sum up:

Above is the micro-channel public platform for developers to configure and receive event push, use the process if you have any questions, comments welcome comments section, if that is good enough for writing small, you can give the point of a small series like Oh!

Digression:

I started also on the micro-channel public platform and WeChat open platform concept vague, because both those who have a lot of duplicate locations, including corporate micro-channel and micro-letters, like, when I was doing business micro-channel scan code to log and found it with the micro-letter scan codes to sign similar logic, but micro-channel sweep step login verification code will be some more, like when we have a micro-channel public platform development needs, we must first become their developer, in this context, service number than the subscription number the more features, but if you want to use some of the advanced interface, such as micro-channel scan code login, you need to register WeChat open platform account.

While WeChat open platform enables scan function code log, but a specific event or to push through a micro-channel public platform.

For example: Our system generates a two-dimensional code, users use mobile phones scan code, micro letter backstage to return information to developers and users concerned about the public number, take off the public number is through micro-channel public platform event push sent to achieve, developers need to configure parameters in the micro-channel public platform background, this point of view there were two common areas.

 Quoted from: https://www.zhihu.com/question/21074751

Micro-channel public platform to the editor, WeChat open platform for technology.

Micro-channel public platform to do?

  • Writing articles hair articles
  • And chat with fans
  • Configuration Menu
  • Open all kinds of public authority number (own number only public)
  • Enabling developer mode, develop their own public number
  • Advertising
  • View data

 

WeChat open platform can do?

  • APP want to use micro letter Login / Share circle of friends, etc.
  • PC would like to use micro-site sign-on letter
  • Registration number of public third-party platforms (all public service numbers)
  • Sign up third-party platform applets (small programs provided template)
  • No binding public or applets, to form UnionID

 

Published 73 original articles · won praise 59 · views 30000 +

Guess you like

Origin blog.csdn.net/tangthh123/article/details/105288990