2018-04-15

[ASP.NET] Amazon SNS Service - Send SMS (中集 - 使用 API 發送)

註冊和測試都沒問題後,來看看要如何使用 Amazon 提供的 API 發送簡訊。


建立 IAM User
使用 API 來發送前,需要先建立一個 IAM User,API 是透過它來做驗證並發送的。

進入 My Security Credentials,選擇 User --> Add User。



過程中的 Permissions 選 Attach existing policies directly,加上以下三個 Policy,第一個是允許該 User 可以完全存取 Amazon SNS Service,後兩個是可以完全存取發送的 Log 檔,用來查詢發送結果是否成功:
  • AmazonSNSFullAccess
  • CloudWatchEventsFullAccess
  • CloudWatchLogsFullAccess


建立完成後,會拿到該 User 的 Access Key 和 Security Access Key,在 API 中會使用到。



使用 API 發送
Amazon Documents 中有 Java 的發送簡訊範例,依樣畫葫藘改成 .Net 版本如下,Coding 前要先 NuGet AWSSDK.SimpleNotificationService API:
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
...

Dictionary<string, MessageAttributeValue> smsAttributes = new Dictionary<string, MessageAttributeValue>();
MessageAttributeValue senderID = new MessageAttributeValue();
MessageAttributeValue sMSType = new MessageAttributeValue();
MessageAttributeValue maxPrice = new MessageAttributeValue();
PublishRequest publishRequest = new PublishRequest();

AmazonSimpleNotificationServiceClient smsClient = new AmazonSimpleNotificationServiceClient("AccessKey", "SecretKey", Amazon.RegionEndpoint.APSoutheast2);

senderID.DataType = "String";
senderID.StringValue = "mySenderId"; // Taiwan not support

sMSType.DataType = "String";
sMSType.StringValue = "Promotional";

maxPrice.DataType = "Number";
maxPrice.StringValue = "0.1";

smsAttributes.Add("AWS.SNS.SMS.SenderID", senderID);
smsAttributes.Add("AWS.SNS.SMS.SMSType", sMSType);
smsAttributes.Add("AWS.SNS.SMS.MaxPrice", maxPrice);

publishRequest.Message = "Tim test send SMS from Amazon SNS Service.";            
publishRequest.PhoneNumber = "+886912345678";
publishRequest.MessageAttributes = smsAttributes;

PublishResponse response = smsClient.Publish(publishRequest);

最後的 PublishResponse 會回傳 JSON,請記下裡面的 MessageID,在下一篇將用它來查詢 Log 用來判斷簡訊是否發送成功。

此範本中 AmazonSimpleNotificationServiceClient API 的 Region 我是指到 APSoutheast2 (Asia Pacific (Sydney)),所以在看 Bill 時,要將 Account 的 Region 切換到 Sydney 才能看到。


沒有留言:

張貼留言