So many times we need to send the SMS or OTP(One time password ) to the user mobile number through our application it can be for any purpose like verification your account , message etc and Twilio make this task more easy for us. Today i am going to share the code for send sms using twilio.
Twilio is a cloud communications platforms it makes sending and receiving SMS easy, it works as an SMS provider which will send a password to users that attempt to login with a properly configured security policy. You can integrate Twilio SMS service in your application for sending OTP SMS to authenticate the users.
For this process first thing we need to do is Sign up for a twilio account and we will get –
1. Twillio Account SID
2. Auth token
3. Twilio phone number
Now for the reference i have added some code with retrofit-
Add the retrofit dependency in build.greadle file
1 |
compile 'com.squareup.retrofit2:retrofit:2.1.0' |
we will create a interface for twilio api .
1 2 3 4 5 6 7 8 9 |
interface TwilioApi { @FormUrlEncoded @POST("Accounts/{ACCOUNT_SID}/SMS/Messages") Call<ResponseBody> sendMessage( @Path("ACCOUNT_SID") String accountSId, @Header("Authorization") String signature, @FieldMap Map<String, String> smsdata ); } |
In the above code ACCOUNT_SID is Twillio Account SID and Authorization is basic Authentication which is base64 of account sid and auth token.
To send sms i have passed the url with base authentication here is the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public static final String ACCOUNT_SID = "accountSId"; public static final String AUTH_TOKEN = "authToken"; private void sendMessage() { String body = "Hello test"; String from = "+..."; String to = "+..."; String base64EncodedCredentials = "Basic " + Base64.encodeToString( (ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP ); Map<String, String> smsData = new HashMap<>(); data.put("From", from); data.put("To", to); data.put("Body", body); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.twilio.com/2010-04-01/") .build(); TwilioApi api = retrofit.create(TwilioApi.class); api.sendMessage(ACCOUNT_SID, base64EncodedCredentials, smsData).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) Log.d("TAG", "onResponse->success"); else Log.d("TAG", "onResponse->failure"); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.d("TAG", "onFailure"); } }); } |
In the above code the smsData
contain these perameters-
From – the number from you want to send sms.
To – the number to which you want to send sms
Body – Message you want to send.
If your twilio account is trial account you have to add the test mobile number to the twillio account.
REFERENCE –
you can also refer their integration guide –
https://www.twilio.com/docs/sms
Hope it will help you Thanks for reading.