php

As an outcome of this guide, you will send an SMS message from your handset to a webhook. This will simulate a scenario in which an end user replies to a message and their reply is stored in a third-party application running on PHP.


Prerequisites

Infobip account

• PHP, version 7.2 or greater

Difficulty level

This guide assumes basic knowledge of PHP and basic familiarity with APIs. It is important, however, that you are familiar with the webhook technology and know how to use it for this project.

Summary of the steps

• Buy a number capable of receiving incoming SMS traffic.
• Set up a webhook.
• Add webhook details to the number you’ve purchased.
• Receive an SMS on your webhook.
• Install Infobip API PHP Client.
• Acces webhook with your PHP project.

Buy a number

To buy a number, you’ll need to log into your Infobip account.

  1. Click on the Channels and Numbers icon on the left-hand side menu.
  2. On the Channels Essentials screen click Numbers.
  3. On the Numbers screen, click Buy Number.
  4. Set up filter options to narrow down your choices:
    • Use Filter By Country to select the country you want to test the number in.
    • Use Filter By Capability to select SMS as an option.
  5. Click Buy to finalize the purchase.

Set up a webhook

For experimenting, you could use a simple free tool like Hook Relay, but in this tutorial, we’ll use ngrok so we can write some PHP locally to receive these webhooks.

Step 1. Install ngrok

Install ngrok, then run a PHP server from the directory where that webhook-incoming.php code is sitting.

php -S localhost:8088

Step 2. Point ngrok at your local server

In another CLI session start up ngrok and point it at that server:

ngrok http http://localhost:8088/

Step 3. Generate a URL

The output will give you a URL, such as Forwarding https://d5de-146-90-0-254.eu.ngrok.io -> http://localhost:8088/. Copy the URL to finish setting up your webhook configuration for the number you have purchased from Infobip. In this case, you’ll use the following URL: https://d5de-146-90-0-254.eu.ngrok.io/webhook-incoming.php. We will shortly explain why we’ve added the webhook-incoming.php bit to the URL.

Configure your number with webhook details

Head back to your Infobip account and access your number configuration page (Channels and Numbers > Numbers).

  1. Select the number you’ve purchased and click on Add Keyword to configure forwarding options. You can leave the Keyword field empty.
  2. Use the Forwarding dropdown to select the Forward to HTTP option. This will expand more options to configure.
  3. Select POST for a Method, and JSON as a Format.
  4. Under Forwarding provide the webhook’s URL.
  5. Click Save.

Receive an SMS on your webhook

To test that all we have configured worked as expected, send an SMS from your handset to the number you have purchased. This should trigger an event, and you should see your message in a JSON format arriving at your webhook.

{
  "results": [
    {
      "messageId": "817790313235066447",
      "from": "385916242493",
      "to": "385921004026",
      "text": "QUIZ Correct answer is Paris",
      "cleanText": "Correct answer is Paris",
      "keyword": "QUIZ",
      "receivedAt": "2016-10-06T09:28:39.220+0000",
      "smsCount": 1,
      "price": {
        "pricePerMessage": 0,
        "currency": "EUR"
      },
      "callbackData": "callbackData"
    }
  ],
  "messageCount": 1,
  "pendingMessageCount": 0
}

That JSON can be deserialized and parsed any way you like, but the Infobip PHP SDK can do a lot of the hard work for you. To do that, we’ll need to install the SDK and authenticate Infobip SMS API.

Add Infobip API PHP Client to your project

To use the Infobip API PHP Client in your PHP project, you’ll need to add it to your project composer.json file, either directly or with this convenient command-line shortcut.

composer require infobip/infobip-api-php-client

Create an InfobipConfiguration instance

You’ll use the instance to input your credentials and authenticate Infobip SMS API. Before running the code, don’t forget to replace the placeholders we set in the example below with your account values. You can find your API Key and API Base URL in your Infobip account or on the Infobip API landing page, once logged in.

<?php

const API_KEY_PREFIX = 'App';
const API_KEY = '<your-api-key>';
const URL_BASE_PATH = '<your-base-URL>';

$configuration = (new InfobipConfiguration())
    ->setHost(URL_BASE_PATH)
    ->setApiKeyPrefix('Authorization', API_KEY_PREFIX)
    ->setApiKey('Authorization', API_KEY);

$client = new GuzzleHttpClient();

Now that we’ve got the configuration done, the next step is configuring your project to listen to and catch webhook events.

Intercept a webhook with your local PHP server

Sending a text message to your newly purchased number should mean that a mobile carrier notifies Infobip, Infobip forwards a message to the configured ngrok URL, and that then forwards it to the local PHP server running an appropriate code. Let’s see it in action!

Create a file called webhook-incoming.php in the same directory you just ran the php -S ... and that file will be accessible to ngrok.

<?php

require "vendor/autoload.php";

use InfobipObjectSerializer;

$data = file_get_contents("php://input");

$type = 'InfobipModelSmsInboundMessageResult';
$messages = ObjectSerializer::deserialize($data, $type);

foreach ($messages->getResults() as $message) {
    echo $message->getFrom() . " - " . $message-> getCleanText() . "n";
}

As a result, you should see your project intercepting the webhook event as soon as you send an SMS to the number you have purchased and configured for forwarding.

[Thu Jun 16 09:09:22 2022] 447785374887 - Hello world!
[Thu Jun 16 09:09:22 2022] [::1]:60030 [200]: POST /webhook-incoming.php
[Thu Jun 16 09:09:22 2022] [::1]:60030 Closing

Manually check for incoming messages

Instead of relying on webhooks, you can always manually check for an incoming traffic. You’d probably want to do that in situations where your system went down briefly for a deploy or crashed unexpectedly.

Before running the solution, don’t forget to replace the placeholders we set with your account values. You can find your API Key and API Base URL either in your Infobip account or on the Infobip API landing page once logged in.

use InfobipAPIReceiveSmsApi;

const API_KEY = '<your-api-key>';
const URL_BASE_PATH = '<your-base-URL>';

$configuration = (new InfobipConfiguration())
    ->setHost(URL_BASE_PATH)
    ->setApiKeyPrefix('Authorization', API_KEY_PREFIX)
    ->setApiKey('Authorization', API_KEY);

$client = new GuzzleHttpClient();
$receiveSmsApi = new ReceiveSmsApi($client, $configuration);

try {
    $smsIncoming = $receiveSmsApi->getInboundSmsMessages();
    var_dump($smsIncoming);
} catch (Throwable $apiException) {
    var_dump($apiException);
}

Running this code will show output that looks a bit like this:

object(InfobipModelSmsInboundMessageResult)#44 (1) {
  ["container":protected]=>
  array(3) {
    ["messageCount"]=>
    int(0)
    ["pendingMessageCount"]=>
    int(0)
    ["results"]=>
    array(0) {
    }
  }
}

If there are no messages then job done, you’re fine. If there are some messages, you can process them through the same code that’s found in the webhook, and eventual consistency has been reached.

And that’s basically it! You’re now successfully receiving messages from your customers with confidence.