Using Telstra API to send SMS in ASP.NET

Telstra (https://dev.telstra.com/) is pushing their own API and as a part of the plan, it is giving away 1000 free SMS per month with the limit of 100 per day.

After a simple register and set up, wait about 1 hour for get "MyAPP" approved, it is ready to go.



It requests an access token with your own "key" and "secret" first which expires in 1 hour. Then we need to pass in this token with all the request we are going to make.
The documentation is simple, straight forward and all the sample code is hosted on github. I write a quick C# to test it out and it works well!

public string GetAccessToken()
{
    const string consumerKey = "{yourkey}";
    const string consumerSecret = "{secret}";
    string url =string.Format("https://api.telstra.com/v1/oauth/token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=SMS", consumerKey, consumerSecret);

    using (var webClient = new System.Net.WebClient())
    {
        var json = webClient.DownloadString(url);
        var obj = JObject.Parse(json);
        return obj.GetValue("access_token").ToString();
     }
}
public string SendSms(string token, string recipientNumber, string message)
{
     try
     {
        using (var webClient = new System.Net.WebClient())
        {
            webClient.Headers.Clear();
            webClient.Headers.Add(HttpRequestHeader.ContentType, @"application/json");
            webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);

            string data = "{\"to\":\"" + recipientNumber + "\", \"body\":\"" + message + "\"}";
            var response = webClient.UploadData("https://api.telstra.com/v1/sms/messages", "POST", Encoding.Default.GetBytes(data));
            var responseString = Encoding.Default.GetString(response);
            var obj = JObject.Parse(responseString);
            return obj.GetValue("messageId").ToString();
                    // Now parse with JSON.Net
        }
     }
     catch (Exception e)
     {
        Console.WriteLine(e.Message);
     }
        return string.Empty;
 }

Comments

  1. mobile marketing is the part of marketing strategy so you can use Bulk SMS Service Provider in India to send sms with sms API and promote your business.

    ReplyDelete

Post a Comment

Popular posts from this blog

Access to the registry key 'Global' is denied in Sitecore

Install MongoDB in Debian

Refresh the page after deletion in Page Editor mode using Sitecore