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

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

前言


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

一、验证码推送使用场景

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

1.条件测试

b.找到消息模板选项

2.配置消息模板

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


服务端环境搭建

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

<dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>2.7.0</version>
</dependency>
wx:
  app-id: *******
  app-secret: ****
server:
  port: 80
@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)

@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);
    }

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

经验分享 程序员 微信小程序 职场和发展