阿里云短信发送

阿里云短信

发送短信验证码是现在日常生活中很常见的事务,但相信很多人都只是接受过验证码,并不知道验证码的生成过程,也不知道如何自己创建一个验证码。会简单介绍如何通过阿里云来创建一个验证码短信。

一、首先打开阿里云官网

官网:https://www.aliyun.com/
在这里插入图片描述

二、开通阿里云短信服务

在这里插入图片描述
开通后五个学习任务,自行完成,可随意填写
在这里插入图片描述

三、完成学习后,获取AccessKey

鼠标点击右上角的头像
在这里插入图片描述
点击进去后,直接创建key,记录好自己key,后面需要用到

四、简单入门

点击左边导航栏,选择快速学习和测试,如下选择
在这里插入图片描述
点击调用之后可以看到如下

在这里插入图片描述

点击SDK实例
在这里插入图片描述
可以自行选择需要的语言。
点击右上角SDK信息,里面有需要的依赖坐标。
在这里插入图片描述
给自己的项目导入坐标后,编写代码
1.首先创建一个AliYunConfig类

package com.kk.user.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AliYunSmsConfig {

    @Value("${aliyun.accessKey.id}")
    private String accessKeyId;
    @Value("${aliyun.accessKey.secret}")
    private String accessKeySecret;
    @Value("${aliyun.dysms.endpoint}")
    private String endpoint;

    /**
     * 使用AK&SK初始化账号Client
     */
    @Bean
    public com.aliyun.dysmsapi20170525.Client smsClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填,您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = endpoint;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}

2.再编写业务实现

package com.kk.user.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kk.redis.utils.RedisCache;
import com.kk.user.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.tools.jar.CommandLine;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Value("${aliyun.dysms.templateCode}")
    private String templateCode;

    @Value("${aliyun.dysms.sign}")
    private String sign;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private Client smsClient;

    @Override
    public void registerSmsSend(String phone) {
        String code = this.generateVerifyCode("MATH", 4);
        try {
            this.send(phone,code);
        } catch (RuntimeException re){
            throw new RuntimeException(re);
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisCache.setCacheObject("USERS:REGISTER:VERIFY_CODE:"+phone, code, 30L, TimeUnit.MINUTES);
    }

    private void send(String phone,String code) throws Exception{
       com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(sign)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = smsClient.sendSmsWithOptions(sendSmsRequest, runtime);
        SendSmsResponseBody body = sendSmsResponse.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        String resJson = objectMapper.writeValueAsString(body);
        log.info("[短信服务] 阿里云发送短信相应结果:",resJson);
        if(!"ok".equalsIgnoreCase(body.code)){
            throw new RuntimeException(body.message);
        }
    }

    private String generateVerifyCode(String type, int len){
        StringBuffer code = new StringBuffer();
        if("MATH".equalsIgnoreCase(type)){
            Random random = new Random();
            for (int i = 0; i < len; i++) {
                code.append(random.nextInt(10));
            }
        } else {
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            code = new StringBuffer(uuid.substring(0, len));
            log.info("[验证码] 生成验证码 ====》 type={}, len={}, code={}",type,len,code);
        }
        return code.toString();
    }
}

以上代码都是根据阿里云自己提供的实例修改
一下为阿里云实例

// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填,您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用,仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html
        com.aliyun.dysmsapi20170525.Client client = Sample.createClient(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers("13558435832")
                .setTemplateParam("{\"code\":\"1234\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }
}

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KYGALYX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值