2015-07-06

Telstra SMS API Quick Demonstration

Telstra recently opened its Dev portal to public. So I just spent some time on its SMS API, and record what I found here.

Overall, Telstra did a good attempt for developers. The SMS API Telstra published allows end user to send 1000 sms for free per month. But there are still quite a lot things need to be improved: documentation, tutorials, API functionality, error handling, etc.

Now time for the demonstration. The application I built is like this:


When I send a SMS from the application, my mobile looks like



And then from the application screenshot, you can see the response I made from my mobile.

To do this, firstly you need to have a developer account. You can register through the link here. In Telstra Dev centre, there are three APIs are available at the moment, as shown below



What we need today is the SMS API. Now click My Apps link, you should be navigated to the My Apps portal.



Click the button "Add a new App" on your right hand side, then you should see the new app registration window like below. Remember in this post we are going to build the SMS App, so just check it. The call back url can be used for application verification in a real world scenario. But in this demonstration, I just create a dummy one.



After you create the App, your request should be shown as pending



Just give it a few hours. When you come back, you should see the Pending status has been changed to Approved. Now expand the App, you can see the consumer key and consumer secret.


Now in Visual Studio, I created a winform project, and add a reference for Newtonsoft.Json (find here), as we need to parse json for the API.

The code itself is quite simple, step by step, we need to
  • Create a Token by using consumer key and consumer secret;
  • Send SMS;
  • Refresh to get the response;

