1.注册微信公众号
进行相关信息填写:
2. 微信开发测试号申请
使用刚刚注册的微信号登录微信开发平台,找到最下面的开发配置
使用微信扫码登录,首次进入需要填写URL和Token,瞎填肯定不会配置成功的,那怎么填呢???
别急,继续往下看。
由于微信开发消息的大致流程:
所以我们需要有自己的服务器,但是为了测试方便,我们需要把本机作为服务器进行本地环境测试。因此我们就需要进行反向代理(内网穿透)
内网穿透的软件有很多,比如ngrok,natapp,花生壳等,以natapp为例进行内网穿透------》natapp官网
进入官网,下载执行程序,注册账号,进行登录:
免费的隧道暂时不能使用,需要购买隧道
购买完成之后,点击左侧我得隧道,知道刚刚购买的隧道,进行配置,然后保存配置。
找到下载的应用程序,解压。然后在cmd中找到解压的路径,然后启动。
natApp.exe --authtoken 购买的隧道authotoken
到此测试号的URL已经创建成功了。如果此时瞎写token,会提示配置失败。接下来进入token的配置
在微信开发文档中,接入概述中提到了,token的作用为了验证微信发来的消息的准确性-------------》微信开发文档--接入概述
因此我们需要写个controller来接受处理微信发来的验证请求。
创建一个springboot项目:
导入相关依赖:
<!--导入微信开发的java sdk-->
<dependency>
<groupId>com.github.liyiorg</groupId>
<artifactId>weixin-popular</artifactId>
<version>2.8.30</version>
</dependency>
修改配置文件:
#必须和natApp配置的代理的端口保持一致
server.port=8080
#微信开发相关配置
wx.appID=xxxxxxxxxx
wx.appsecret=xxxxxxxxxxxxxxxx
#token 自定义,必须和测试号配置的token保持一致
wx.token=dubboStudy
创建处理微信服务器请求验证的controller类
@Controller
@RequestMapping("/wxService")
public class WxTokenValidateController {
@Autowired
WxConfig wxConfig;
@RequestMapping("sign")
@ResponseBody
public String tokenValidate(@RequestParam Map<String,String> params, //参数列表
HttpServletRequest request,
HttpServletResponse response){
String token = wxConfig.getToken(); //获取配置文件中的token
String signature = params.get("signature"); //获取微信服务器加密后的字符串
String timestamp = params.get("timestamp"); //时间戳
String nonce = params.get("nonce"); //随机数
String echostr = params.get("echostr"); //随机字符串
if (timestamp.isEmpty()||nonce.isEmpty()){
return "";
}
/*
* 验证逻辑:
* token+timestamp+nonce三个字符串进行sort排序,
* 然后按照顺序进行拼接字符串,进行shaHex算法加密得到加密后的字符串
* 最后判断signature和加密后的密文是否相同
* 如果相同表示验证通过,返回echostr字符串
* 否则验证失败。
* */
if(signature.equals(SignatureUtil.generateEventMessageSignature(token,timestamp,nonce))){
return echostr;
}
return "";
}
}
wxconfig类:
@Configuration
@ConfigurationProperties(prefix = "wx")
public class WxConfig {
private String appID;
private String appsecret;
private String token;
/*******setter and getter*************/
}
启动程序,输入natApp的配置的域名,token为项目设置的自定义token,然后点击提交
至此测试号就申请好了!!!!