阿里短信工具类和代码

158 阅读1分钟

话不多说,直接上。(底下会给代码文本)

第一步 pom依赖

image.png

第二步 写工具类

image.png image.png

@Slf4j public class AliSendSmsUtil {

private static String accessKeyId = "xxxxxxxxxx";

private static String accessKeySecret = "xxxxxxxxxx";

private static String FROM = "xxxxxxxxxx";

/**
 * 更换手机号验证码模板
 */
private static String REPLACE_MOBILE_ID = "xxxxxxxxxx";

/**
 * 汇款验证码模板
 */
private static String REMITTANCE_CODE_ID = "xxxxxxxxxx";

public static String SEND_SMS_TYPE_REPLACE_MOBILE = "发短信场景:更换手机号";
public static String SEND_SMS_TYPE_REMITTANCE = "发短信场景:汇款";


public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
    Config config = new Config();
    config.accessKeyId = accessKeyId;
    config.accessKeySecret = accessKeySecret;
    return new Client(config);
}

public static String sendSms(String type, String mobile, String smsCode) {
    try {
        Client client = AliSendSmsUtil.createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(mobile);
        sendSmsRequest.setSignName(FROM);
        if (type.equalsIgnoreCase(SEND_SMS_TYPE_REPLACE_MOBILE)) {
            sendSmsRequest.setTemplateCode(REPLACE_MOBILE_ID);
        } else {
            sendSmsRequest.setTemplateCode(REMITTANCE_CODE_ID);
        }
        sendSmsRequest.setTemplateParam("{\"code\":\"" + smsCode + "\"}");
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        if (null != sendSmsResponse && null != sendSmsResponse.getBody() && sendSmsResponse.getBody().code.equals("OK")) {
            return smsCode;
        }
    } catch (Exception e) {
        log.error("阿里发送短信错误:{}", e);
        //返回8个8 方便后续发现用户收不到短信 看日志 可以快速查到日志位置
        return "88888888";
    }
    return smsCode;
}

}