Posts

Ultimate Guide to send OTP using PHP(Twilio) in 5 minutes?

Are you facing an increase in attempts by spam to gain unauthorized access to your website? Once you’ve launched your website and you haven’t put any spam prevention measure in place. Verification Code allows you to protect your website by adding send sms verification functionality to User Registration functions before the user can see the full content of your website.

Verification Code is used Twilio Networks HTTP API to send messages, meaning you will need a valid Twilio Networks username and password in order to be able to send SMS messages. The account can be obtained from the https://www.twilio.com

Basic Php Integration to Send SMS with Twilio

1. How to Setup Twilio

To send SMS and outgoing messages perform an HTTP POST to the Messages resource URI. We will also use the Twilio PHP Library for making REST requests.

If you are using a Twilio Trial account for this example, you will only be able to send SMS messages to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console’s Verified Caller IDs. The ‘From’ parameter will also need to be a phone number you purchased from Twilio.

Create an account on Twilio.

  • Follow this link for create account on Twilio https://www.twilio.com.
  • If you created trial account on Twilio then you can send SMS to only the verified number of Twilio account.
  • For send SMS on any number you need to create premium account or upgrade the Twilio account.

2. Scheduled SMS campaigns

You’ll be assigned a number when you sign up to Twilio that you can use for testing but can’t send any actual texts through it. We just credited the account straight away so we could see the text coming through live. For us and probably most others we only needed to send a handful of texts whilst testing. As you’ll see further down this write up the library provided by Twilio is super simple and you are only charged when a text is successfully delivered so for the cost of having the convenience of actual messages being delivered to real phones was well worth it.

Sign up for a free Twilio account and buy a phone number.

3. Grab the PHP library and your API credentials

Download the PHP library provided by Twilio and put it somewhere that it can be included in the PHP script you want to use to send the SMS text. When sending your messages you’ll also need your account sid and your Auth Token. These can be grabbed from your account settings.

4. Set up the sending of the message

Firstly include the PHP library you’ve just downloaded and unzipped:

require "PATH YOUR TWILIO LIBRARY/Services/Twilio.php";
$client = new Services_Twilio('ACCOUNT SID HERE', 'AUTHTOKENHERE');

You have to find the your account SID and auth token in your console dashboard, and your phone number in your phone numbers list. Create a file called settings.php to store these values.

 
     $account_sid = "YOURACCOUNTSID";
     $auth_token = "YOURAUTHTOKEN";
     $twilio_phone_number = "+YOURTWILIONUMBER";

Create a file called send-sms.php and paste in the code below to:

  • Include the helper library and settings file
  • Create a Twilio client using our account credentials
  • Create a new message from our twilio number, to our cellphone
require "PATH YOUR TWILIO LIBRARY/Services/Twilio.php";
include 'settings.php';
$client = new Services_Twilio('ACCOUNT SID HERE', 'AUTHTOKENHERE'); 
$client->account->messages->create(array(
  'To' => 'NUMBER OF RECIPIENT',
  'From' => 'NUMBER PURCHASED WITH YOUR ACCOUNT',
  'Body' => "THIS IS YOUR TEXT MESSAGE",
));

Save your file and run it:
php send-sms.php

Conculsion

It’s as easy as that! You’ll now be sending live text messages via PHP and Twilio. You can keep an eye on the outgoing messages via the logs area of your Twilio account area and keep an eye on costs via the usage area.
Following on from that we set the header type text/plain and simply output what we’d like to be text back to the number that has sent the text, Twilio does the rest. That’s sending a text messages and handling a response via a text all wrapped with small amount of code.

References

Twilio Docs
The Twilio Php Helper Library
SEND SMS AND MMS MESSAGES IN PHP

Further Reading

Twilio voice: Receive Call On Your Android Mobile
Easy way to play an audio file on call in android using twilio
How to enable two step verification in Socialengine websites

Twilio voice: Receive Call On Your Android Mobile

Twilio voice is a telephony web-service API that lets you use your existing web languages and skills to build voice and SMS applications. Twilio is a third-party service. Here we have easy steps to receive call using android twilio voice.

