You can use a message queue to receive SMS delivery status reports (SmsReport), which are delivery receipts for messages sent using the SendSms and SendBatchSms API operations.
Prerequisites
-
You have registered an Alibaba Cloud account and generated an access key (AccessKey). For more information, see Create an AccessKey for a RAM user.
-
Make sure you can ping the following endpoints from your local machine:
dysmsapi.aliyuncs.com,mns.cn-hangzhou.aliyuncs.com(for the China (Hangzhou) region), ordybaseapi.aliyuncs.com. -
You have created a RAM user and granted it Short Message Service permissions and Lightweight Message Queue permissions.
-
You have read Configure message receipts and understand the receipt message modes, types, and configuration process.
SmsReport message body format
|
Parameter |
Type |
Example |
Description |
|
send_time |
String |
2021-09-06 15:49:55 |
The time when the message was forwarded to the carrier. |
|
report_time |
String |
2021-09-06 15:49:58 |
The time when the delivery receipt was received from the carrier. |
|
success |
Boolean |
true |
Indicates whether the message was delivered successfully. Valid values:
|
|
err_msg |
String |
The user received the message. |
The description of the status code. |
|
err_code |
String |
DELIVERED |
The status code from the carrier. For successful deliveries, this is often |
|
phone_number |
String |
159****6532 |
The recipient's phone number. |
|
sms_size |
String |
1 |
The length of the SMS message. For details on how message length is calculated, see SMS sending rules. |
|
biz_id |
String |
12345 |
The delivery receipt ID, also known as the delivery serial number. This is the
|
|
out_id |
String |
123456 |
The custom |
Download the demo
See Lightweight Message Queue (formerly MNS) consumer demo to download the demo and SDK for your preferred programming language. This topic uses Java as an example.
-
After you download the demo, the
libdirectory contains the required JAR packages. Import them by clicking Add as Library. -
You can find the Maven dependencies in the
pom.xmlfile and install the Alibaba Cloud SDK for Java.
Configure parameters
Before using the sample code, configure the following parameters.
Access key
Complete example
The dealMessage method processes the status reports you receive. You can add your business logic for handling these reports within this method.
// Parse the message body based on the message format in the documentation.
String arg = (String) contentMap.get("arg");
// Add your business logic here.
The arg parameter represents a field in the receipt message body. Valid values include: send_time, report_time, success, err_msg, err_code, phone_number, sms_size, biz_id, and out_id.
package com.alicom.mns.sample;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alicom.mns.tools.DefaultAlicomMessagePuller;
import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.google.gson.Gson;
/**
* This demo is for receiving messages from Alibaba Cloud Communications services only. It cannot be used for other services.
*/
public class ReceiveDemo {
private static Log logger=LogFactory.getLog(ReceiveDemo.class);
static class MyMessageListener implements MessageListener{
private Gson gson=new Gson();
@Override
public boolean dealMessage(Message message) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Key values of the message
System.out.println("message receiver time from mns:" + format.format(new Date()));
System.out.println("message handle: " + message.getReceiptHandle());
System.out.println("message body: " + message.getMessageBodyAsString());
System.out.println("message id: " + message.getMessageId());
System.out.println("message dequeue count:" + message.getDequeueCount());
System.out.println("Thread:" + Thread.currentThread().getName());
try{
Map<String,Object> contentMap=gson.fromJson(message.getMessageBodyAsString(), HashMap.class);
// Parse the message body based on the message format in the documentation.
String arg = (String) contentMap.get("arg");
// Add your business logic here.
}catch(com.google.gson.JsonSyntaxException e){
logger.error("error_json_format:"+message.getMessageBodyAsString(),e);
// JSON format errors should not occur. If they do, delete the message to prevent it from being redelivered and causing repeated errors.
return true;
} catch (Throwable e) {
// If an exception occurs in your business logic, return false. This prevents the message from being deleted and allows it to be redelivered according to the retry policy.
return false;
}
// If the message is processed successfully, return true. The SDK will then delete the message from the queue.
return true;
}
}
public static void main(String[] args) throws Exception, ParseException {
DefaultAlicomMessagePuller puller=new DefaultAlicomMessagePuller();
// Set the asynchronous thread pool size, task queue size, and idle thread sleep time.
puller.setConsumeMinThreadSize(6);
puller.setConsumeMaxThreadSize(16);
puller.setThreadQueueSize(200);
puller.setPullMsgThreadSize(1);
// Enable this for server-side debugging. Keep it disabled during normal operation to improve performance.
puller.openDebugLog(false);
// Obtain the AccessKey ID and AccessKey secret from local environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
/*
* Replace messageType and queueName with your message type and queue name.
* Supported message types for Alibaba Cloud Communications services:
* 1. SMS delivery receipt: SmsReport,
* 2. Inbound SMS message: SmsUp,
* 3. International SMS delivery receipt: GlobeSmsReport
*/
String messageType="<MESSAGE_TYPE>"; // Replace this with the message type for your product.
String queueName="<QUEUE_NAME>"; // The queue name is available on the console page after you enable message queuing. The format is similar to Alicom-Queue-******-SmsUp.
puller.startReceiveMsg(accessKeyId,accessKeySecret,messageType,queueName,new MyMessageListener());
}
}
The following is sample output from running the demo.
/Library/Java/JavaVirtualMachines/jdk1.8.0_291.jdk/Contents/Home/bin/java ...
Connected to the target VM, address: '127.0.0.1:62393', transport: 'socket'
14:00:07.056 [PullMessageTask-thread-0] DEBUG com.aliyun.mns.client.CloudAccount - initiated CloudAccount, accessId: xxx accessKey= xxx
message receiver time from mns: xxx
message handle: xxx
message body: xxx
message id: xxx
message dequeue count:1
Thread:pool-1-thread-1