Skip to content

Latest commit

 

History

History
77 lines (63 loc) · 2.51 KB

02.subscriptions.md

File metadata and controls

77 lines (63 loc) · 2.51 KB

Subscriptions

Subscribe to Events

This example demonstrates how to subscribe to inbound text events. The same code applies to subscribing to any other type of events, with the TriggerEvent parameter changed appropriately.

<?php
use CallFire\Api\Rest\Request;
use CallFire\Api\Rest\Response;
require 'vendor/autoload.php';

$client = CallFire\Api\Client::Rest("<api-login>", "<api-password>", "Subscription");

$request = new Request\CreateSubscription;
$request->setEndpoint('http://example.com/subscribe.php');
$request->setNotificationFormat($client::FORMAT_XML);
$request->setTriggerEvent($client::EVENT_INBOUND_TEXT_FINISHED);

$response = $client->CreateSubscription($request);
$result = $client::response($response);
if($result instanceof ResourceReference) {
    // Success
}

Receive Events

This script would live at the http://example.com/subscribe.php URL referenced in the event subscription examples. Please note that the POST data is received in its unprocessed format, as subscription event data is not posted in normal key-value pair format. It is more akin to a PUT request.

Although it is not described here, it is recommended that you place a unique, secure token in your subscription URLs, and verify it in your subscription scripts, so as to avoid event forgery - unintentional or otherwise.

<?php
use CallFire\Common\Subscription;
require 'vendor/autoload.php';

$postData = file_get_contents('php://input'); // Collect raw input data
if(!($format = Subscription::is_event_request())) {
    // This request does not conform to what an event notification looks like
    exit;
}
if(!($event = Subscription::event($postData, $format))) {
    // This is not an event
    exit;
}

switch(true) {
    case $event instanceof Subscription\TextNotification:
        $text = $event->getText();
        $fromNumber = $text->getFromNumber();
        $message = $text->getMessage();
        $created = $text->getCreated();
        $logMessage = "[{$created}] {$fromNumber}: {$message}";
        
        file_put_contents(__DIR__.'/text-messages.log', $logMessage.PHP_EOL, FILE_APPEND);
        break;
    case $event instanceof Subscription\CallFinished:
        $call = $event->getCall();
        $fromNumber = $text->getFromNumber();
        $created = $text->getCreated();
        $logMessage = "[{$created}] {$fromNumber}";
        
        file_put_contents(__DIR__.'/finished-calls.log', $logMessage.PHP_EOL, FILE_APPEND);
        break;
    default:
        throw new Exception('Unknown event type');
}