Twilio Voice allows your applications to make and receive phone calls. Twilio SMS allows your applications to make and receive SMS messages. Twilio Client allows your applications to enable voice communication using existing Internet connections, including mobile connections.

Building Apps That Talk in the Cloud

Using Twilio Client for Android, developers have access to a few key features that will make building communications apps easy.

  • Real-time Presence – Build buddy lists into any app letting users know who is online and set up notifications when a user is available for voice chat
  • App Backgrounding – The SDK can receive voice calls even when a different app is in use, letting users switch between apps easily to respond to incoming calls.
  • Cross-Platform Interoperability – Twilio Client supports Android, iOS, and web browsers so apps can make calls between any platform, including bridging VoIP calls with traditional phone calls.
  • Voice Over Data and WiFi connections – Make and receive calls over data and WiFi connections without using carrier minutes.

Steps to make call in android Twilio voice

Step 1: Configure your application to use twilio libraries

import com.twilio.client.Connection;
import com.twilio.client.ConnectionListener;
import com.twilio.client.Device;
import com.twilio.client.DeviceListener;
import com.twilio.client.PresenceEvent;
import com.twilio.client.Twilio;
private static final String TOKEN_SERVICE_URL = "your twilio url";

Step 2: Initilizze the twilio sdk

if (!Twilio.isInitialized()) {
    Twilio.initialize(getApplicationContext(), new Twilio.InitListener() {

        /*
         * Now that the SDK is initialized we can register using a Capability Token.
         * A Capability Token is a JSON Web Token (JWT) that specifies how an associated Device
         * can interact with Twilio services.
         */
        @Override
        public void onInitialized() {
            Twilio.setLogLevel(Log.DEBUG);
            /*
             * Retrieve the Capability Token from your own web server
             */
            retrieveCapabilityToken(clientProfile);
        }

        @Override
        public void onError(Exception e) {
            Log.e(TAG, e.toString());
            Toast.makeText(ClientActivity.this, "Failed to initialize the Twilio Client SDK", Toast.LENGTH_LONG).show();
        }
    });
}

Step 3: In this step generate Capability tokens. Capability tokens allow you to add Twilio capabilities to web and mobile applications without exposing your super secret Auth Token in JavaScript or any other client-side environment.

  • Your server provides a Capability Token to each client.
  • Each token contains specific information that enables Twilio to identify that the client belongs to your Twilio account, and what permissions (‘capabilities’) you have granted this user.
Uri.Builder b = Uri.parse(TOKEN_SERVICE_URL).buildUpon();
if (newClientProfile.isAllowOutgoing()) {
    b.appendQueryParameter("allowOutgoing", newClientProfile.allowOutgoing ? "true" : "false");
}
if (newClientProfile.isAllowIncoming() && newClientProfile.getName() != null) {
    b.appendQueryParameter("client", newClientProfile.getName());
}

Ion.with(getApplicationContext())
        .load(b.toString())
        .asString()
        .setCallback(new FutureCallback<String>() {
            @Override
            public void onCompleted(Exception e, String capabilityToken) {
                if (e == null) {
                    Log.d(TAG, capabilityToken);

                    // Update the current Client Profile to represent current properties
                    ClientActivity.this.clientProfile = newClientProfile;

                    // Create a Device with the Capability Token
                    createDevice(capabilityToken);
                } else {
                    Log.e(TAG, "Error retrieving token: " + e.toString());
                    Toast.makeText(ClientActivity.this, "Error retrieving token", Toast.LENGTH_SHORT).show();
                }
            }
        });

Making an HTTP request to the /token endpoint of the web-server returns a Capability Token, which, when provided to a Device constructor, grants the new Device capabilities such as making outgoing calls or allowing incoming calls.

Conclusion

If you want to implement android twilio voice call in your project then you will find these steps more easy. Implementation of android twilio voice has very easy steps as described above. You can edit the xml and activity files in your own way to make it more attractive as per your requirements.

Go to Call android using twilio voice Example on Github

Refrences

Twilio : Twilio documentation that gives the information about twilio.

Android : Android document that gives the information about android that is useful for developer.