SpringBoot整合阿里云短信驗證服務的使用示例

來源: CSDN
作者:BLUcoding
時間:2021-02-23
17576
添加 RAM 用戶并賦予權限:AliyunDysmsFullAccess(管理短信服務(SMS)的權限),添加短信模板并等待審核通過,記錄下模板CODE:SMS_205403229。

SpringBoot整合阿里云短信驗證服務的使用示例

1.添加 RAM 用戶并賦予權限:AliyunDysmsFullAccess(管理短信服務(SMS)的權限)

2.添加短信模板并等待審核通過,記錄下模板CODE:SMS_205403229

ia_500000006.png

3. 添加簽名,適用場景選擇驗證碼,等待審核通過,記錄下簽名名稱:BLU的java自學網(wǎng)站

4.SpringBoot項目導入依賴:

<dependency>

    <groupId>com.aliyun</groupId>

    <artifactId>aliyun-java-sdk-core</artifactId>

    <version>4.5.3</version>

</dependency>

<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>fastjson</artifactId>

    <version>1.2.62</version>

</dependency>

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

測試類:

@Test

void contextLoads() {

    //連接阿里云

    DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的AccessKey ID", "你的AccessKey Secret");

    IAcsClient client = new DefaultAcsClient(profile);

    //構建請求

    CommonRequest request = new CommonRequest();

    //下面的信息不要改

    request.setSysMethod(MethodType.POST);

    request.setSysDomain("dysmsapi.aliyuncs.com");

    request.setSysVersion("2017-05-25");

    request.setSysAction("SendSms");

    //自定義的參數(shù)(手機號、簽名和模版CODE)

    request.putQueryParameter("PhoneNumbers", "測試的手機號碼");

    request.putQueryParameter("SignName", "你的簽名名稱");

    request.putQueryParameter("TemplateCode", "你的模版CODE");

    //構建一個短信驗證碼

    HashMap<String, Object> map = new HashMap<>();

    map.put("code", 2333);

    request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

    //嘗試發(fā)送

    try {

        CommonResponse response = client.getCommonResponse(request);

        System.out.println(response.getData());

    } catch (ServerException e) {

        e.printStackTrace();

    } catch (ClientException e) {

        e.printStackTrace();

    }

}

ia_500000007.png

配置文件:

server.port=9090

spring.redis.host=127.0.0.1

spring.redis.port=6379

Service接口:

package com.blu.service;

import java.util.Map;

public interface SendSms {

public boolean send(String phoneNum,String trmplateCode,Map<String,Object> code);

}

Service實現(xiàn)類:

package com.blu.service.Impl;

import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import com.aliyuncs.CommonRequest;

import com.aliyuncs.CommonResponse;

import com.aliyuncs.DefaultAcsClient;

import com.aliyuncs.IAcsClient;

import com.aliyuncs.exceptions.ClientException;

import com.aliyuncs.exceptions.ServerException;

import com.aliyuncs.http.MethodType;

import com.aliyuncs.profile.DefaultProfile;

import com.blu.service.SendSms;

@Service

public class SendSmsImpl implements SendSms {

@Override

public boolean send(String phoneNum, String trmplateCode, Map<String, Object> code) {

// 連接阿里云

DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的AccessKey ID",

"你的AccessKey Secret");

IAcsClient client = new DefaultAcsClient(profile);

// 構建請求

CommonRequest request = new CommonRequest();

// 下面的信息不要改

request.setSysMethod(MethodType.POST);

request.setSysDomain("dysmsapi.aliyuncs.com");

request.setSysVersion("2017-05-25");

request.setSysAction("SendSms");

// 自定義的參數(shù)(手機號,驗證碼,簽名,模板)

request.putQueryParameter("PhoneNumbers", phoneNum);

request.putQueryParameter("SignName", "BLU的java自學網(wǎng)站");

request.putQueryParameter("TemplateCode", trmplateCode);

request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));

try {

CommonResponse response = client.getCommonResponse(request);

System.out.println(response.getData());

//返回是否成功

return response.getHttpResponse().isSuccess();

} catch (ServerException e) {

e.printStackTrace();

} catch (ClientException e) {

e.printStackTrace();

}

return false;

}

}

Controller接口:

package com.blu.controller;

import java.util.HashMap;

import java.util.UUID;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.utils.StringUtils;

import com.blu.service.SendSms;

@RestController

@CrossOrigin

public class SmsApiController {

@Autowired

private SendSms sendSms;

@Autowired

private RedisTemplate<String,String> redisTemplate;

@GetMapping("send/{phone}")

public String code(@PathVariable("phone") String phone) {

String code = redisTemplate.opsForValue().get(phone);

if(!StringUtils.isEmpty(code)) {

return phone + ':' + code + "還沒有過期";

}else {

//生成4位驗證碼并存儲到 redis 中

code = UUID.randomUUID().toString().substring(0,4);

HashMap<String, Object> map = new HashMap<>();

map.put("code", code);

boolean isSend = sendSms.send(phone, "SMS_205403229", map);

if(isSend) {

                //將驗證碼存入redis,并設置1分鐘過期時間

redisTemplate.opsForValue().set(phone, code,1,TimeUnit.MINUTES);

return phone + ':' + code + "發(fā)送成功!";

}else {

return "發(fā)送失敗!";

}

}

}

}

測試請求:http://localhost:9090/send/1565177xxxx

ia_500000008.png

ia_500000009.png

立即登錄,閱讀全文
版權說明:
本文內(nèi)容來自于CSDN,本站不擁有所有權,不承擔相關法律責任。文章內(nèi)容系作者個人觀點,不代表快出海對觀點贊同或支持。如有侵權,請聯(lián)系管理員(zzx@kchuhai.com)刪除!
掃碼登錄
打開掃一掃, 關注公眾號后即可登錄/注冊
加載中
二維碼已失效 請重試
刷新
賬號登錄/注冊
個人VIP
小程序
快出海小程序
公眾號
快出海公眾號
商務合作
商務合作
投稿采訪
投稿采訪
出海管家
出海管家