其實如果你之前做過對接微信公衆號其它接口,那做起來就簡單很多。如果和我一樣是第一次對接微信接口就有點難了。(看了文檔無從下手)
一、基本配置
1-1:準備一個認證的微信號,然後添加客服功能插件
1-2:配置服務器地址
如果你之前做過其它的公衆號接口對接,這一步應該是已經做好的。
接入api文檔地址: https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
這裏簡單解釋一下(具體實現在代碼裏面):
- 1、這個服務器地址是需要外網可以訪問的,但是我們開發都是本地的。所以我們需要使用一個工具映射我們的ip。(https://www.jianshu.com/p/571fdbc98d25)
- 2、然後我們提供一個接口,讓微信可以認證我們。認證操作見文檔中 第二步:驗證消息的確來自微信服務器
- 3、比如的我服務器地址是:http://f20d7f264d2d.ngrok.io/portal,其實就相當於 http://127.0.0.1:8080/portal
import org.springframework.web.bind.annotation.*;
/**
* 微信認證
*/
@RestController
@RequestMapping("/portal")
public class WxPortalController {
@GetMapping(produces = "text/plain;charset=utf-8")
public String authGet(
@RequestParam(name = "signature", required = false) String signature,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "nonce", required = false) String nonce,
@RequestParam(name = "echostr", required = false) String echostr) {
return echostr;
// return "非法請求";
}
@PostMapping(produces = "application/xml; charset=UTF-8")
public String post(@RequestBody String requestBody,
@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce, @RequestParam("openid") String openid,
@RequestParam(name = "encrypt_type", required = false) String encType,
@RequestParam(name = "msg_signature", required = false) String msgSignature) {
System.out.println(requestBody);
System.out.println(signature);
System.out.println(timestamp);
System.out.println(nonce);
System.out.println(openid);
System.out.println(encType);
System.out.println(msgSignature);
String str = " <xml> \n" +
" <ToUserName><![CDATA["+openid+"]]></ToUserName> \n" +
" <FromUserName><![CDATA[xxxxx]]></FromUserName> \n" +
" <CreateTime>1399197672</CreateTime> \n" +
" <MsgType><![CDATA[transfer_customer_service]]></MsgType> \n" +
"</xml>";
return str;
}
}
- 也就是以後微信需要給我們服務器發送消息的時候,get請求和post請求就會進入上面這兩個方法。(理解這很重要)
二、接入客服功能
最開始可能有人和我想的一樣,用戶從那裏輸入消息呢?一般都是有個菜單聯繫客服,但是微信公衆號是不需要的,用戶直接輸入就好了。
2-1:不需要api,直接操作
在公衆號後臺可以直接對客服進行增刪改和綁定操作。 至於用戶和那個客服進行對接,應該是輪詢吧,這個我也沒有嘗試過。
2-2:接入api操作(重點)
2-2-1:對客服進行增刪改查綁定操作
文檔地址:https://developers.weixin.qq.com/doc/offiaccount/Customer_Service/Customer_Service_Management.html
這個也很簡單,就是相對於的Get和Post請求,我們可以直接使用HttpClient進行操作就好了。 比如我們新增之後,我們可以到後臺客服功能進行查看我們添加的客服。
2-2-2:對消息的處理
消息先是發送到你在微信公衆號綁定的那個地址,然後你可以在這個方法裏面進行你想要的操作:
- 比如對消息進行存入數據庫
- 比如對消息進行發送到客服(消息是不直接發送給客服的,需要你這裏操作)
- 比如對消息進行指定發送給客服
2-2-2-1:如果是隨便哪個客服都可以進行消息的處理,那就使用這個
2-2-2-2:如果是要選定客服進行消息的處理,就是用這個
注:這個返回值,其實就是這個格式的字符串,在上面配置的微信地址接口裏面
比如下面這個格式: