问题描述
POST https://connect.esendex.com/richcontent/v3/send
我的任务是使用 EsendEx 作为 SMS 提供商实施并努力在他们的网站上找到工作代码,我在这里提出了一个解决方案。
这是使用富内容 API,因为它看起来最灵活,尽管它首先需要您在 EsendEx 上启用提供程序并复制订阅密钥。
这是所需的完整代码,我也将其分为请求和响应对象的类。您可能希望将这些类复制到解决方案中的文件夹中。
希望这会有所帮助。
向 REST API 发送短信将导致此调用:
static void Main(string[] args)
{
var smsProvider = new EsendexSmsProvider();
var success = smsProvider.SendViaRichContentAsync( "Hello [[first_Name]],this is the voice of the Mysterons sending a test message").Result;
}
解决方法
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace EsendExExample
{
using EsendExExample.Request;
using EsendExExample.Response;
class Program
{
static void Main(string[] args)
{
var smsProvider = new EsendexSmsProvider();
var success = smsProvider.SendViaRichContentAsync( "Hello [[first_Name]],this is the voice of the Mysterons sending a test message").Result;
}
}
static class stuff
{
public static string ToBase64(this string plainTextToConvert)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainTextToConvert);
return System.Convert.ToBase64String(plainTextBytes);
}
}
/// <summary>
/// Specific SMS sender implementation for Esendex SMS
/// https://developers.esendex.com/
/// </summary>
public sealed class EsendexSmsProvider
{
private const string AccountRef = "EX0<number>";
private const string Username = "someone@test.com";
private const string ApiKey = "<yourkey>";
private const string UserPassword = "<userpassword>";
private const string RichContentEndPoint = "https://connect.esendex.com/richcontent/v3/send";
// https://console.esendex.com/products/rich-content add subscription get key
private const string RichContentSubscriptionKey = "<yoursubscription>";
/// <summary>
/// POST https://connect.esendex.com/richcontent/v3/send
///
/// Authorization: YOUR_PRIMARY_KEY
/// Content-Type: application/json
///
/// https://developers.esendex.com/api-reference
/// Example code founds at https://console.esendex.com/docs/services/Version-3/operations/Send
/// </summary>
public async Task<bool> SendViaRichContentAsync(string body)
{
var request = this.GetEsendexRichContentMessageRequest(body);
var json = JsonConvert.SerializeObject(request);
var httpResponse = await this.SendSms(json,RichContentEndPoint,RichContentSubscriptionKey);
var responseBody = await httpResponse.Content.ReadAsStringAsync();
var esendExResponse = JsonConvert.DeserializeObject<EsendExMessageResponse>(responseBody);
return httpResponse.IsSuccessStatusCode;
}
private async Task<HttpResponseMessage> SendSms(string message,string endPoint,string subKey)
{
HttpResponseMessage response = null;
try
{
var request = new HttpRequestMessage(HttpMethod.Post,endPoint)
{
Content = new StringContent(message,Encoding.UTF8,"application/json")
};
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("Authorization",subKey);
response = await httpClient.SendAsync(request);
}
catch (Exception e)
{
Console.WriteLine(e);
}
return response;
}
private EsendexRichContentMessageRequest GetEsendexRichContentMessageRequest(string body)
{
return new EsendexRichContentMessageRequest
{
AccountReference = AccountRef,Channels = new List<string> {"SMS"},Metadata = new EsendexRichContentMetadata
{
Key = "blah"
},Recipient = new EsendexRichContentRecipient
{
Variables = new EsendexRichContentVariables
{
["first_Name"] = "Paul"
},Address = new EsendexRichContentAddress
{
msisdn = "+44<number>"
}
},ChannelSettings = new EsendexRichContentChannelSettings
{
Sms = new EsendexRichContentSms
{
Originator = "John Doe",CharacterSet = "GSM"
}
},Content = new EsendexRichContentContent
{
Body = new EsendexRichContentBody
{
Text = new EsendexRichContentText
{
Value = "Hello [[first_Name]],this is the voice of the Mysterons sending a test message"
}
}
},Expiry = "30"
};
}
}
}
namespace EsendExExample.Request
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
/// <summary>
/// Serializing class for sending message to EsendEx rest API for messages
/// </summary>
/// <example>
/// {
/// "accountReference":"EX0000000",/// "messages":[{
/// "to":"447700900123",/// "body":"Every message matters!"
/// }]
/// }
/// </example>
public class EsendExMessageRequest
{
[JsonProperty("accountReference")]
public string AccountReference { get; set; }
[JsonProperty("messages")]
public ICollection<EsendExMessage> Messages { get; set; }
}
public class EsendExMessage
{
/// <summary>
/// Gets or sets the phone number/ recipient identifier to send the message to
/// </summary>
[JsonProperty("to")]
public string To { get; set; }
/// <summary>
/// Gets or sets the message to be sent in the SMS
/// </summary>
[JsonProperty("body")]
public string Message { get; set; }
}
public class EsendexRichContentAddress
{
/// <summary>
/// Gets or sets the address id,or more frequently the Internationalised phone number.
///
/// E.164 MSISDN Format
/// The telephone number of the message recipient must be in E.164 format. This means the number must be in the format:
///
/// +{Country Dial Code}{Rest of phone number}
/// Examples
///
/// Phone Number Country Dial Code E.164 Formatted Number
/// 07948751633 UK 44 +447948751633
/// 0123456789 France 33 +33123456789
/// 912345678 Spain 34 +34912345678
/// 0491570156 Australia 61 +61491570156
/// 5417543010 USA 1 +15417543010
/// </summary>
[JsonProperty("msisdn")]
public string msisdn { get; set; }
}
public class EsendexRichContentBody
{
[JsonProperty("text")]
public EsendexRichContentText Text { get; set; }
}
public class EsendexRichContentChannelSettings
{
[JsonProperty("sms")]
public EsendexRichContentSms Sms { get; set; }
}
public class EsendexRichContentContent
{
[JsonProperty("body")]
public EsendexRichContentBody Body { get; set; }
}
/// <summary>
/// Serializing class for sending message to EsendEx rest API for messages using rich content SMS/pictures/whatsapp
/// </summary>
/// <example>
/// {
/// "accountReference": "{ESENDEX_ACCOUNT_REFERENCE}",/// "channels": [
/// "SMS"
/// ],/// "metadata":{
/// "key": "value"
/// },/// "recipient": {
/// "variables": {
/// "name": "Fred"
/// },/// "address": {
/// "msisdn": "{INTERNATIONALISED_PHONE_NUMBER}"
/// }
/// },/// "content": {
/// "body": {
/// "text": {
/// "value": "Hello [[name]]"
/// }
/// }
/// },/// "channelSettings": {
/// "sms": {
/// "originator": "{MESSSAGE_ORIGINATOR}",/// "characterSet": "GSM"
/// }
/// },/// "expiry": "30"
/// }
/// </example>
public class EsendexRichContentMessageRequest
{
[JsonProperty("accountReference")]
public string AccountReference { get; set; }
[JsonProperty("channels")]
public List<string> Channels { get; set; }
[JsonProperty("metadata")]
public EsendexRichContentMetadata Metadata { get; set; }
[JsonProperty("recipient")]
public EsendexRichContentRecipient Recipient { get; set; }
[JsonProperty("content")]
public EsendexRichContentContent Content { get; set; }
[JsonProperty("channelSettings")]
public EsendexRichContentChannelSettings ChannelSettings { get; set; }
[JsonProperty("expiry")]
public string Expiry { get; set; }
}
public class EsendexRichContentMetadata
{
[JsonProperty("key")]
public string Key { get; set; }
}
public class EsendexRichContentRecipient
{
[JsonProperty("variables")]
public EsendexRichContentVariables Variables { get; set; }
[JsonProperty("address")]
public EsendexRichContentAddress Address { get; set; }
}
public class EsendexRichContentSms
{
[JsonProperty("originator")]
[MaxLength(11)]
public string Originator { get; set; }
[JsonProperty("characterSet")]
public string CharacterSet { get; set; }
}
public class EsendexRichContentText
{
[JsonProperty("value")]
public string Value { get; set; }
}
/// <summary>
/// Used to st up any variables that can be used in the message via substitution.
///
/// https://developers.esendex.com/api-reference#recipient-variables
/// </summary>
/// <example>
/// {
/// "recipient": {
/// "variables": {
/// "first_name": "John",/// "last_name": "Smith"
/// },/// "address": {
/// "msisdn": "+447123456789"
/// }
/// },/// "content": {
/// "text": "Hello [[first_name]] [[last_name]]"
/// }
/// }
/// </example>
public class EsendexRichContentVariables : Dictionary<string,string>
{
}
}
namespace EsendExExample.Response
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
/// <summary>
/// The accepted response from the Esendex SMS REST API call.
/// </summary>
/// <example>
/// {
/// "batch": {
/// "batchid": "19aafc9c-b08a-400d-a9f1-afe3c46f0a25",/// "messageheaders": [
/// {
/// "uri": "http://api.esendex.com/v1.0/messageheaders/72d91006-eb01-4e69-ae98-0e02c92c8e34",/// "id": "72d91006-eb01-4e69-ae98-0e02c92c8e34"
/// }
/// ]
/// },/// "errors": null
/// }
/// </example>
public class EsendExMessageResponse
{
[JsonProperty("gatewayId")]
public Guid GatewayId { get; set; }
public EsendExResponseBatch Batch { get; set; }
[JsonProperty("errors")]
public ICollection<EsendExResponseError> Errors { get; set; }
}
public class EsendExResponseBatch
{
[JsonProperty("batchid")]
public string BatchId { get; set; }
[JsonProperty("messageheaders")]
public Collection<EsendExResponseMessageHeader> MessageHeaders { get; set; }
}
public class EsendExResponseError
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("error")]
public string Description { get; set; }
}
public class EsendExResponseMessageHeader
{
public string Uri { get; set; }
public string Id { get; set; }
}
}