Long in short, the complete code looks like this:

 public partial class Form1 : Form  
   {  
     private TelstraToken TheToken;  
     public Form1()  
     {  
       InitializeComponent();  
     }      
     private async void button1_Click(object sender, EventArgs e)  
     {  
       string ConsumerKey = "<consumer key>";  
       string ConsumerSecret = "<consumer secret>";  
       TheToken = await GetAccessToken(ConsumerKey, ConsumerSecret);  
       string Mobile = txtMobile.Text;  
       string Sms = txtSMS.Text;  
       SMSMessage SMS = new SMSMessage();  
       SMS = SendSMS(Mobile, Sms, TheToken);  
       lstSMS.Items.Add(SMS);  
       lstSMS.DisplayMember = "Mobile";        
     }  
     private void btnRefresh_Click(object sender, EventArgs e)  
     {  
       SMSMessage item = (SMSMessage)lstSMS.SelectedItem;  
       CheckStatus(item, TheToken);  
       if (!string.IsNullOrEmpty(item.ResponseContent))  
       {  
         txtResponse.Text = "Response: " + item.ResponseContent + Environment.NewLine + "RepondTime: " + item.AcknowledgedDt.ToShortDateString();  
       }  
       MessageBox.Show(item.Status);  
     }  
     private async Task<TelstraToken> GetAccessToken(string consumerkey, string consumersecret)  
     {  
       TelstraToken Token = new TelstraToken();  
       string AccessUrl = @"https://api.telstra.com/v1/oauth/token";  
       HttpClient authClient = new HttpClient();  
       HttpContent httpContent = new FormUrlEncodedContent(new Dictionary<string, string>   
       {  
         {"client_id", consumerkey},  
         {"client_secret", consumersecret},  
         {"grant_type", "client_credentials"},  
         {"scope", "SMS"}  
       });  
       HttpRequestMessage Request = new HttpRequestMessage()  
       {  
         Method = HttpMethod.Post,  
         RequestUri = new Uri(AccessUrl),  
         Content = httpContent  
       };  
       try  
       {  
         var ResponseMessage = await authClient.SendAsync(Request);  
         var Response = await ResponseMessage.Content.ReadAsStringAsync();  
         if (ResponseMessage.IsSuccessStatusCode)  
         {  
           var AuthToken = JsonConvert.DeserializeObject<object>(Response);  
           JObject jObj = JObject.Parse(AuthToken.ToString());  
           Token.AccessToken = jObj["access_token"].ToString();  
           Token.ExpiryDt = DateTime.Now.AddSeconds(double.Parse(jObj["expires_in"].ToString()));  
         }  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
       return Token;   
     }  
     private SMSMessage SendSMS(string mobile, string message, TelstraToken token)   
     {  
       SMSMessage msg = new SMSMessage();  
       if (token.ExpiryDt <= DateTime.Now)  
       {  
         MessageBox.Show("Session Expired!");  
         return null;  
       }  
       WebClient Client = new WebClient();  
       Client.Headers.Clear();  
       Client.Headers.Add("Authorization: Bearer " + token.AccessToken);  
       Client.Headers.Add("Content-Type", "application/json");  
       string command = "{\"to\":\"" + mobile + "\", \"body\":\"" + message + "\"}";  
       try  
       {  
         byte[] buffer = Client.UploadData(@"https://api.telstra.com/v1/sms/messages", "POST", Encoding.Default.GetBytes(command));  
         string bufferstring = Encoding.Default.GetString(buffer);  
         JObject o = JObject.Parse(bufferstring);  
         msg.MessageID = o["messageId"].ToString();  
         msg.SendDt = DateTime.Now;  
         msg.Status = "PEND";  
         msg.Mobile = txtMobile.Text;  
         msg.Message = txtSMS.Text;  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
       return msg;  
     }  
     private void CheckStatus(SMSMessage msg, TelstraToken token)  
     {  
       string status = string.Empty;  
       if (token.ExpiryDt < DateTime.Now)  
       {  
         MessageBox.Show("Session expired!");  
         return;  
       }  
       WebClient Client = new WebClient();  
       Client.Headers.Clear();  
       Client.Headers.Add("Authorization: Bearer " + token.AccessToken);  
       try  
       {  
         byte[] buffer = Client.DownloadData(string.Format("https://api.telstra.com/v1/sms/messages/{0}", msg.MessageID));  
         string bufferstring = Encoding.Default.GetString(buffer);  
         JObject o = JObject.Parse(bufferstring);  
         msg.Status = o["status"].ToString();  
         byte[] Response = Client.DownloadData(string.Format("https://api.telstra.com/v1/sms/messages/{0}/response", msg.MessageID));  
         string ResponseString = Encoding.Default.GetString(Response);  
         //JObject oR = JObject.Parse(ResponseString);  
         JArray a = JArray.Parse(ResponseString);  
         foreach (JObject jo in a)  
         {  
           if (jo["content"].ToString() != "N/A")  
           {  
             msg.ResponseContent = jo["content"].ToString();  
             msg.AcknowledgedDt = DateTime.Parse(jo["acknowledgedTimestamp"].ToString());  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  
     private class SMSMessage  
     {  
       //unique id of the message  
       public string MessageID { get; set; }  
       //datetime of the message was sent  
       public DateTime SendDt { get; set; }  
       //current status of the message  
       public string Status { get; set; }  
       //message body  
       public string Message { get; set; }  
       //sms recipient  
       public string Mobile { get; set; }  
       //datetime when the message acknowledged  
       public DateTime AcknowledgedDt { get; set; }  
       //response  
       public string ResponseContent { get; set; }  
     }  
     private class TelstraToken  
     {  
       public string AccessToken { get; set; }  
       public DateTime ExpiryDt { get; set; }  
     }  
   }  


Just some quick explanation:
  • The token will be expired after certain time (3600), therefore when I create the Telstra token, I will record the expiry date time of the token.
  • There is 160 characters limitation of the SMS API, but we need to handle by ourselves, e.g. read amount of characters in the application. Otherwise it will return server error 400.
  • When send the message, I will store the message into the SMSMessage class, and list it into the listbox. For the listed message, I can check its status by click refresh button.


The problem of this API is that it will send the message via a random Telstra owned mobile number. As you can imagine, we could treat it like a fraud SMS. So hopefully it can be improved in its future release.

9 comments :

  1. Thanks for a great little tutorial for a noob :)

    ReplyDelete
  2. helpful data on subjects that bounty are intrigued on for this awesome post.Admiring the time and exertion you put into your b!.. Bulk SMS in Pune

    ReplyDelete
  3. I was looking for SMS API from a longtime to send bulk SMS directly from the platform. Thank you so much for sharing this informative blog here.

    ReplyDelete
  4. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
    Digital Mobile Marketing
    SMS API
    SMS Marketing

    ReplyDelete
  5. Anonymous2/4/19 02:21

    Telstra is well known SMS Service provider.For bulk messaging API is best to use to get instant results and is also easy to use. Everyone is not able to pay a large amount of money so it is the best option for them.Bulk SMS API

    ReplyDelete
  6. A Bulk SMS API is an application interface which allows functions of bulk messaging softwares to be used within the existing technical framework of business applications and ensure that the two key applications work harmoniously.

    ReplyDelete
  7. Nowadays landline texting is popular in worldwide. If you are not using it for your business that means you are missing so many business opportunities. To get all opportunities, you should use the landline texting service from today. Best landline texting service for business

    ReplyDelete
  8. Hey @chi! I'm a Developer Advocate at Telstra Dev and would love to hear how you've been consuming our API since this post, and if there are any other demos you'd like to see with the API. Please reach out at telstradev@team.telstra.com

    ReplyDelete