对接阿里云sms短信服务发送验证码

1.购买阿里云短信服务

 

2.申请签名

3.申请短信模板

4.获取密钥

  

 

5.maven依赖

<dependency>

<groupId>com.aliyun</groupId>

<artifactId>dysmsapi20170525</artifactId>

<version>2.0.9</version>

</dependency>

6.发送短信工具类

package com.thk.utils;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.thk.constant.Constant;
import org.springframework.stereotype.Component;

@Component
public class Sample {

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public  static  com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(Constant.ACCESSKEYID)
                // 您的AccessKey Secret
                .setAccessKeySecret(Constant.ACCESSKEYSECRET);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public  void sendSms(String code)  {
        try {
            com.aliyun.dysmsapi20170525.Client client = Sample.createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                     //签名
                    .setSignName("申请的签名")
                     //模板
                    .setTemplateCode("申请的模板")
                    .setPhoneNumbers("需要发送的手机号码")
                    //验证码
                    .setTemplateParam("{code:+" + code + "}");
            RuntimeOptions runtime = new RuntimeOptions();
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println("发送成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送失败!!!");
        }
    }


}

7.测试

 


版权声明:本文为weixin_58696998原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。