微信公众号之验证码推送(spring-boot+测试号)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

根据此文可以实现简单的微信公众号验证码推送功能。


提示:以下是本篇文章正文内容,下面案例可供参考

一、验证码推送使用场景

传统的验证码可以防止恶意攻击、以及防止网络爬虫。但是无论验证码设计的有多复杂,也可以通过智能算法破解。也许有人会想到手机验证码,手机验证码的确可以解决上述问题,但是如果你的系统用户存在海外用户,此项功能就被限制,所以使用微信公众号推送验证码是个非常不错的选择。

二、测试号中消息模板的搭建

1.条件测试

想要实现验证码推送必须使用消息模板,但是订阅号想要使用消息模板必须要认证,所以这里选择了测试号,测试号申请过程如下:
a.进入自己的公众号页面拉到最下面

在这里插入图片描述

在这里插入图片描述

b.找到消息模板选项

在这里插入图片描述

2.配置消息模板

注:其中变量必须用{{}}包裹起来、变量名后必须加.DATA否则得不到值。例:{{code.DATA}}

在这里插入图片描述
至此微信公众平台基本已经搭建好了,以下信息是我们在服务端需要用到的。
a. appID wx5fc55e59461****
b. appsecret a8ae4637b095df
c. 模板id jerVx-
*******


服务端环境搭建

服务端我们使用weixin-java-mp框架,此框架封装了支付、认证等众多方法。

<dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>2.7.0</version>
</dependency>

1.在application.yml配置app-id和app-secret以认证此测试号,相对应的建立微信配置的相关的类。

wx:
  app-id: *******
  app-secret: ****
server:
  port: 80

1.1 微信账号配置类WxAccountConfig.class

@Component
@ConfigurationProperties("wx")
public class WxAccountConfig {
    // 公众号ID
    private String appId;
    // 公众号secret
    private String appSecret;

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getAppSecret() {
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }

}

1.2 微信配置类,此类作用将appid等设置到封装的WxMpService 和 WxMpConfigStorage中。

@Configuration
public class WxConfig {

    @Autowired
    private WxAccountConfig wxAccountConfig;

    @Bean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        // 在这里我们要设置appid 和 appsecret 需要在配置文件里面设置两个变量,这样全局都可以用
        // 然后设置一个WexAccountConfig类,来注入这两个参数,这样在使用的时候就可以直接调用这两个类
        wxMpConfigStorage.setAppId(wxAccountConfig.getAppId());
        wxMpConfigStorage.setSecret(wxAccountConfig.getAppSecret());
        wxMpConfigStorage.setAccessToken("wangyu");
        return wxMpConfigStorage;
    }

}

2.新建推送消息的Service接口和实现,这里只贴出实现。

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxMpService wxMpService;
    
    @Override
    public void returnVerficationCode(String receiveId) {
         //模板消息封装的对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //消息模板ID
        wxMpTemplateMessage.setTemplateId(WxConfigConstant.VERFICATION_CODE_TEMPLATE_ID);
        wxMpTemplateMessage.setToUser(receiveId);
        wxMpTemplateMessage.setData(wrapperTemplateData());
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        }catch (WxErrorException errorException){
            logger.error("推送出现错误!" );
        }
    }
    
    /**
     *  得到验证码封装数据
     * @return
     */
    private List<WxMpTemplateData> wrapperTemplateData(){
        //得到4为验证码
        String code = VerficationCodeUtils.getVerficationCode(4);
        List<WxMpTemplateData> wxMpTemplateData = new ArrayList<>();
        wxMpTemplateData.add(new WxMpTemplateData("code",code));
        wxMpTemplateData.add(new WxMpTemplateData("validity",WxConfigConstant.VERFICATION_CODE_VALIDITY_TIME));
        return wxMpTemplateData;
    }

注:如想设置字体颜色,则需使用此构造方法WxMpTemplateData(String name, String value, String color)

