最近開始玩公衆號開發了,首先得註冊一個公衆號
公衆號後臺網址:https://mp.weixin.qq.com
進入後可以看到公衆號分爲兩大類(服務號和訂閱號),服務號個人註冊不太到,個人一般使用訂閱號。
訂閱號也分認證和未認證。未認證的情況下,個人的接口調用有限制。
所以這裏我們可以申請微信公衆平臺接口測試帳號,裏面啥權限都有了。
申請地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
進入以後如圖:
授權登錄以後,是這樣的。
這裏要填兩個值(url和token),點擊“提交”按鈕的時候,微信會向我們的url發起一個請求。
我在這裏隨便跑了個項目,寫了個controller,啓動。訪問地址localhost:8080/wx/get(測試走的通)
接下來我們可以把訪問地址填在公衆號後臺的url裏了。這裏插一句嘴,我們一般開發的時候都是localhost:8080啥啥的,微信這邊訪問不到。(你可以試試在上面填個localhost:8080看人微信理你不。當然你要是有云平臺那另說…)
我這個窮孩子的話就選一個免費的內網穿透工具ngrok。差不多就是把你的本地網址能讓外界訪問到。
以上通過ngrok就能把我的localhost:8080變成前面那一串,在把他丟在微信測試平臺後臺的url那一欄,在隨便寫個token。
我是這麼填的。
點擊提交,這時候,微信就向你的服務器上發起一個請求,並帶過來四個參數。每次微信測試平臺點“提交”都來一次請求哈!!
這裏我在後臺接收了這四個參數,並打印出來代表流程走通了。
@GetMapping("/get")
private String get(String signature, String timestamp, String nonce, String echostr) {
System.out.println("signature="+signature);
System.out.println("timestamp="+timestamp);
System.out.println("nonce="+nonce);
System.out.println("echostr="+echostr);
return “”;
}
接下來步驟按着微信官方文檔來走。
開發者通過檢驗signature對請求進行校驗。若確認此次GET請求來自微信服務器,請原樣返回echostr參數內容,則接入生效,成爲開發者成功,否則接入失敗。加密/校驗流程如下:
1)將token、timestamp、nonce三個參數進行字典序排序
2)將三個參數字符串拼接成一個字符串進行sha1加密
3)開發者獲得加密後的字符串可與signature對比,標識該請求來源於微信。
//Controller完整代碼
@GetMapping("/get")
private String get(String signature, String timestamp, String nonce, String echostr) {
System.out.println("signature="+signature);
System.out.println("timestamp="+timestamp);
System.out.println("nonce="+nonce);
System.out.println("echostr="+echostr);
boolean isSuccess = weChatService.check(signature, timestamp, nonce);
if (isSuccess) {
System.out.println("成功");
}else {
System.out.println("失敗");
}
//若確認此次GET請求來自微信服務器,請原樣返回echostr參數內容
return echostr;
}
//具體校驗
@Service
public class WeChatServiceImpl implements WeChatService {
private static final String TOKEN = "token";
// 1)將token、timestamp、nonce三個參數進行字典序排序 2)將三個參數字符串拼接成一個字符串進行sha1加密
// 3)開發者獲得加密後的字符串可與signature對比,標識該請求來源於微信
@Override
public boolean check(String signature, String timestamp, String nonce) {
boolean isSuccess = true;
// 1)將token、timestamp、nonce三個參數進行字典序排序
String [] arr = new String [] {TOKEN, timestamp, nonce};
Arrays.sort(arr);
// 2)將三個參數字符串拼接成一個字符串進行sha1加密
String mdResult = getMdAh1Result(arr[0] + arr[1] + arr[2]);
// 3)開發者獲得加密後的字符串可與signature對比,標識該請求來源於微信
return signature.endsWith(mdResult);
}
//加密
private String getMdAh1Result(String str) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
}
後臺校驗寫完以後再回到公衆號點提交。校驗完成以後就是配置成功了。