最近項目中因爲某些緣由,涉及到了微信公衆號
的開發,此處簡單記錄下微信公衆號的接入。html
一、須要有一個能夠在外網能夠訪問的域名
二、本地開發,須要將內網環境穿透到外網能夠訪問。
三、須要有一個公衆號。 java
注意:
一、內網穿透
和外網域名
咱們能夠經過 natapp
來購買實現。git
此處根據本身的狀況,購買一個適合本身的隧道。
後期將會把咱們本身的本地端口,映射到一個外網能夠訪問的網址上。github
注意:
一、此處購買一個 二級域名,若是本身有 域名,能夠不用購買。web
https://natapp.cn/#download
此處須要根據本身的操做系統,下載對應的客戶端。服務器
此處的 authtoken
的值爲 咱們本身購買的隧道的值。微信
路徑:開發->基本配置
app
微信服務器地址URL
:這個能夠先記下來,下面會告知在那個地方配置咱們本身接入微信公衆號有些驗證比較麻煩,此處藉助網上的開源框架 weixin-java-mp 這個程序開發
。框架
<dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>4.0.0</version> </dependency>
@Configuration public class WxMpConfiguration { @Autowired private WxMpProperties wxMpProperties; @Bean public WxMpService wxMpService() { WxMpServiceImpl wxMpService = new WxMpServiceImpl(); wxMpService.setWxMpConfigStorage(wxMpConfigStorage()); // 設置多個微信公衆號的配置 // wxMpService.setMultiConfigStorages(); return wxMpService; } /** * 這個地方的配置是保存在本地,生產環境須要本身擴展,能夠保存在Redis中等等 * * @return WxMpConfigStorage */ public WxMpConfigStorage wxMpConfigStorage() { WxMpDefaultConfigImpl storage = new WxMpDefaultConfigImpl(); storage.setAppId(wxMpProperties.getAppId()); storage.setSecret(wxMpProperties.getAppSecret()); storage.setAesKey(wxMpProperties.getAesKey()); storage.setToken(wxMpProperties.getToken()); return storage; } }
注意
一、WxMpConfigStorage
這個類在生產環境中,若是服務是 集羣
部署的話,最好不要使用 WxMpDefaultConfigImpl
由於這個是將配置保存在 內存中。能夠考慮使用 WxMpRedissonConfigImpl
這個類。
二、WxMpConfigStorage
中的配置,和上方的服務器配置保持一致。spa
@Component @RestController @Slf4j public class MpEntryController { @Autowired private WxMpService wxMpService; /** * 微信接入 * * @param signature 簽名 * @param timestamp 時間戳 * @param nonce 隨機數 * @param echoStr 隨機字符串 * @return 接入成功返回 echoStr 的值,不然隨便返回 */ @GetMapping("/mp/entry") public String entry(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce, @RequestParam("echostr") String echoStr) { log.info("微信公衆號/服務號接入傳遞的參數 signature:[{}],timestamp:[{}],nonce:[{}],echostr:[{}]", signature, timestamp, nonce, echoStr); if (StringUtils.isAnyBlank(signature, timestamp, nonce, echoStr)) { log.error("接收到微信認證信息,參數非法,存在爲空的參數"); return "error"; } boolean result = wxMpService.checkSignature(timestamp, nonce, signature); log.info("微信公衆號/服務號接入成功?[{}]", result); return result ? echoStr : "error"; } }
注意
一、/mp/entry
這個爲咱們本身的接入路徑,和上方圖中保存一致。
一、啓動咱們的web工程
二、在微信配置頁面,點擊提交
。
三、驗證經過,說明接入成功。
微信服務器地址URL 就是 /mp/entry
一、微信接入