微信公眾號開發(fā)流程
1.填寫服務(wù)器配置
2.驗證服務(wù)器地址的有效性
3.依據(jù)接口文檔實現(xiàn)業(yè)務(wù)邏輯
1.接口配置
URL為內(nèi)網(wǎng)穿透映射的URL
Token則是你隨意定即可
軟件環(huán)境:idea+springboot

image.png
2.驗證消息的確來自微信服務(wù)器
開發(fā)者提交信息后,微信服務(wù)器將發(fā)送GET請求到填寫的服務(wù)器地址URL上,GET請求攜帶參數(shù)如下表所示:
signature 微信加密簽名,signature結(jié)合了開發(fā)者填寫的token參數(shù)和請求中的timestamp參數(shù)、nonce參數(shù)。
timestamp 時間戳
nonce 隨機數(shù)
echostr 隨機字符串
開發(fā)者通過檢驗signature對請求進行校驗(下面有校驗方式)。若確認(rèn)此次GET請求來自微信服務(wù)器,請原樣返回echostr參數(shù)內(nèi)容,則接入生效,成為開發(fā)者成功,否則接入失敗。加密/校驗流程如下:
1)將token、timestamp、nonce三個參數(shù)進行字典序排序 2)將三個參數(shù)字符串拼接成一個字符串進行sha1加密 3)開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識該請求來源于微信
對比方法如下:
public boolean check(String signature, String timestamp, String nonce, String token) {
//1)將token、timestamp、nonce三個參數(shù)進行字典序排序
String[] str = new String[]{token, timestamp, nonce};
Arrays.sort(str);
//2)將三個參數(shù)字符串拼接成一個字符串進行sha1加密
String str2 = str[0] + str[1] + str[2];
String sha1Str = addSha1(str2);
//3)開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識該請求來源于微信
sha1Str.equals(signature);
return true;
}
2.contoller方法
@RestController
@RequestMapping("wx")
public class DemoWxController {
@Value("${demo.token}")
private String token;
@Resource
private DemoWxService demoWxService;
@GetMapping("test")
public void demoTest(HttpServletRequest request, HttpServletResponse response) {
//第二步:驗證消息的確來自微信服務(wù)器
//開發(fā)者提交信息后,微信服務(wù)器將發(fā)送GET請求到填寫的服務(wù)器地址URL上,GET請求攜帶參數(shù)如下表所示:
//signature 微信加密簽名,signature結(jié)合了開發(fā)者填寫的token參數(shù)和請求中的timestamp參數(shù)、nonce參數(shù)。
//timestamp 時間戳
//nonce 隨機數(shù)
//echostr 隨機字符串
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
System.out.println(signature);
System.out.println(timestamp);
System.out.println(nonce);
System.out.println(echostr);
//開發(fā)者通過檢驗signature對請求進行校驗(下面有校驗方式)。若確認(rèn)此次GET請求來自微信服務(wù)器,請原樣返回echostr參數(shù)內(nèi)容,則接入生效,成為開發(fā)者成功,否則接入失敗。加密/校驗流程如下:
try {
if (demoWxService.check(signature, timestamp, nonce, token)) {
System.out.println("微信接入成功");
PrintWriter writer = null;
writer = response.getWriter();
//原樣返回echostr參數(shù)內(nèi)容
writer.print(echostr);
writer.flush();
writer.close();
} else {
System.out.println("微信接入失敗");
}
} catch (IOException e) {
e.printStackTrace();
}
}
3.啟動項目

image.png
4.點擊接口配置信息提交,這里微信會和服務(wù)器進行對接,匹配成功則提交成功,否則失敗

image.png