最近项目中因为某些缘由,涉及到了微信公众号
的开发,此处简单记录下微信公众号的接入。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
一、微信接入