3.新建推送消息的Controller,userId为关注公众号的openId。

        @ResponseBody
    @RequestMapping(value = "/sendVertficationCode", produces = { "application/json;charset=utf-8" })
    public String sendVertficationCode(HttpServletRequest request, @RequestParam(required = true) String echostr,
            @RequestParam String userId) {
//      userId = o3FqD1sJQdv0oQz_dEPvbgk3AFbE;
        pushMessageService.returnVerficationCode(userId);
        return echostr;
    }
    

贴上生成验证码的工具类


public class VerficationCodeUtils {
    
    private static final String SYMBOLS = "0123456789"; // 数字
    private static final Random RANDOM = new SecureRandom();
    
    /**
     *  生成指定位数的数字验证码
     * @return
     */
    public static String getVerficationCode(int length) {
        
        // 如果需要4位,那 new char[4] 即可,其他位数同理可得
        char[] nonceChars = new char[length];
        
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
    

四、实现验证码推送至公众号

我们再次打开我们测试号页面,如使用的本机搭建的环境,可以使用内网穿透工具,我这里使用的是natapp,里面有教程,非常方便。URL填写刚才Controller中可以访问的地址记得加上userId,Token要和wxMpConfigStorage.setAccessToken()一致,点击提交,现在你的公众号就收到验证码了。

image.png

本文来源网络, 只是记录学习用,如有侵权,可联系删除

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要集成微信公众号的消息推送功能,可以使用Spring Boot和WeChat SDK。以下是一些步骤: 1. 在微信公众平台上创建一个公众号,并获得AppID和AppSecret。 2. 在Spring Boot项目中添加WeChat SDK依赖项。 3. 创建一个Controller类来处理微信服务器发送过来的请求,比如验证URL有效性和处理用户消息。 4. 配置服务器URL和Token,并在微信公众平台上进行验证。 5. 使用SDK提供的方法实现消息的回复和推送。 以下是一个简单的代码示例: ```java @RestController @RequestMapping("/wechat") public class WeChatController { @Autowired private WxMpService wxMpService; @GetMapping(produces = "text/plain;charset=utf-8") public String validate(@RequestParam(name = "signature") String signature, @RequestParam(name = "timestamp") String timestamp, @RequestParam(name = "nonce") String nonce, @RequestParam(name = "echostr") String echostr) { if (wxMpService.checkSignature(timestamp, nonce, signature)) { return echostr; } return "error"; } @PostMapping(produces = "application/xml; charset=UTF-8") public String handleMessage(@RequestBody String requestBody, @RequestParam(name = "signature") String signature, @RequestParam(name = "timestamp") String timestamp, @RequestParam(name = "nonce") String nonce, @RequestParam(name = "openid") String openid) { // 处理用户发送的消息 WxMpXmlMessage wxMessage; try { wxMessage = WxMpXmlMessage.fromXml(requestBody); } catch (Exception e) { return "error"; } // 构造回复消息 WxMpXmlOutMessage outMessage = WxMpXmlOutMessage.TEXT() .content("你好,欢迎关注我的公众号!") .fromUser(wxMessage.getToUser()) .toUser(wxMessage.getFromUser()) .build(); return outMessage.toXml(); } } ``` 在上面的代码中,我们首先验证了微信服务器发送过来的请求是否有效。如果有效,我们返回echostr作为响应。接下来,我们处理用户发送的消息,并构造一个回复消息。最后,我们将回复消息作为响应返回给微信服务器。 请注意,我们使用了WxMpService类提供的方法来验证签名、解析消息和构造回复消息。要使用这个类,我们需要在Spring Boot项目的配置文件中添加以下内容: ``` # WeChat SDK wx.mp.appId=<your app ID> wx.mp.secret=<your app secret> wx.mp.token=<your token> wx.mp.aesKey=<your AES key> ``` 在上面的代码中,我们使用了WxMpXmlOutMessage.TEXT()方法来构造文本消息的回复。如果你需要回复其他类型的消息,比如图文消息或音频消息,请查看WeChat SDK的文档。 最后,我们需要在微信公众平台上配置服务器URL和Token。可以在公众号的基本配置页面中找到这些设置。在配置完成后,我们可以向公众号发送消息,然后观察是否收到了回复。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值