阿里云SMS短信服务的使用

短信服务是每个商家和企业都会去使用的,用户会收到106开头的号码的短信的内容,多用于用户传递验证码、系统通知等。

下面记录一下使用阿里云短信服务的经验和心得 ~ 

 以下忽略申请流程,直接接入短息服务...

1. 获取开发者的accesskeys(在阿里云访问控制台寻找)

阿里云SMS短信服务的使用_第1张图片

阿里云SMS短信服务的使用_第2张图片

以上可获取到accessKeyId && accessKeySecret

 

2. 获取短信签名&&模板

① 签名名称:可以理解为公司名称,比如短信的中的:【中国移动】

需要注意的是签名的场景要跟模板上场景对的上,不然是无法调用模板的。

阿里云SMS短信服务的使用_第3张图片

 

② 模板管理:就是短信内容,需要获取的是“ 模版CODE ”

阿里云SMS短信服务的使用_第4张图片

 

3. 发送短信

①首先引入jar包,没有的小伙伴们可以自行下载 ~

    aliyun-java-sdk-core.jar

    aliyun-java-sdk-dysmsapi.jar

link:https://download.csdn.net/download/weixin_38407595/11504104

②查找官方模板(Java)

https://helpcdn.aliyun.com/document_detail/55284.html?spm=a2c4g.11186623.4.1.5124157boF2inj

我自己修改的模板,可以参考下~

package com.platform.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * @ClassName:AliMessagesUtil
 * @Author:QQ
 * @Createtime:2019-08-18 18:88
 * @Description:TODO
 * @Version:1.0
 */
public class AliMessagesUtil {

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // 此处需要替换成开发者自己的APK(在阿里云访问控制台寻找)
    static final String accessKeyId = "去找吧";
    static final String accessKeySecret = "去找吧";
    static final String signName = "签名名称";
    static final String templateCodeA = "模板CODE";
    static final String outId = "9696";

    /**
     * Send SMS
     * 收到商品
     * @param phone
     * @param code
     * @return
     * @throws ClientException
     */
    public static SendSmsResponse sendSms(String phone, String name, String code) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();

        //必填:待发送手机号
        request.setPhoneNumbers(phone);

        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);

        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCodeA);

        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"name\":\""+name+"\",\"code\":\""+code+"\"}");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId(outId);

        //hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

    
    /**
     * Query SMS
     * @param phone
     * @param bizId
     * @return
     * @throws ClientException
     */
    public static QuerySendDetailsResponse querySendDetails(String phone,String bizId) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(phone);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询,格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常,注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    /**
     * Random number
     * @param charCount
     * @return
     */
    public static String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }

    private static int randomInt(int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }

}

 

③模拟测试发送短信

package com.orangele.test;

import java.util.Scanner;

import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.orangele.util.AliMessagesUtil;

public class TestSendMessages {
	
	public static Scanner input = new Scanner(System.in);
	
	public static void main(String[] args) throws ClientException, InterruptedException {
		/*
		  * 测试发送短信
		 */
		System.out.print("请输入手机号码:");
		String phone = input.next();
		String rand=AliMessagesUtil.getRandNum(4);
		SendSmsResponse response=AliMessagesUtil.sendSms(phone, "020201908030934","520.00");
		
		if (null!=response) {
			System.out.println("发送成功~\n您的验证码为:"+rand);
		}
		
		System.out.println("↓----------------查询响应----------------↓");
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());
        Thread.sleep(3000L);

        //明细
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = AliMessagesUtil.querySendDetails(phone,response.getBizId());
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("响应码=" + querySendDetailsResponse.getCode());
            System.out.println("响应消息=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("短信发送详述["+i+"]:");
                System.out.println("信息内容=" + smsSendDetailDTO.getContent());
                System.out.println("业务方扩展字段=" + smsSendDetailDTO.getOutId());
                System.out.println("发送手机号=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("发送日期=" + smsSendDetailDTO.getSendDate());
                System.out.println("发送状态=" + smsSendDetailDTO.getSendStatus());
                System.out.println("短信模板=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("查询短信数量=" + querySendDetailsResponse.getTotalCount());
            System.out.println("短信请求码=" + querySendDetailsResponse.getRequestId());
        }

		}	
	}

完成...

你可能感兴趣的:(Java,Tool)