Java uses the [NetEase Yunxin] SMS interface to send and verify verification codes to mobile phone users

Thanks to the original author, basically it can be used, but there are still some small pits (mainly the loading of jar packages), so I reprinted it and adjusted it to suit me.


Netease Yunxin address : http://dev.netease.im/


The jar package I used in this project:

fastjson-1.1.36.jar

My maven cannot download fastjson-1.1.36.jar with external address

https://www.oschina.net/news/43956/fastjson-1-1-36

httpcore-4.4.5.jar

httpcore-ab-4.4.5.jar

httpcore-nio-4.4.5.jar

httpclient-4.5.jar

commons-codec-1.9.jar

commons-logging-1.2.jar


The above is the original author's package. I mainly downloaded the following two packages and fastjson-1.1.36.jar.

Jar package download

httpcore-4.4.3.jar

  • [org.apache.http.HttpResponse]
  • [org.apache.http.NameValuePair]
  • [org.apache.http.message.BasicNameValuePair]
  • [org.apache.http.util.EntityUtils]

httpclient-4.5.1.jar

  • [org.apache.http.client.entity.UrlEncodedFormEntity]
  • [org.apache.http.client.methods.HttpPost]
  • [org.apache.http.impl.client.DefaultHttpClient]


Because of the convenience of the mobile terminal, many websites and applications on the Internet now have the function of binding with the user's mobile phone. There are many advantages to this, such as account login, password modification, online payment, etc. functional modules can be combined with the mobile phone to obtain the verification code SMS in real time to ensure the user's safe operation.


We generally divide the operation of the verification code into two parts:
1. Send the verification code to the mobile phone user.
2. Through the feedback of mobile phone users, we need to verify whether the verification code entered by the user is correct.

1.
Sending verification code
First we create: verification code generation class
package com.mobile;

import java.security.MessageDigest;

/**
 * verification code generation tool class
 * @author Administrator
 *
 */
public class CheckSumBuilder {

    //Calculate and Get checkSum
    public static String getCheckSum(String appSecret,String nonce,String curTime){
        return encode("SHA",appSecret+nonce+curTime);
    }

    private static String encode(String algorithm,String value){
        if(value==null ){
            return null;
        }

        try {
            MessageDigest messageDigest=MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes){
        int len=bytes.length;
        StringBuilder sb=new StringBuilder(len*2);
        for(int $i=0;$i<len;$i++){
            sb.append(HEX_DIGITS[(bytes[$i]>>4)&0x0f]);
            sb.append(HEX_DIGITS[bytes[$i]&0x0f]);
        }
        return sb.toString();
    }

    private static final char[] HEX_DIGITS={'0','1','2','3','4','5','6',
            '7','8','9','a','b','c','d','e','f'};

}


然后我们再封装: 短信发送工具类
package com.mobile;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * SMS sending tool class
 * @author Administrator
 *
 */
public class MobileMessageSend {
    private static final String SERVER_URL="https://api.netease.im/sms/sendcode.action"; //Request path URL for sending verification code
    private static final String APP_KEY="e8c86e26c09d*************";//The account assigned by NetEase
    Yunxin private static final String APP_SECRET="0177b8** ***";//
Key
    private static final String NONCE="123456";//Random number

    public static String sendMsg(String phone) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(SERVER_URL);

        String curTime=String.valueOf((new Date().
        String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

        //设置请求的header
        post.addHeader("AppKey",APP_KEY);
        post.addHeader("Nonce",NONCE);
        post.addHeader("CurTime",curTime);
        post.addHeader("CheckSum",checkSum);
        post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

        //设置请求参数
        List<NameValuePair> nameValuePairs =new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("mobile",phone));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

        //执行请求
        HttpResponse response=httpclient.execute(post);
        String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

        //Determine whether the transmission is successful, and return true if the transmission is successful
        String code= JSON.parseObject(responseEntity).getString("code");
        if ( code.equals("200")){
            return "success";
        }
        return "error";
    }
}


Finally, we test in the main method: Test class for sending verification code
package com.mobile;

/**
 * Send verification code
 * Netease Yunxin address: http://dev.netease.im/
 * @author Administrator
 *
 */
public class SendMsg {
    public static void main(String[] args) {
        String mobileNumber = "185******** ";//The mobile phone number to receive the verification code
        try {
            String str = MobileMessageSend.sendMsg(mobileNumber);
            if("success".equals(str)){
                System.out.println("Send successfully!");
            }else{
                System.out.println("Send failed!") ;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}


Second, we first encapsulate the verification
code: verification code verification tool class
package com.web;

import java.io.IOException ;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.mobile.CheckSumBuilder;

/**
 * 校验验证码工具类
 * @author Administrator
 *
 */
public class MobileMessageCheck {

    private static final String SERVER_URL="https://api.netease.im/sms/verifycode.action";//校验验证码的请求路径URL
    private static final String APP_KEY="e8c86e26c09da8**************";//账号
    private static final String APP_SECRET="0177b8******";//密钥
    private static final String NONCE="123456";//随机数

    public static String checkMsg(String phone,String sum) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(SERVER_URL);

        String curTime=String.valueOf((new Date().getTime()/1000L));
        String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

        //设置请求的header
        post.addHeader("AppKey",APP_KEY);
        post.addHeader("Nonce",NONCE);
        post.addHeader("CurTime",curTime);
        post.addHeader("CheckSum",checkSum);
        post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

        //设置请求参数
        List<NameValuePair> nameValuePairs =new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("mobile",phone));
        nameValuePairs.add(new BasicNameValuePair("code",sum));
       
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

        //执行请求
        HttpResponse response=httpclient.execute(post);
        String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

        //判断是否发送成功,发送成功返回true
        String code= JSON.parseObject(responseEntity).getString("code");
        if (code.equals("200")){
            return "success";
        }
        return "error";
    }
}


We test in the main method: The test class for verifying the verification code
package com.web;

/**
 * Verifying the verification code
 * @author Administrator
 *
 */
public class CheckMsg {
    public static void main (String[] args) {
        String mobileNumber = "185********";//Mobile phone number
        String code = "1071";//Verification code
        try {
            String str = MobileMessageCheck.checkMsg(mobileNumber,code) ;
            if("success".equals(str)){
                System.out.println("Verification succeeded!");
            }else{
                System.out.println("Verification failed!");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325727894&siteId=291194637