老鬼的博客 来都来啦,那就随便看看吧~
微信公众号如何对接服务器配置开发
发布于: 2021-03-27 更新于: 2021-03-27 分类于:  阅读次数: 

一:介绍

1
2
3
微信公众号后台有一个基本配置,基本配置里面有一个服务器配置,
这里要设置服务器地址(URL),令牌(Token),消息加解密密钥(EncodingAESKey),
如下图所示,我这里只是介绍一下明文模式。

1.png

二:如何配置?

1
2
3
4
5
配置之前首先要写一个接口,也就是服务器的地址供微信调用,下面
介绍一下这个接口如何编写,下面代码就是参数都是微信定义的,
我们要感觉微信传递的值进行签名校验,如果校验通过,则返回echostr
值,如果校验不通过直接返回null,其中body里面的内容就是微信推送
的消息内容。

微信官方服务器配置介绍

  • 接受微信请求的后台server接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @desc 服务器server
* @return
* @throws Exception
*/
@RequestMapping(value = "/accept")
public String accept(String signature, String timestamp, String nonce, String echostr,
HttpServletRequest request) throws Exception {
log.info("signature:" + signature);
log.info("timestamp:" + timestamp);
log.info("nonce:" + nonce);
log.info("echostr:" + echostr);
boolean flag = WxUtils.CheckSignature(signature, timestamp, nonce);
log.info("flag:" + flag);
String data = TohoursUtils.inputStream2String(request.getInputStream(), "UTF-8");
log.info("data:" + data);//微信推送消息的内容

if(flag) {
return echostr;
}else {
return null;
}
}
  • 签名验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.tohours.wechatapi.utils;

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

import com.tohours.wechatapi.constants.ApiWxConstants;

public class WxUtils {
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };

/**
* @desc token验证
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean CheckSignature(String signature, String timestamp, String nonce) {

// 1)将token、timestamp、nonce三个参数进行字典序排序
// 2)将三个参数字符串拼接成一个字符串进行sha1加密
// 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
String[] strs = new String[] { ApiWxConstants.DEVELOP_TOKEN, timestamp, nonce };

Arrays.sort(strs);

String str = strs[0] + strs[1] + strs[2];

String mysignature = sha1(str);
return mysignature.equals(signature);
}

private static String sha1(String str) {

if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private static String getFormattedText(byte[] bytes) {

int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
}
*************感谢您的阅读*************