07 June 2015

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;
 }

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

WFFM Web form for marketer fail to submit in Sitecore

I have setup a standard form using WFFM in Sitecore 8.2. It always fail when submit. Error as below, Error: Exception: System.Data.DataE...