Sample Code – Send Text using PHP
So you are a PHP guru or maybe just getting started and you want to do something out of the ordinary by allowing your app to communicate with users real time. You could build an app for an event promoter that sends texts every Friday/Saturday evening promoting an event and even handle text responses or you could just build an app that texts your friends once a week to stay in touch.
To send a text programmatically your code needs to make an XHR request to an SMS gateway that will read the text details from your request and then initiate a text to the recipient’s phone number
PureText offers a Texting/SMS gateway to which you can make an HTTP GET/POST request with details such as recipient number and body of the text and PureText will deliver the text to the recipient for you.
In order to identify that this request belongs to you, you’ll need to include your API token in the HTTP GET/POST request. Register for a free API token here
A thing to note is that you cannot just use any phone number as the ‘From’ number. The rule of thumb is the number must be registered through the same company who’s SMS gateway you choose to use.
To send a text message using Node.js you don’t need a dedicated short code. Dedicated short codes are expensive and take 2-3 months to get approved, instead, you can now use local 10 digit VOIP numbers or also referred to as long codes to send a text/SMS programmatically from your Node.js app
So let’s get started, to do a quick and dirty POC you’ll need:
- An API token key (free API token here)
- A ‘From’ number through your SMS gateway (Get a free one here)
Copy Paste the following code in your IDE and replace the apiToken and fromNumber values with the API token you will see in your dashboard and the number you will or have reserved on the numbers page in PureText
//API Url $url = 'http://api.puretext.us/service/sms/send'; //Initiate cURL. $ch = curl_init($url); //The JSON data. $jsonData = array( 'apiToken' => 'XXXXX', //Sign up for an account to get an API Token 'fromNumber' => '+14703497270' // From number is the number you choose after signing up 'toNumber' => '+X-XXX-XXX-XXXX', // To Number is the number you will be sending the text to 'smsBody' => 'SENDING TEXT USING PHP', // Text Content ); //Encode the array into JSON. $jsonDataEncoded = json_encode($jsonData); //Tell cURL that we want to send a POST request. curl_setopt($ch, CURLOPT_POST, 1); //Attach our encoded JSON string to the POST fields. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); //Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //Execute the request $result = curl_exec($ch); echo $result;