Alibaba Cloud Short Message Service (SMS)API Access Tutorial: Support Vue SpringBoot

cloud 2026-05-28 阅读 15
3

Whether it is user registration, login verification, or order status notification, SMS service is just needed.

Many novices look at Aliyun's official SMS documents and are easily confused by a pile of AccessKey, signatures, templates and SDK concepts. In addition, the official sample code is often bloated and they do not know how to integrate with their front-end and back-end projects at that time.

Today, don't talk nonsense, directly on the actual combat. Take you to use the most grounded "real-life writing style",

Run through Aliyun Short Message Service (SMS) in 5 minutes from background configuration, to back-end Spring Boot core logic encapsulation, and then to the full countdown implementation of front-end Vue.

Core Interaction Process

Before writing the code, fill in the closed-loop logic of the verification code SMS:

Plaintext

[Vue Front End] -1. Enter the mobile phone number and click Send-> [Spring Boot Back End]]

▲ │

2. Generate a 6-bit random number.

│ 3. Deposit Redis (set to expire in 5 minutes)

│ 4. Call Aliyun API to send

│ │

│ ▼

[User's mobile phone] <── 5. Received SMS verification code ── ─ [Alibaba Cloud SMS Gateway]]

Step 1: Alibaba Cloud console activation and qualification application (2 minutes)

As the domestic anti-fraud governance is very strict, SMS service

Must apply for qualification and signature first

, directly calling the API will report a permission error.

1. Open service

Log on to the Alibaba Cloud console and search

"SMS Service"

, click on the open (open free, send according to the deduction, suggest to buy a package of tens of dollars).

2. Apply for SMS signature (who are you)

Go to the SMS console. On the left, click China Message $\rightarrow $Signature Management $\rightarrow $Add Signature ".

Signature Name: Usually your website name, app name, or company abbreviation (such as a geek blog).

Signature Source: Individual developers generally choose "Filed Website" or "Real Application" and need to provide

Your ICP record number or app screenshot.

3. Apply for SMS template (what did you send)

Switch to Template Management $\rightarrow $Add Template ".

Template Type: Select Verification Code ".

Template name: such as login verification code.

Template content: fixed format, variable with ${code}. For example, if you are logging in to the system, the verification code is ${code}, valid for 5 minutes. Please do not disclose it to others.

Submitted for review, usually 10 to 30 minutes to pass. Remember the TemplateCode after passing (such as SMS_1234567).

Step 2: Back-end Spring Boot core docking (3 minutes)

Don't use the old version of SDK, we directly use Aliyun's latest

V2.0

Cloud-native Java SDK, more streamlined code.

1. Introducing Maven dependencies

In your Spring Boot project

pom.xml

Introduce the Aliyun SMS core library in:

XML

<dependency>

<groupId>com.aliyun</groupId>

<artifactId>dysmsapi20170525</artifactId>

<version>3.0.0</version> </dependency>

2. Configure the key in application.yml.

Do you remember the principle of minimum RAM permissions that we talked about in the last issue? Go to the Alibaba Cloud RAM console to create a sub-account and only grant

AliyunDysmsFullAccess

(SMS management) permission, generate a set of AK/SK fill in here:

YAML

aliyun:

sms:

access-key-id: LTAI5tXXXXXXXXXXXX# sub-account AK

access-key-secret: Pn7yXXXXXXXXXXXXXXXX# sub-account SK

Sign-name: geek blog# the signature you applied

template-code: SMS_1234567# ID of the template you applied

3. Encapsulate the SMS sending tool class

Create a Service and directly copy the following pure dry goods code that I have simplified and optimized for you:

Java

import com.aliyun.dys

msapi20170525.Client;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;

import com.aliyun.teaopenapi.models.Config;

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

import org.springframework.stereotype.Service;

@Service

public class SmsService {

@Value("${aliyun.sms.access-key-id}")

private String accessKeyId;

@Value("${aliyun.sms.access-key-secret}")

private String accessKeySecret;

@Value("${aliyun.sms.sign-name}")

private String signName;

@Value("${aliyun.sms.template-code}")

private String templateCode;

/**

* Send verification code SMS

* @ param phone target phone number

* @ param code random verification code

*/

public boolean sendVerifyCode(String phone, String code) {

try {

// 1. Initialize the configuration client

Config config = new Config()

.setAccessKeyId(accessKeyId)

.setAccessKeySecret(accessKeySecret);

// Fixed SMS access point

config.endpoint = "dysmsapi.aliyuncs.com ";

Client client = new Client(config);

// 2. Assembly request parameters

SendSmsRequest request = new SendSmsRequest()

.setPhoneNumbers(phone)

.setSignName(signName)

.setTemplateCode(templateCode)

// Variables must be converted to JSON string format.

.setTemplateParam("{\"code\":\"" code "\"}");

// 3. Perform Send

SendSmsResponse response = client.sendSms(request);

// 4. Judge the sending result

if (" OK ".equals(response.getBody().getCode())) {

return true;

} else {

System.err.println("SMS sending failed, reason:" response.getBody().getMessage());

return false;

}

} catch (Exception e) {

e.printStackTrace();

return false;

}

}

}

4. Write Controller business interface

In the Controller layer, combine your Redis (here with pseudo-code instead of showing the logical closed loop):

Java

@RestController

@RequestM

apping("/api/sms")

public class SmsController {

@Autowired

private SmsService smsService;

@Autowired

private StringRedisTemplate redisTemplate; // Inject Redis

@PostMapping("/send")

public ResponseEntity<String> sendCode(@RequestParam String phone) {

// 1. Simple regular check of mobile phone number

if (! phone.matches("^1[3-9]\\d{9}$")) {

return ResponseEntity.badRequest().body("Incorrect phone number format");

}

// 2. Anti-brush mechanism: Check Redis to make sure that there is no repeat sending within 60 seconds.

if (Boolean.TRUE.equals(redisTemplate.hasKey("SMS_LIMIT:" phone))) {

return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("Send too frequently, please try again later");

}

// 3. Generate 6 random number verification code

String code = String.valueOf((int)((Math.random() * 9 1) * 100000));

// 4. Call the Alibaba Cloud service to send

boolean isSuccess = smsService.sendVerifyCode(phone, code);

if (! isSuccess) {

return ResponseEntity.status(500).body("SMS sending failed, please contact administrator");

}

// 5. Store in Redis and set the validity period of 5 minutes; At the same time, set one

60-second anti-brush limit

redisTemplate.opsForValue().set("SMS_CODE:" phone, code, 5, TimeUnit.MINUTES);

redisTemplate.opsForValue().set("SMS_LIMIT:" phone, "1", 60, TimeUnit.SECONDS);

return ResponseEntity. OK ("verification code sent successfully");

}

}

Step 3: Write the front-end Vue countdown component (1 minute)

The back-end is done, and the front-end we need to do a standard 60-second countdown to prevent users from clicking the "send" button crazily.

Here, taking… as an example

Vue 3 (Composition API) Axios

For example, directly on the most intuitive code:

Code snippet

<template>

<div class="sms-box">

<input type = "text" v-model = "phone" placeholder = "Enter your phone number" />

<button :disabled="isCounting" @click="handleSend">

{{isCounting ? '${countdown} seconds later to get': 'Get verification code'}}

</button>

</div>

</template>

<script setup>

import { ref } from 'vue ';

import axios from 'axios ';

const phone = ref('');

const countdown = ref(60);

const isCounting = ref(false);

let timer = null;

const handleSend = async () => {

if (! /^1[3-9]\d{9}$/.test(phone.value)) {

alert ('Please enter the correct phone number ');

return;

}

try {

// Call the back-end interface.

const res = awa

it axios.post('/api/sms/send?phone=${phone.value}');

alert(res.data);

// Activate the countdown

startCountdown();

} catch (error) {

alert(error.response?.data | | 'Request Failed');

}

};

const startCountdown = () => {

isCounting.value = true;

countdown.value = 60;

timer = setInterval(() => {

countdown.value --;

if (countdown.value <= 0) {

clearInterval(timer);

isCounting.value = false;

}

}, 1000);

};

</script>

Guide to Avoid Pits in Production Environment (Operation and Maintenance Experience)

Beware of the interface by hackers "SMS bombing"! As soon as the interface goes online, hackers will use automated scripts to frantically request your/api/sms/send interface with tens of thousands of random mobile phone numbers. You can deduct all the balance of your Aliyun account in one night. Iron law defense: in addition to the 60-second countdown at the front end and the 60-second frequency limit of single phone number with Redis at the back end, "graphic verification code" or "man-machine slider verification" must be forcibly added to the interface sending short messages ". Only legitimate requests for puzzle success, the backend will text.

The "frequency limit" that triggers Alibaba Cloud to report an error. Alibaba Cloud SMS has a flow control and anti-brush mechanism (no more than 1 cell phone number in 1 minute, no more than 5 cell phone numbers in 1 hour, and no more than 10 cell phone numbers in 1 day). If you send yourself a text message during a local test and suddenly report an error in the isv.BUSINESS_ LIMIT_CONTROL, don't panic. It's not that the code is wrong, but that you are officially restricted by ariyun, and it will be automatically unblocked tomorrow.

When this set of front-end and back-end closed-loop comes down, your microservice application will officially have the ability to notify compliant and secure short messages. Quickly deploy to try it!

3
← 返回新闻中心