According to this article can achieve a simple wechat public number verification code push function.

I. Application scenarios of verification code push

Traditional captchas can prevent malicious attacks and crawlers. But captchas, no matter how complex they are, can be cracked by intelligent algorithms. Some people may think of mobile verification code, mobile verification code can indeed solve the above problems, but if your system users have overseas users, this function is limited, so using wechat public account to push verification code is a very good choice.

2. Build the message template in the test number

  1. The message template must be used to realize the verification code push, but the subscription number must be authenticated to use the message template, so the test number is selected here, and the application process of the test number is as follows:

A. Enter your official account page and pull it to the bottom B. Find the message template option2. Configure the message template note: Variables must be wrapped with {{}} and the variable name must be appended. DATA otherwise gets no value. Example: {{code. The DATA}}3. So far, the wechat public platform has been basically set up. The following information is what we need on the server side. a. appID wx5fc55e59461**** b. appsecret a8ae4637b095*df c. Template ID jerVx-* * * * * *

Third, the server environment construction

On the server side, we use weixin-Java-MP framework, which encapsulates payment, authentication and many other methods.

< the dependency > < groupId > com. Making. Binarywang < / groupId > < artifactId > weixin - Java - mp < / artifactId > < version > 2.7.0 < / version > </dependency>Copy the code
  1. Yml configures app-id and app-secret to authenticate this test number, corresponding to the relevant classes for establishing wechat configuration.
wx:
  app-id: *******
  app-secret: ****
server:
  port: 80
Copy the code

1.1 wechat Account Configuration Class WxAccountConfig.class

@Component@ConfigurationProperties (" wX ") public Class WxAccountConfig {// Public ID private String appId; // public id 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; }}Copy the code

1.2 wechat configuration class, which sets appID and other functions to encapsulated WxMpService and 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(); // To set appID and AppSecret, we need to set two variables in the configuration file so that they can be used globally. Then we need to set a WexAccountConfig class to inject these two parameters. So when using can directly call these two classes wxMpConfigStorage. SetAppId (wxAccountConfig. GetAppId ()); wxMpConfigStorage.setSecret(wxAccountConfig.getAppSecret()); wxMpConfigStorage.setAccessToken("wangyu"); return wxMpConfigStorage; }}Copy the code
  1. Create a Service interface and implementation for push messages. Only the implementation is posted here.
private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private WxMpService wxMpService; @Override public void returnVerficationCode(String receiveId) {// Object encapsulated by the template message WxMpTemplateMessage WxMpTemplateMessage = new WxMpTemplateMessage(); / / message template ID wxMpTemplateMessage. SetTemplateId (WxConfigConstant. VERFICATION_CODE_TEMPLATE_ID); wxMpTemplateMessage.setToUser(receiveId); wxMpTemplateMessage.setData(wrapperTemplateData()); try { wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage); }catch (WxErrorException errorException){logger.error ); }} /** * wrapperTemplateData(){private List<WxMpTemplateData> wrapperTemplateData(){// Get 4 for 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; }Copy the code

WxMpTemplateData(String Name, String Value, String color) 3. Create Controller of push message,userId is openId of concerned public number.

@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; }Copy the code
  1. Paste the utility class that generates the captcha
public class VerficationCodeUtils { private static final String SYMBOLS = "0123456789"; Private static final Random Random = new SecureRandom(); Public static String getVerficationCode(int length) {public static String getVerficationCode(int length) {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); }}Copy the code

4. Verification code is pushed to the public account

We open the page of our test number again. If we use the environment built by the local machine, we can use the Intranet penetration tool. I use NatApp here, which has a tutorial, which is very convenient. URL just in Controller can access the address remember add userId, Token to and wxMpConfigStorage setAccessToken (), click submit, and now you received the authentication code number of public.