Navbar
  • Guides
  • REST APIs
  • SDKs Reference
  • Compatibility API
  • Log In
  • Sign Up
  • Relay SDK for PHP
  • API Reference
  • Examples
  • Relay SDK for PHP

    Getting Started

    The Relay SDK for PHP enables PHP developers to connect and use SignalWire's Relay APIs within their own PHP code. Our Relay SDK allows developers to build or add robust and innovative communication services to their applications.

    The Relay SDK for PHP is easy to use and only takes a few minute to setup and get running.

    THIS PACKAGE IS NOT ACTIVELY MAINTAINED ANYMORE
    Visit the community-led fork for new updates to the PHP library, including compatibility with PHP 8.

    Latest Version:

    Source Code: signalwire/signalwire-php

    Support: SignalWire Community Slack Channel

    Installation

    Install the package using Composer:

    composer require signalwire/signalwire
    

    Minimum Requirements

    The PHP SDK requires PHP 7.1 or greater installed on your system.

    Using the SDK

    The PHP SDK can be used to get up and running with Relay quickly and easily. In order to use the PHP client, you must get your project and token from your SignalWire dashboard.

    There are a few ways to get started, depending on your needs: Relay.Consumer, Relay.Task, and Relay.Client.

    Relay Consumer

    A Relay.Consumer creates a long running process, allowing you to respond to incoming requests and events in realtime. Relay Consumers abstract all the setup of connecting to Relay and automatically dispatches workers to handle requests; so you can concentrate on writing your code without having to worry about multi-threading or blocking, everything just works. Think of Relay Consumers like a background worker system for all your calling and messaging needs.

    Relay Consumers can scale easily, simply by running multiple instances of your Relay.Consumer process. Each event will only be delivered to a single consumer, so as your volume increases, just scale up! This process works well whether you are using Docker Swarm, a Procfile on Heroku, your own webserver, and most other environments.

    Setting up a new consumer is the easiest way to get up and running.

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    use SignalWire\Relay\Consumer;
    
    class CustomConsumer extends Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['home', 'office'];
    
      public function ready(): Coroutine {
        yield;
        // Consumer is successfully connected with Relay.
        // You can make calls or send messages here..
      }
    
      public function onIncomingCall($call): Coroutine {
        $result = yield $call->answer();
        if ($result->isSuccessful()) {
          yield $call->playTTS(['text' => 'Welcome to SignalWire!']);
        }
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    Learn more about Relay Consumers

    Relay Task

    A Relay.Task is simple way to send jobs to your Relay.Consumers from a short lived process, like a web framework. Relay Tasks allow you to pass commands down to your Consumers without blocking your short lived request. Think of a Relay Task as a way to queue a job for your background workers to processes asynchronously.

    For example, if you wanted to make an outbound call and play a message when your user clicks a button on your web application, since Relay is a realtime protocol and relies on you to tell it what to do in realtime, if you did this within your web application, your web server would block until the call was finished... this may take a long time! Instead, simply create a new Relay Task. This task will be handled by a running Relay Consumer process and your web application can respond back to your user immediately.

    Send a task in the office context with custom data.

    // create-task.php
    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use SignalWire\Relay\Tasking\Task;
    
    $task = new Task('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
    $context = 'office';
    $delivered = $task->deliver($context, [
      'uuid' => 'unique id',
      'data' => 'data for your job'
    ]);
    

    Handle the task in a Consumer.

    // consumer-task.php
    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['office']; // Task is delivered on the "office" context!
    
      public function onTask($message): Coroutine {
        yield;
        // Retrieve your custom properties in $message..
        echo $message->uuid; // 'unique id'
        echo $message->data; // 'data for your job'
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    Learn more about Relay Tasks

    Relay Client

    Relay.Client is a lower level object, giving you a basic connection to Relay but that is all. It is best used when you are creating a script only concerned with sending outbound requests or you want complete control over the Relay connection yourself.

    Setting up a new client and make an outbound call.

    <?php
    
    $client = new SignalWire\Relay\Client([
      'project' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      'token' => 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    ]);
    
    $client->on('signalwire.ready', function($client) {
    
      $params = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
      $client->calling->dial($params)->done(function($result) {
        if ($result->isSuccessful()) {
          // Your active $call..
          $call = $result->getCall();
        }
      });
    
    });
    
    $client->connect();
    

    Learn more about Relay Clients

    Contexts

    Relay uses Contexts as a simple way to separate events to specific consumers, allowing you to write consumers for specific types of calls or messages or scale them independently. A Context is simply a named string, that allows you to categorize requests. When creating outbound requests, or configuring phone numbers for inbound requests, you can specify the context; Relay will then deliver that call or event to Consumers that are configured to listen for that context.

    For example, you could have a customer support phone number configured to send to Relay with the support context, and a personal number configured with personal context. Relay would deliver these events to any Consumer listening for those contexts. This gives you a lot of control in how messages are delivered to your Consumers, allowing you to write Consumer classes specific to the context, scale them independently, or separate traffic based on your own business rules.

    API Reference

    Relay.Client

    Relay.Client is the basic connection to Relay, allowing you send commands to Relay and setup handlers for inbound events.

    Constructor

    Constructs a client object to interact with Relay.

    Parameters

    project string required Project ID from your SignalWire Space
    token string required Token from your SignalWire Space

    Examples

    Create a Client to interact with the Relay API.

    <?php
    
    $client = new SignalWire\Relay\Client([
      'project' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
      'token' => 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    ]);
    

    Properties

    calling Relay.Calling Returns a Relay.Calling instance associated with the client.

    Methods

    connect

    Activates the connection to the Relay API. The connection to Relay does not happen automatically so that you can setup handlers to events that might occur before the connection is successfully established.

    Available In:

    Returns

    void

    Examples

    <?php
    
    $client->connect();
    

    disconnect

    Disconnect the client from Relay.

    Available In:

    Returns

    void

    Examples

    <?php
    
    $client->disconnect();
    

    on

    Attach an event handler for a specific type of event.

    Available In:

    Parameters

    $event string required Event name. Full list of events Relay.Client Events
    $callback function required Callable to invoke when the event comes.

    Returns

    Relay.Client - The client object itself.

    Examples

    Subscribe to the signalwire.ready and signalwire.error events.

    <?php
    
    $client->on('signalwire.ready', function($client) {
      // Your client is ready!
    })->on('signalwire.error', function(\Exception $error) {
      // Got an error...
    });
    

    off

    Remove an event handler that were attached with .on(). If no handler parameter is passed, all listeners for that event will be removed.

    Parameters

    $event string required Event name. Full list of events Relay.Client Events
    $callback function optional Callable to remove.
    Note: $callback will be removed from the stack by reference so make sure to use the same reference in both .on() and .off() methods.

    Returns

    Relay.Client - The client object itself.

    Examples

    Subscribe to the signalwire.error and then, remove the event handler.

    <?php
    
    $errorHandler = function($error) {
      // Log the error..
    };
    
    $client->on('signalwire.error', $errorHandler);
    
    // .. later
    $client->off('signalwire.error', $errorHandler);
    

    Events

    All available events you can attach a listener on.

    signalwire.ready The session has been established and all other methods can now be used.
    signalwire.error There is an error dispatch at the session level.
    signalwire.socket.open The websocket is open. However, you have not yet been authenticated.
    signalwire.socket.error The websocket gave an error.
    signalwire.socket.message The client has received a message from the websocket.
    signalwire.socket.close The websocket is closing.

    Relay.Calling

    This represents the API interface for the Calling Relay Service. This object is used to make requests related to managing end to end calls.

    Methods

    dial

    Make an outbound Call and waits until it has been answered or hung up.

    Available In:

    Parameters

    $params array required Array with the following properties:
    type string required The type of call. Only phone is currently supported.
    from string required The party the call is coming from.
    Must be a SignalWire number or SIP endpoint that you own.
    to string required The party you are attempting to call.
    timeout number optional The time, in seconds, the call will ring before going to voicemail.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DialResult object.

    Examples

    Make an outbound Call and grab the call object if it was answered.

    <?php
    
    $params = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
    $client->calling->dial($params)->done(function($dialResult) {
      if ($dialResult->isSuccessful()) {
        // Your active $call..
        $call = $dialResult->getCall();
      }
    });
    

    newCall

    Create a new Call object. The call has not started yet allowing you to attach event listeners on it.

    Available In:

    Parameters

    See Relay.Calling.Dial for the parameter list.

    Returns

    Call - A new Relay.Calling.Call object.

    Examples

    Create a new Call object.

    <?php
    
    $params = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
    $call = $client->calling->newCall($params);
    // Use the $call object...
    

    Relay.Calling.AnswerResult

    This object returned from the answer method.

    Methods

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Start recording in stereo mode and grab the result when it's completed.

    <?php
    
    $call->answer()->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    isSuccessful

    Return true if the call was answered without errors, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - Whether the call has been answered successfully.

    Examples

    Start the recording and then check if it has ended successfully.

    <?php
    
    $call->answer()->done(function($result) {
      if ($result->isSuccessful()) {
        // $call is now active...
      }
    });
    

    Relay.Calling.Call

    All calls in SignalWire have a common generic interface, Call. A Call is a connection between SignalWire and another device.

    Properties

    id string The unique identifier of the call.
    type string The type of call. Only phone is currently supported.
    from string The phone number that the call is coming from.
    to string The phone number you are attempting to call.
    timeout number The seconds the call rings before being transferred to voicemail.
    state string The current state of the call. See Relay.Calling.Call State Events for all the possible call states.
    prevState string The previous state of the call.
    context string The context the call belongs to.
    peer Relay.Calling.Call The call your original call is connected to.
    active boolean Whether the call is active.
    ended boolean Whether the call has ended.
    answered boolean Whether the call has been answered.
    failed boolean Whether the call has failed.
    busy boolean Whether the call was busy.

    Methods

    amd

    Alias for detectAnsweringMachine.

    amdAsync

    Alias for detectAnsweringMachineAsync.

    answer

    Answer an inbound call.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.AnswerResult object.

    Examples

    Answer an inbound call and check if it was successful.

    <?php
    
    $call->answer()->done(function($answerResult) {
    
    });
    

    connect

    Attempt to connect an existing call to a new outbound call and waits until one of the remote party picks the call or the connect fails.
    This method involves complex nested parameters. You can connect to multiple devices in series, parallel, or any combination of both with creative use of the parameters. Series implies one device at a time, while parallel implies multiple devices at the same time.

    Available In:

    Parameters

    $params array required Array with the following properties:
    devices array required One or more arrays with the structure below.
    Nested depends on whether to dial in serial or parallel.
    ringback array optional Ringback audio to play to call leg. You can play audio, tts, silence or ringtone. See play media parameter for details.
    • Structure of a device:
    type string required The device type. Only phone is currently supported.
    from string optional The party the call is coming from.
    If not provided, the SDK will use the from of the originator call.
    Must be a SignalWire number or SIP endpoint that you own.
    to string required The party you are attempting to connect with.
    timeout number optional The time, in seconds, the call will ring before going to voicemail.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.ConnectResult object.

    Examples

    Try connecting by calling +18991114444 and +18991114445 in series.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connect(...$devices)->done(function($connectResult) {
      if ($connectResult->isSuccessful()) {
        $remoteCall = $connectResult->getCall();
      }
    });
    

    Combine serial and parallel calling. Call +18991114443 first and - if it doesn't answer - try calling in parallel +18991114444 and +18991114445. If none of the devices answer, continue the same process with +18991114446 and +18991114447.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114443", "timeout" => 30 ],
      [
        [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
        [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
      ],
      [
        [ "type" => "phone", "to" => "+18991114446", "timeout" => 30 ],
        [ "type" => "phone", "to" => "+18991114447", "timeout" => 20 ]
      ]
    ];
    $call->connect(...$devices)->done(function($connectResult) {
      if ($connectResult->isSuccessful()) {
        $remoteCall = $connectResult->getCall();
      }
    });
    

    Try connecting by calling +18991114444 and +18991114445 in series playing the US ringtone.

    <?php
    
    $params = [
      "devices" => [
        [ "type" => "phone", "to" => "+18991114444" ],
        [ "type" => "phone", "to" => "+18991114445" ]
      ],
      "ringback" => [ "type" => "ringtone", "name" => "us" ]
    ];
    $call->connect(...$devices)->done(function($connectResult) {
      if ($connectResult->isSuccessful()) {
        $remoteCall = $connectResult->getCall();
      }
    });
    

    connectAsync

    Asynchronous version of connect. It does not wait the connect to completes or fails but returns a Relay.Calling.ConnectAction you can interact with.

    Available In:

    Parameters

    See connect for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.ConnectAction object.

    Examples

    Trying to connect a call by calling in series +18991114444 and +18991114445.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connect(...$devices)->done(function($connectAction) {
      // .. do other important things while Relay try to connect your call..
    
      // then check whether the action has completed
      if ($connectAction->isCompleted()) {
    
      }
    });
    

    detect

    Start a detector on the call and waits until it has finished or failed.

    The detect method is a generic method for all types of detecting, see detectAnsweringMachine, detectDigit or detectFax for more specific usage.

    Available In:

    Parameters

    $params array required Array with the following properties:
    • To detect an answering machine:
    type string required machine
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.
    • To detect digits:
    type string required digit
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    digits string optional The digits to detect.
    Defaults to "0123456789#*".
    • To detect a fax:
    type string required fax
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    tone string optional The fax tone to detect: CED or CNG.
    Defaults to "CED".

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

    Examples

    Detect a machine with custom parameters and timeout.

    <?php
    
    $params = [
      'type' => 'machine',
      'timeout' => 45,
      'initial_timeout' => 3.0
    ];
    $call->detect($params)->done(function($detectResult) {
      if ($detectResult->isSuccessful()) {
        $type = $detectResult->getType(); // machine
        $result = $detectResult->getResult(); // MACHINE / HUMAN / UNKNOWN
      }
    });
    

    Detect a Fax setting timeout only.

    <?php
    
    $params = [
      'type' => 'fax',
      'timeout' => 45
    ];
    $call->detect($params)->done(function($detectResult) {
      if ($detectResult->isSuccessful()) {
    
      }
    });
    

    detectAsync

    Asynchronous version of detect. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

    Available In:

    Parameters

    See detect for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

    Examples

    Detect digits using default parameters. Stop the action immediately.

    <?php
    
    $call->on('detect.update', function ($call, $params) {
      // Handle a detector event here..
      print_r($params);
    });
    $call->detectAsync([ 'type' => 'digit' ])->done(function ($detectAction) {
      // Do other things while detector runs and then stop it.
      if (!$detectAction->isCompleted()) {
        $detectAction->stop();
      }
    });
    

    detectAnsweringMachine

    This is a helper function that refines the use of detect. The Promise will be resolved with a Relay.Calling.DetectResult object as soon as the detector decided who answered the call: MACHINE, HUMAN or UNKNOWN.

    Available In:

    Parameters

    $params array optional Array with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

    Examples

    Perform an AMD and wait until the machine is ready.

    <?php
    
    $params = [
      'wait_for_beep' => true
    ];
    $call->detectAnsweringMachine($params)->done(function($detectResult) {
      if ($detectResult->isSuccessful()) {
        $result = $detectResult->getResult(); // MACHINE || HUMAN || UNKNOWN
      }
    });
    

    detectAnsweringMachineAsync

    Asynchronous version of detectAnsweringMachine. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

    Available In:

    Parameters

    See detectAnsweringMachine for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

    Examples

    Perform an asynchronous AMD on the call. Then stop the action if not completed yet.

    <?php
    
    $call->on('detect.update', function ($call, $params) {
      // Handle a detector event here..
      print_r($params);
    });
    $call->detectAnsweringMachineAsync()->done(function ($detectAction) {
      // Do other things while detector runs and then stop it.
      if (!$detectAction->isCompleted()) {
        $detectAction->stop();
      }
    });
    

    detectDigit

    This is a helper function that refines the use of detect. This simplifies detecting digits on a call.

    Available In:

    Parameters

    $params array optional Array with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    digits string optional The digits to detect.
    Defaults to "0123456789#*".

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

    Examples

    Detect digits and then write a log with the result.

    <?php
    
    $call->detectDigit()->done(function($detectResult) {
      if ($detectResult->isSuccessful()) {
        echo "Digits detected: " . $detectResult->getResult();
      }
    });
    

    detectDigitAsync

    Asynchronous version of detectDigit. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

    Available In:

    Parameters

    See detectDigit for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

    Examples

    Detect only 1-3 digits asynchronously.

    <?php
    
    $call->on('detect.update', function ($call, $params) {
      // Handle a detector event here..
      print_r($params);
    });
    $call->detectDigitAsync([ 'digits' => '123' ])->done(function ($detectAction) {
      // Do other things while detector runs and then stop it.
      if (!$detectAction->isCompleted()) {
        $detectAction->stop();
      }
    });
    

    detectFax

    This is a helper function that refines the use of detect. This simplifies detecting a fax.

    Available In:

    Parameters

    $params array optional Array with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    tone string optional The fax tone to detect: CED or CNG.
    Defaults to "CED".

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

    Examples

    Detect fax on the current call.

    <?php
    
    $call->detectFax()->done(function($detectResult) {
      if ($detectResult->isSuccessful()) {
        // A fax has been detected!
      }
    });
    

    detectFaxAsync

    Asynchronous version of detectFax. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

    Available In:

    Parameters

    See detectFax for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

    Examples

    Detect fax on the current call. Stop the action immediately.

    <?php
    
    $call->on('detect.update', function ($call, $params) {
      // Handle a detector event here..
      print_r($params);
    });
    $call->detectFaxAsync()->done(function ($detectAction) {
      // Do other things while detector runs and then stop it.
      if (!$detectAction->isCompleted()) {
        $detectAction->stop();
      }
    });
    

    detectHuman

    This is a helper function that refines the use of detect. This simplifies detecting a human on the call and is the inverse of detectMachine.

    Deprecated since: Use detectAnsweringMachine instead.

    Parameters

    $params array optional Array with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

    Examples

    Detect a human on the current call.

    <?php
    
    $call->detectHuman()->done(function($detectResult) {
      if ($detectResult->isSuccessful()) {
        // A human has been detected!
      }
    });
    

    detectHumanAsync

    Asynchronous version of detectHuman. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

    Deprecated since: Use detectAnsweringMachineAsync instead.

    Parameters

    See detectHuman for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

    Examples

    Detect a human on the current call. Stop the action immediately.

    <?php
    
    $call->detectHumanAsync()->done(function ($detectAction) {
      // For demonstration purposes only..
      $detectAction->stop();
    });
    

    detectMachine

    This is a helper function that refines the use of detect. This simplifies detecting a machine on the call and is the inverse of detectHuman.

    Deprecated since: Use detectAnsweringMachine instead.

    Parameters

    $params array optional Array with the following properties:
    timeout number optional Number of seconds to run the detector.
    Defaults to 30.0.
    wait_for_beep boolean optional Whether to wait until the AM is ready for voicemail delivery.
    Defaults to false.
    initial_timeout number optional Number of seconds to wait for initial voice before giving up.
    Defaults to 4.5.
    end_silence_timeout number optional Number of seconds to wait for voice to finish.
    Defaults to 1.0.
    machine_voice_threshold number optional How many seconds of voice to decide is a machine.
    Defaults to 1.25.
    machine_words_threshold number optional How many words to count to decide is a machine.
    Defaults to 6.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectResult object.

    Examples

    Detect a machine on the current call.

    <?php
    
    $call->detectMachine()->done(function($detectResult) {
      if ($detectResult->isSuccessful()) {
        // A machine has been detected!
      }
    });
    

    detectMachineAsync

    Asynchronous version of detectMachine. It does not wait the detector ends but returns a Relay.Calling.DetectAction you can interact with.

    Deprecated since: Use detectAnsweringMachineAsync instead.

    Parameters

    See detectMachine for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DetectAction object.

    Examples

    Detect a machine on the current call. Stop the action immediately.

    <?php
    
    $call->detectMachineAsync()->done(function ($detectAction) {
      // For demonstration purposes only..
      $detectAction->stop();
    });
    

    dial

    This will start a call that was created with newCall and waits until the Call has been answered or hung up.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.DialResult object.

    Examples

    <?php
    
    $call->dial()->done(function($dialResult) {
    
    });
    

    faxReceive

    Prepare the call to receive an inbound fax. It waits until the fax has been received or failed.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.FaxResult object.

    Examples

    Receiving a fax on the call and print logs for URL and number of received pages.

    <?php
    
    $call->faxReceive()->done(function($faxResult) {
      echo 'URL: ' . $faxResult->getDocument() . PHP_EOL;
      echo 'Total pages: ' . $faxResult->getPages();
    });
    

    faxReceiveAsync

    Asynchronous version of faxReceive. It does not wait the fax to be received but returns Relay.Calling.FaxAction you can interact with.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.FaxAction object.

    Examples

    Trying to receive a fax and then stop it.

    <?php
    
    $call->faxReceiveAsync()->done(function ($faxAction) {
      // For demonstration purposes only..
      $faxAction->stop();
    });
    

    faxSend

    Send a fax through the call. It waits until the fax has been sent or failed.

    Available In:

    Parameters

    $document string required Http(s) URL to the document to send.
    PDF format only.
    $identity string optional Identity to display on receiving fax.
    Defaults to SignalWire DID.
    $header string optional Custom string to add to header of each fax page.
    Set to empty string to disable sending any header.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.FaxResult object.

    Examples

    Sending a fax on the call and print logs the number of sent pages.

    <?php
    
    $call->faxSend('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', null, 'Custom Header')->done(function($faxResult) {
      echo "\n URL: " . $faxResult->getDocument();
      echo "\n Total pages: " . $faxResult->getPages();
    });
    

    faxSendAsync

    Asynchronous version of faxSend. It does not wait the fax to be sent but returns a Relay.Calling.FaxAction you can interact with.

    Available In:

    Parameters

    See faxSend for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.FaxAction object.

    Examples

    Trying to send a fax and then stop it.

    <?php
    
    $call->faxSendAsync('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', null, 'Custom Header')->done(function ($faxAction) {
      // For demonstration purposes only..
      $faxAction->stop();
    });
    

    hangup

    Hangup the call.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.HangupResult object.

    Examples

    Hangup the current call and check if it was successful.

    <?php
    
    $call->hangup()->done(function($hangupResult) {
      if ($hangupResult->isSuccessful()) {
    
      }
    });
    

    on

    Attach an event handler for the event.

    Available In:

    Parameters

    $event string required Event name. Full list of events Relay.Calling.Call Events
    $handler callable required Handler to call when the event comes.

    Returns

    Relay.Calling.Call - The call object itself.

    Examples

    Subscribe to the answered and ended events for a given call.

    <?php
    
    $call->on('ended', function($call) {
      // Call has ended.. cleanup something?
    });
    

    off

    Remove an event handler that were attached with the on method. If you don't pass a $handler, all listeners for that event will be removed.

    Available In:

    Parameters

    $event string required Event name. Full list of events Relay.Calling.Call Events
    $handler callable optional Handler to remove.
    Note: $handler will be removed from the stack by reference so make sure to use the same reference in both on and off methods.

    Returns

    Relay.Calling.Call - The call object itself.

    Examples

    Subscribe to the call ended state change and then, remove the event handler.

    <?php
    
    $callback = function($call) {
      // Call has ended.
    };
    
    $call->on('ended', $callback);
    
    // .. later
    $call->off('ended', $callback);
    

    play

    Play one or multiple media in a call and waits until the playing has ended.

    The play method is a generic method for all types of playing, see playAudio, playSilence, playTTS or playRingtone for more specific usage.

    Available In:

    Parameters

    $params array required Array with the following properties:
    media array required List of media elements to play. See below for each type.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.
    • To play an audio file:
    type string required audio
    url string required Http(s) URL to audio resource to play.
    • To play a text to speech string:
    type string required tts
    text string required TTS to play.
    language string optional Default to en-US.
    gender string optional male or female. Default to female.
    • To play silence:
    type string required silence
    duration number required Seconds of silence to play.
    • To play ringtone:
    type string required ringtone
    name string required The name of the ringtone. See ringtones for the supported values.
    duration number optional Duration of ringtone to play.
    Default to 1 ringtone iteration.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

    Examples

    Play multiple media elements in the call.

    <?php
    
    $params = [
      'media' => [
        [ "type" => "tts", "text" => "Listen this awesome file!" ],
        [ "type" => "audio", "url" => "https://example.domain.com/audio.mp3" ],
        [ "type" => "silence", "duration" => 5 ],
        [ "type" => "tts", "text" => "Did you like it?" ]
      ],
      'volume' => 4.0
    ];
    $call->play($params)->done(function ($playResult) {
      if ($playResult->isSuccessful()) {
    
      }
    });
    

    playAsync

    Asynchronous version of play. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

    Available In:

    Parameters

    See play for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

    Examples

    Play multiple media elements in the call and then stop it.

    <?php
    
    $params = [
      'media' => [
        [ "type" => "tts", "text" => "Listen this awesome file!" ],
        [ "type" => "audio", "url" => "https://example.domain.com/audio.mp3" ],
        [ "type" => "silence", "duration" => 5 ],
        [ "type" => "tts", "text" => "Did you like it?" ]
      ],
      'volume' => 4.0
    ];
    $call->playAsync($params)->done(function ($playAction) {
      // For demonstration purposes only..
      $playAction->stop();
    });
    

    playAudio

    This is a helper function that refines the use of play. This simplifies playing an audio file.

    Available In:

    Parameters

    $params array required Array with the following properties:
    url string required Http(s) URL to audio resource to play.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

    Examples

    Play an Mp3 file using the signature with a string as parameter.

    <?php
    
    $call->playAudio('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($playResult) {
      // interact with $playResult..
    });
    

    Play an Mp3 file setting volume level to 4dB. Require v2.3+

    <?php
    
    $params = [
      'url' => 'https://cdn.signalwire.com/default-music/welcome.mp3',
      'volume' => 4.0
    ];
    $call->playAudio($params)->done(function($playResult) {
      // interact with $playResult..
    });
    

    playAudioAsync

    Asynchronous version of playAudio. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

    Available In:

    Parameters

    See playAudio for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

    Examples

    Play an Mp3 file and stop it after 5 seconds.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($playAction) {
      // For demonstration purposes only..
      $playAction->stop();
    });
    

    Play an Mp3 file setting the volume and stop it after 5 seconds.

    <?php
    
    $params = [
      'url' => 'https://cdn.signalwire.com/default-music/welcome.mp3',
      'volume' => 4.0
    ];
    $call->playAudioAsync($params)->done(function($playAction) {
      // For demonstration purposes only..
      $playAction->stop();
    });
    

    playRingtone

    This is a helper function that refines the use of play. This simplifies play a ringtone.

    Available In:

    Parameters

    $params array required Array with the following properties:
    name string required The name of the ringtone. See ringtones for the supported values.
    duration number optional Duration of ringtone to play.
    Default to 1 ringtone iteration.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

    Examples

    Play a single US ringtone.

    <?php
    
    $params = [ 'name' => 'us' ];
    $call->playRingtone($params)->done(function($playResult) {
      // interact with $playResult..
    });
    

    playRingtoneAsync

    Asynchronous version of playRingtone. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

    Available In:

    Parameters

    See playRingtone for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

    Examples

    Play US ringtone for 30 seconds, if Agent is available, stop the play.

    <?php
    
    $params = [ 'name' => 'us', 'duration' => 30 ];
    $call->playRingtoneAsync($params)->done(function($playAction) use ($globalAgent) {
      // For demonstration purposes only ..
      if ($globalAgent->isAvailable()) {
        $playAction->stop();
      }
    });
    

    playSilence

    This is a helper function that refines the use of play. This simplifies playing silence.

    Available In:

    Parameters

    $duration number required Seconds of silence to play.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

    Examples

    Play silence for 10 seconds.

    <?php
    
    $call->playSilence(10)->done(function($playResult) {
      // interact with $playResult..
    });
    

    playSilenceAsync

    Asynchronous version of playSilence. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

    Available In:

    Parameters

    See playSilence for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

    Examples

    Play silence for 60 seconds, if Agent is available, stop the play.

    <?php
    
    $call->playSilenceAsync(60)->done(function($playAction) use ($globalAgent) {
      // For demonstration purposes only ..
      if ($globalAgent->isAvailable()) {
        $playAction->stop();
      }
    });
    

    playTTS

    This is a helper function that refines the use of play. This simplifies playing TTS.

    Available In:

    Parameters

    $params array required Array with the following properties:
    text string required TTS to play.
    language string optional Default to en-US.
    gender string optional male or female. Default to female.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayResult object.

    Examples

    Play TTS.

    <?php
    
    $params = [ 'text' => 'Welcome to SignalWire!' ];
    $call->playTTS($params)->done(function($playResult) {
      // interact with $playResult..
    });
    

    playTTSAsync

    Asynchronous version of playTTS. It does not wait the playing to completes but returns a Relay.Calling.PlayAction you can interact with.

    Available In:

    Parameters

    See playTTS for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayAction object.

    Examples

    Play TTS and stop it after 5 seconds.

    <?php
    
    $params = [ 'text' => 'Welcome to SignalWire!' ];
    $call->playTTSAsync($params)->done(function($playAction) {
      // interact with $playAction..
    
      $playAction->stop();
    });
    

    prompt

    Play one or multiple media while collecting user's input from the call at the same time, such as digits and speech.

    It waits until the collection succeed or timeout is reached.

    The prompt method is a generic method, see promptAudio, promptTTS or promptRingtone for more specific usage.

    Available In:

    Parameters

    $collect array required Array with the following properties:
    type string required digits, speech or both.
    media array required List of media elements to play. See play for the array structure.
    initial_timeout number optional Initial timeout in seconds.
    Default to 4 seconds.
    volume number optional Volume value between -40dB and +40dB where 0 is unchanged.
    Default is 0.
    • To collect digits:
    digits_max number required Max digits to collect.
    digits_terminators string optional DTMF digits that will end the recording.
    Default not set.
    digits_timeout number optional Timeout in seconds between each digit.
    • To collect speech:
    end_silence_timeout number optional How much silence to wait for end of speech.
    Default to 1 second.
    speech_timeout number optional Maximum time to collect speech.
    Default to 60 seconds.
    speech_language string optional Language to detect.
    Default to en-US.
    speech_hints array optional Array of expected phrases to detect.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

    Examples

    Ask user to enter their PIN and collect the digits.

    <?php
    
    $mediaToPlay = [
      ['type' => 'tts', 'text' => 'Welcome at SignalWire. Please, enter your PIN and then # to proceed']
    ];
    $collect = [
      'type' => 'digits',
      'digits_max' => 4,
      'digits_terminators' => '#',
      'media' => $mediaToPlay
    ];
    $call->prompt($collect)->done(function($promptResult) {
      if ($promptResult->isSuccessful()) {
        $type = $promptResult->getType(); // => digit
        $pin = $promptResult->getResult(); // => pin entered by the user
      }
    });
    

    promptAsync

    Asynchronous version of prompt. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

    Available In:

    Parameters

    See prompt for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

    Examples

    Ask user to enter their PIN and collect the digits.

    <?php
    
    $mediaToPlay = [
      ['type' => 'tts', 'text' => 'Welcome at SignalWire. Please, enter your PIN and then # to proceed']
    ];
    $collect = [
      'type' => 'digits',
      'digits_max' => 4,
      'digits_terminators' => '#',
      'media' => $mediaToPlay
    ];
    $call->promptAsync($collect, $tts)->done(function($promptAction) {
      // .. do other important things while collecting user digits..
      if ($promptAction->isCompleted()) {
        $promptResult = $promptAction->getResult(); // => Relay.Calling.PromptResult Object
      }
    });
    

    promptAudio

    This is a helper function that refines the use of prompt.
    This function simplifies playing an audio file while collecting user's input from the call, such as digits and speech.

    Available In:

    Parameters

    You can set all the properties that prompt accepts replacing media with:

    url string required Http(s) URL to audio resource to play.

    The SDK will build the media for you.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

    Examples

    Collect user's digits while playing an Mp3 file.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 4,
      'url' => 'https://cdn.signalwire.com/default-music/welcome.mp3'
    ];
    $call->promptAudio($collect)->done(function($promptResult) {
      if ($promptResult->isSuccessful()) {
        $type = $promptResult->getType(); // => digit
        $pin = $promptResult->getResult(); // => pin entered by the user
      }
    });
    

    promptAudioAsync

    Asynchronous version of promptAudio. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

    Available In:

    Parameters

    See promptAudio for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

    Examples

    Ask user to enter their PIN and collect the digits.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 4,
      'url' => 'https://cdn.signalwire.com/default-music/welcome.mp3'
    ];
    $call->promptAudioAsync($collect)->done(function($promptAction) {
      // .. do other important things while collecting user digits..
      if ($promptAction->isCompleted()) {
        $promptResult = $promptAction->getResult(); // => Relay.Calling.PromptResult Object
      }
    });
    

    promptRingtone

    This is a helper function that refines the use of prompt.
    This function simplifies playing ringtone while collecting user's input from the call, such as digits and speech.

    Available In:

    Parameters

    You can set all the properties that prompt accepts replacing media with:

    name string required The name of the ringtone. See ringtones for the supported values.
    duration number optional Duration of ringtone to play.
    Default to 1 ringtone iteration.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

    Examples

    Play US ringtone for 30 seconds while collect digits.

    <?php
    
    $params = [
      'type' => 'digits',
      'digits_max' => 3,
      'name' => 'us',
      'duration' => '30'
    ];
    $call->promptRingtone($params)->done(function($promptResult) {
      if ($promptResult->isSuccessful()) {
        $type = $promptResult->getType(); // => digit
        $pin = $promptResult->getResult(); // => user's digits
      }
    });
    

    promptRingtoneAsync

    Asynchronous version of promptRingtone. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

    Available In:

    Parameters

    See promptRingtone for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

    Examples

    Play US ringtone for 30 seconds while collect digits in asynchronous.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'name' => 'us',
      'duration' => '30'
    ];
    $call->promptRingtoneAsync($collect)->done(function($promptAction) {
      // .. do other important things while collecting user digits..
    
      if ($promptAction->isCompleted()) {
        $promptResult = $promptAction->getResult(); // => Relay.Calling.PromptResult Object
      }
    });
    

    promptTTS

    This is a helper function that refines the use of prompt.
    This function simplifies playing TTS while collecting user's input from the call, such as digits and speech.

    Available In:

    Parameters

    You can set all the properties that prompt accepts replacing media with:

    text string required Text-to-speech string to play.
    language string optional Default to en-US.
    gender string optional male or female. Default to female.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptResult object.

    Examples

    Ask user to enter their PIN and collect the digits.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'text' => 'Please, enter your 3 digit PIN.'
    ];
    $call->promptTTS($collect)->done(function($promptResult) {
      if ($promptResult->isSuccessful()) {
        $type = $promptResult->getType(); // => digit
        $pin = $promptResult->getResult(); // => pin entered by the user
      }
    });
    

    promptTTSAsync

    Asynchronous version of promptTTS. It does not wait the collection to completes but returns a Relay.Calling.PromptAction you can interact with.

    Available In:

    Parameters

    See promptTTS for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptAction object.

    Examples

    Ask user to enter their PIN and collect the digits.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'text' => 'Please, enter your 3 digit PIN.'
    ];
    $call->promptTTSAsync($collect)->done(function($promptAction) {
      // .. do other important things while collecting user digits..
      if ($promptAction->isCompleted()) {
        $promptResult = $promptAction->getResult(); // => Relay.Calling.PromptResult Object
      }
    });
    

    record

    Start recording the call and waits until the recording ends or fails.

    Available In:

    Parameters

    $params array optional Array with the following properties:
    beep boolean optional Default to false.
    stereo boolean optional Default to false.
    format string optional mp3 or wav.
    Default mp3.
    direction string optional listen, speak or both. Default to speak.
    initial_timeout number optional How long to wait in seconds until something is heard in the recording. Disable with 0.
    Default 5.0.
    end_silence_timeout number optional How long to wait in seconds until caller has stopped speaking. Disable with 0.
    Default 1.0.
    terminators string optional DTMF digits that will end the recording.
    Default #*.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.RecordResult object.

    Examples

    Start recording audio in the call for both direction in stereo mode, if successful, grab url, duration and size from the RecordResult object.

    <?php
    
    $params = [
      'stereo' => true,
      'direction' => 'both'
    ];
    $call->record($params)->done(function($recordResult) {
      if ($recordResult->isSuccessful()) {
        $url = $recordResult->getUrl();
        $duration = $recordResult->getDuration();
        $size = $recordResult->getSize();
      }
    });
    

    recordAsync

    Asynchronous version of record. It does not wait the end of recording but returns a Relay.Calling.RecordAction you can interact with.

    Available In:

    Parameters

    See record for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.RecordAction object.

    Examples

    Start recording audio in the call for both direction in stereo mode and then stop it using the RecordAction object.

    <?php
    
    $params = [
      'stereo' => true,
      'direction' => 'both'
    ];
    $call->record($params)->done(function($recordAction) {
      // For demonstration purposes only ..
      $recordAction->stop();
    });
    

    sendDigits

    This method sends DTMF digits to the other party on the call. Allowed digits are 1234567890*#ABCD and wW for short and long waits. If any invalid characters are present, the entire operation is rejected.

    Available In:

    Parameters

    $digits string required String of DTMF digits to send.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.SendDigitsResult object.

    Examples

    Send some digits.

    <?php
    
    $call->sendDigits('123')->done(function($result) {
      if ($result->isSuccessful()) {
        // ...
      }
    });
    

    sendDigitsAsync

    Asynchronous version of sendDigits. It does not wait for the sending event to complete, and immediately returns a Relay.Calling.SendDigitsAction object you can interact with.

    Available In:

    Parameters

    See sendDigits for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.SendDigitsAction.

    Examples

    Send some digits and then check if the operation is completed using the SendDigitsAction object.

    <?php
    
    $call->sendDigitsAsync('123')->done(function($action) {
      // ...
      // Later in the code for demonstration purposes only ..
      $completed = $action->isCompleted();
    });
    

    tap

    Intercept call media and stream it to the specify endpoint. It waits until the end of the call.

    Available In:

    Parameters

    $tap array required Array with the following properties:
    audio_direction string required listen what the caller hears, speak what the caller says or both.
    target_type string required Protocol to use: rtp or ws, defaults to rtp.
    target_ptime number optional Packetization time in ms. It will be the same as the tapped media if not set.
    codec string optional Codec to use. It will be the same as the tapped media if not set.
    • To tap through RTP:
    target_addr string required RTP IP v4 address.
    target_port number required RTP port.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.TapResult object.

    Examples

    Tapping audio from the call, if successful, print both source and destination devices from the TapResult object.

    <?php
    
    $tap = [
      'audio_direction' => 'both',
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tap($tap)->done(function($tapResult) {
      if ($tapResult->isSuccessful()) {
        print_r($tapResult->getSourceDevice());
        print_r($tapResult->getDestinationDevice());
      }
    });
    

    tapAsync

    Asynchronous version of tap. It does not wait the end of tapping but returns a Relay.Calling.TapAction you can interact with.

    Available In:

    Parameters

    See tap for the parameter list.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.TapAction object.

    Examples

    Tapping audio from the call and then stop it using the TapAction object.

    <?php
    
    $tap = [
      'audio_direction' => 'both',
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tapAsync($tap, $device)->done(function($tapAction) {
      // ... later in the code to stop tapping..
      $tapAction->stop();
    });
    

    waitFor

    Wait for specific events on the Call or returns false if the Call ends without getting them.

    Available In:

    Parameters

    event1, event2, ..eventN string or string[] required One or more Relay.Calling.Call State Events

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with true or false.

    Examples

    Wait for ending or ended events.

    <?php
    
    $call->waitFor('ending', 'ended')->done(function($success) {
      if ($success) {
        // ...
      }
    });
    

    waitForAnswered

    This is a helper function that refines the use of waitFor. This simplifies waiting for the answered state.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with true or false.

    Examples

    Wait for the answered event.

    <?php
    
    $call->waitForAnswered()->done(function($success) {
      if ($success) {
        // ...
      }
    });
    

    waitForEnded

    This is a helper function that refines the use of waitFor. This simplifies waiting for the ended state.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with true or false.

    Examples

    Wait for the ended event.

    <?php
    
    $call->waitForEnded()->done(function($success) {
      if ($success) {
        // ...
      }
    });
    

    waitForEnding

    This is a helper function that refines the use of waitFor. This simplifies waiting for the ending state.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with true or false.

    Examples

    Wait for the ending event.

    <?php
    
    $call->waitForEnding()->done(function($success) {
      if ($success) {
        // ...
      }
    });
    

    waitForRinging

    This is a helper function that refines the use of waitFor. This simplifies waiting for the ringing state.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with true or false.

    Examples

    Wait for ending or ended events.

    <?php
    
    $call->waitForRinging()->done(function($success) {
      if ($success) {
        // ...
      }
    });
    

    Events

    All these events can be used to track the calls lifecycle and instruct SignalWire on what to do for each different state.

    State Events

    To track the state of a call.

    stateChange Event dispatched when Call state changes.
    created The call has been created in Relay.
    ringing The call is ringing and has not yet been answered.
    answered The call has been picked up.
    ending The call is hanging up.
    ended The call has ended.

    Connect Events

    To track the connect state of a call.

    connect.stateChange Event dispatched when the Call connect state changes.
    connect.connecting Currently calling the phone number(s) to connect.
    connect.connected The calls are being connected together.
    connect.failed The last call connection attempt failed.
    connect.disconnected The call was either never connected or the last call connection completed.

    Play Events

    To track a playback state.

    play.stateChange Event dispatched when the state of a playing changes.
    play.playing A playback is playing on the call.
    play.error A playback failed to start.
    play.finished The playback has ended.

    Record Events

    To track a recording state.

    record.stateChange Event dispatched when the state of a recording changes.
    record.recording The call is being recorded.
    record.no_input The recording failed due to no input.
    record.finished The recording has finished.

    Prompt Events

    To track a prompt state.

    prompt The prompt action on the call has finished.

    Fax Events

    To track a fax state.

    fax.error Faxing failed.
    fax.finished Faxing has finished.
    fax.page A fax page has been sent or received.

    Detect Events

    To track a detector state.

    detect.error The detector has failed.
    detect.finished The detector has finished.
    detect.update There is a notification from the detector (eg: a new DTMF).

    Tap Events

    To track a tapping state.

    tap.tapping The tap action has started on the call.
    tap.finished Tap has finished.

    Digits Events

    To track a send digits action state.

    sendDigits.finished Digits have been sent.

    Ringtones

    Here you can find all the accepted values for the ringtone to play, based on short country codes:

    name at, au, bg, br, be, ch, cl, cn, cz, de, dk, ee, es, fi, fr, gr, hu, il, in, it, lt, jp, mx, my, nl, no, nz, ph, pl, pt, ru, se, sg, th, uk, us, tw, ve, za

    Relay.Calling.ConnectAction

    This object returned from connectAsync method that represents a connecting attempt that is currently active on a call.

    Methods

    getResult

    Returns the final result of the connect attempt.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.ConnectResult - Final result of the connect attempt.

    Examples

    Trying to connect two numbers in series and grab the result when it's completed.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connectAsync(...$devices)->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $result = $action->getResult();
      }
    });
    

    getState

    Return the current state of the connect attempt.

    Available In:

    Parameters

    None

    Returns

    string - Current state of the connect attempt.

    Examples

    Trying to connect two numbers in series and print the state.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connectAsync(...$devices)->done(function($action) {
      echo $action->getState();
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Trying to connect two numbers in series and print out the payload.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connectAsync(...$devices)->done(function($action) {
      print_r($action->getPayload());
    });
    

    isCompleted

    Return true if the connect attempt has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Trying to connect two numbers in series and check if it has finished.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connectAsync(...$devices)->done(function($action) {
      if ($action->isCompleted()) {
    
      }
    });
    

    Relay.Calling.ConnectResult

    This object returned from the connect method that represents the final result of a connection between your call and a remote one.

    Methods

    getCall

    Return the Call object connected with yours, if the connection succeeded.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.Call - The remote Call.

    Examples

    Trying to connect two devices and then use the remote Call.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connect(...$devices)->done(function($result) {
      if ($result->isSuccessful()) {
        $remoteCall = $result->getCall();
        // Use $remoteCall as a normal Relay.Calling.Call object...
      }
    });
    

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Trying to connect two devices and then grab the Relay event to inspect the payload.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connect(...$devices)->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    isSuccessful

    Return true if the call has connected with a remote party, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - Whether the call has been connected successfully.

    Examples

    Trying to connect two devices and then check if your call has been connected.

    <?php
    
    $devices = [
      [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
      [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
    ];
    $call->connect(...$devices)->done(function($result) {
      if ($result->isSuccessful()) {
        // Your call has been connected..
      }
    });
    

    Relay.Calling.DetectAction

    This object returned from one of asynchronous detect methods that represents a running detector on the call.

    Methods

    getControlId

    Return the UUID to identify the action.

    Available In:

    Parameters

    None

    Returns

    string - UUID to identify the action.

    Examples

    Start a detector and print the controlId.

    <?php
    
    $call->detectMachineAsync()->done(function ($action) {
      echo $action->getControlId();
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Start a detector and print out the payload.

    <?php
    
    $call->detectDigitAsync()->done(function($detectResult) {
      print_r($action->getPayload());
    });
    

    getResult

    Returns the final detector result.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.DetectResult - Final detector result.

    Examples

    Trying detecting DTMF and grab the result when it's completed.

    <?php
    
    $call->detectDigitAsync()->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $detectResult = $action->getResult();
      }
    });
    

    isCompleted

    Return true if detector has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Trying detecting DTMF and check if it has finished.

    <?php
    
    $call->detectDigitAsync()->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
    
      }
    });
    

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.StopResult object.

    Examples

    Trying detecting a machine and then stop the action.

    <?php
    
    $call->detectMachineAsync()->done(function ($action) {
      // For demonstration purposes only..
      $action->stop()->done(function($stopResult) {
    
      });
    });
    

    Relay.Calling.DetectResult

    This object returned from one of synchronous detect methods that represents the final result of a detector.

    Methods

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Detect digits and grab the result when it's completed.

    <?php
    
    $call->detectDigit()->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    getResult

    Returns the result of the detector. It could be the digits or the type (machine or human) detected.

    Available In:

    Parameters

    None

    Returns

    string - Detector result.

    Examples

    Detect DTMF and print out the result.

    <?php
    
    $call->detectDigit()->done(function($result) {
      if ($result->isSuccessful()) {
        echo "DTMF detected: " . $result->getResult();
      }
    });
    

    getType

    Returns the type of detector.

    Available In:

    Parameters

    None

    Returns

    string - Detector type: digit, machine or fax.

    Examples

    Check the type of a detector.

    <?php
    
    $call->detectFax()->done(function($result) {
      if ($result->isSuccessful()) {
        echo "Detector type: " . $result->getType();
      }
    });
    

    isSuccessful

    Return true if detector succeeded, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Start detecting a fax, then check if a fax has been detected.

    <?php
    
    $call->detectFax()->done(function($result) {
      if ($result->isSuccessful()) {
        // Fax has been detected!
      }
    });
    

    Relay.Calling.DialResult

    This object returned from Calling dial and Call dial methods.

    Methods

    getCall

    Return the active Call object, right after the remote peer picked it up.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.Call - The remote Call.

    Examples

    Trying to call a remote peer and, if it answer, get the active Call.

    <?php
    
    $params = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
    $client->calling->dial($params)->done(function($result) {
      if ($result->isSuccessful()) {
        $call = $result->getCall();
        // Your active $call..
      }
    });
    

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Start an outbound Call and then grab the Relay event to inspect the payload.

    <?php
    
    $call->dial()->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    isSuccessful

    Return true if the call was picked up by the remote party, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - Whether the call has been answered.

    Examples

    Start an outbound Call and then check if the dial has completed successfully.

    <?php
    
    $call->dial()->done(function($result) {
      if ($result->isSuccessful()) {
        // Your call has been answered by the remote party..
      }
    });
    

    Relay.Calling.FaxAction

    This object returned from faxReceiveAsync and faxSendAsync methods represents a receiving or sending Fax on the call.

    Methods

    getControlId

    Return the UUID to identify the fax action.

    Available In:

    Parameters

    None

    Returns

    string - UUID to identify the action.

    Examples

    Start faxing and print the controlId.

    <?php
    
    $call->faxSendAsync('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')->done(function ($action) {
      echo $action->getControlId();
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Start sending a fax and print out the payload.

    <?php
    
    $call->faxSendAsync('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', '+1888222111', 'Custom Header')->done(function ($action) {
      print_r($action->getPayload());
    });
    

    getResult

    Returns the final result of the faxing.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.FaxResult - Final result of the faxing.

    Examples

    Trying receiving a Fax and grab the result when it's completed.

    <?php
    
    $call->faxReceiveAsync()->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $faxResult = $action->getResult();
      }
    });
    

    isCompleted

    Return true if faxing has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Trying receiving a Fax and check if it has finished.

    <?php
    
    $call->faxReceiveAsync()->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
    
      }
    });
    

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - A React Promise that will be resolved with the Relay response.

    Examples

    Trying to receive a Fax and then stop the attempt.

    <?php
    
    $call->faxReceiveAsync()->done(function ($faxAction) {
      // For demonstration purposes only..
      $faxAction->stop();
    });
    

    Relay.Calling.FaxResult

    This object returned from faxReceive and faxSend methods that represents the final result of a sent or received Fax.

    Methods

    getDirection

    Returns the direction of the fax: send or receive.

    Available In:

    Parameters

    None

    Returns

    string - send or receive.

    Examples

    Start faxing and then check the direction.

    <?php
    
    $call->faxSend('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')->done(function($result) {
      if ($result->isSuccessful()) {
        echo $result->getDirection(); // => "send"
      }
    });
    

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Send a document and then inspect the last received Relay event.

    <?php
    
    $call->faxSend('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')->done(function($result) {
      if ($result->isSuccessful()) {
        print_r($result->getEvent());
      }
    });
    

    getDocument

    Returns the URL to the document send or received.

    Available In:

    Parameters

    None

    Returns

    string - URL to the document.

    Examples

    Receiving fax and print the URL of the document.

    <?php
    
    $call->faxReceive()->done(function($result) {
      if ($result->isSuccessful()) {
        echo $result->getDocument();
      }
    });
    

    getIdentity

    Returns the identity sending the fax.

    Available In:

    Parameters

    None

    Returns

    string - Identity that sent the document.

    Examples

    Receiving fax and print the identity.

    <?php
    
    $call->faxReceive()->done(function($result) {
      if ($result->isSuccessful()) {
        echo $result->getIdentity();
      }
    });
    

    getPages

    Returns the number of pages in the document.

    Available In:

    Parameters

    None

    Returns

    number - Number of pages.

    Examples

    Receiving fax and print the number of received pages.

    <?php
    
    $call->faxReceive()->done(function($result) {
      if ($result->isSuccessful()) {
        echo $result->getPages();
      }
    });
    

    getRemoteIdentity

    Returns the remote identity sent or receiving the Fax.

    Available In:

    Parameters

    None

    Returns

    string - The remote identity.

    Examples

    Receiving fax and print the remote identity.

    <?php
    
    $call->faxReceive()->done(function($result) {
      if ($result->isSuccessful()) {
        echo $result->getRemoteIdentity();
      }
    });
    

    isSuccessful

    Return true if faxing succeeded, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - True/False accordingly to the state.

    Examples

    Start sending a document and then check if it has sent successfully.

    <?php
    
    $call->faxSend('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')->done(function($result) {
      if ($result->isSuccessful()) {
        // Fax sent successfully..
      }
    });
    

    Relay.Calling.HangupResult

    This object returned from hangup method.

    Methods

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Hangup the call and inspect the retrieve the last Relay event.

    <?php
    
    $call->hangup()->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    getReason

    Returns the reason why the call has ended.

    Available In:

    Parameters

    None

    Returns

    string - Possible values: hangup, cancel, busy, noAnswer, decline, error

    Examples

    <?php
    
    $call->hangup()->done(function($result) {
      $reason = $result->getReason();
    });
    

    isSuccessful

    Return true if the call was answered without errors, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - Whether the call has been answered successfully.

    Examples

    Hangup the call and check if the operation succeeded.

    <?php
    
    $call->hangup()->done(function($result) {
      if ($result->isSuccessful()) {
        // $call has been hung up successfully!
      }
    });
    

    Relay.Calling.PlayAction

    This object returned from one of asynchronous play methods that represents a playing currently active on a call.

    Methods

    getControlId

    Return the UUID to identify the playing.

    Available In:

    Parameters

    None

    Returns

    string - UUID to identify the action.

    Examples

    Start the play and print the controlId.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      echo $action->getControlId();
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Start the play and print out the payload.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      print_r($action->getPayload());
    });
    

    getResult

    Returns the final result of the playing.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.PlayResult - Final result of the playing.

    Examples

    Start the play and grab the result when it's completed.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $result = $action->getResult();
      }
    });
    

    getState

    Return the current state of the playing.

    Available In:

    Parameters

    None

    Returns

    string - Current state of the playing.

    Examples

    Start the play and print the state.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      echo $action->getState();
    });
    

    isCompleted

    Return true if the playing has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Start the play and check if it has finished.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      if ($action->isCompleted()) {
    
      }
    });
    

    pause

    Pause the playback immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayPauseResult object.

    Examples

    Start playing an audio file and pause it.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      // For demonstration purposes only..
      $action->pause()->done(function($pauseResult) {
        if ($pauseResult->successful) {
    
        }
      });
    });
    

    resume

    Resume the playback immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayResumeResult object.

    Examples

    Start playing an audio file, stop it and then resume it.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      // For demonstration purposes only..
      $action->pause()->done(function($pauseResult) use ($action) {
        // .. later in the code..
        $action->resume()->done(function($resumeResult) {
    
        });
      });
    });
    

    Note: you can avoid the callback hell using these methods in a Relay.Consumer.

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.StopResult object.

    Examples

    Start the play and stop it if an Agent is not available.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) use ($globalAgent) {
      if ($globalAgent->isAvailable() === false) {
        $action->stop()->done(function($stopResult) {
    
        });
      }
    });
    

    volume

    Control the volume of the playback.

    Available In:

    Parameters

    volume number required Volume value between -40dB and +40dB where 0 is unchanged.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PlayVolumeResult object.

    Examples

    Start the play and increase the playback volume.

    <?php
    
    $call->playAudioAsync('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($action) {
      // For demonstration purposes only..
      $action->volume(5.0)->done(function($volumeResult) {
        if ($volumeResult->successful) {
    
        }
      });
    });
    

    Relay.Calling.PlayPauseResult

    This object is returned by pause method and represents the final result of a play pause operation.

    Properties

    successful boolean Whether the playing has been paused successfully.

    Relay.Calling.PlayResult

    This object returned from one of synchronous play methods that represents the final result of a playing action.

    Methods

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Start playing an audio file and then grab the last event occurred.

    <?php
    
    $call->playAudio('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    isSuccessful

    Return true if the playing has succeeded, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - Whether the playing has finished successfully.

    Examples

    Start the recording and then check if it has ended successfully.

    <?php
    
    $call->playAudio('https://cdn.signalwire.com/default-music/welcome.mp3')->done(function($result) {
      if ($result->isSuccessful()) {
        // Do other things...
      }
    });
    

    Relay.Calling.PlayResumeResult

    This object is returned by resume method and represents the final result of a play resume operation.

    Properties

    successful boolean Whether the playing has resumed successfully.

    Relay.Calling.PlayVolumeResult

    This object is returned by volume method and represents the final result of a volume control operation.

    Properties

    successful boolean Whether the playing volume has been changed successfully.

    Relay.Calling.PromptAction

    This object returned from one of asynchronous prompt methods that represents a prompt attempt that is currently active on a call.

    Methods

    getControlId

    Return the UUID to identify the prompt attempt.

    Available In:

    Parameters

    None

    Returns

    string - UUID to identify the action.

    Examples

    Start the attempt and print the controlId.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTSAsync($collect)->done(function($action) {
      echo $action->getControlId();
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Start the attempt and print out the payload.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTSAsync($collect)->done(function($action) {
      print_r($action->getPayload());
    });
    

    getResult

    Returns the final result of the prompt attempt.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.PromptResult - Final result of the prompt attempt.

    Examples

    Start the attempt and grab the result when it's completed.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTSAsync($collect)->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $result = $action->getResult();
      }
    });
    

    getState

    Return the current state of the prompt attempt.

    Available In:

    Parameters

    None

    Returns

    string - Current state of the prompt attempt.

    Examples

    Start the attempt and print the state.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTSAsync($collect)->done(function($action) {
      echo $action->getState();
    });
    

    isCompleted

    Return true if the prompt attempt has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Start the attempt and check if it has finished.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTSAsync($collect)->done(function($action) {
      if ($action->isCompleted()) {
    
      }
    });
    

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.StopResult object.

    Examples

    Start the attempt and then stop it.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTSAsync($collect)->done(function($action) {
      // For demonstration purposes only..
      $action->stop()->done(function($stopResult) {
    
      });
    });
    

    volume

    Control the volume of the playback.

    Available In:

    Parameters

    volume number required Volume value between -40dB and +40dB where 0 is unchanged.

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.PromptVolumeResult object.

    Examples

    Start the prompt and increase the playback volume.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTSAsync($collect)->done(function($action) {
      // For demonstration purposes only..
      $action->volume(5.0)->done(function($volumeResult) {
    
      });
    });
    

    Relay.Calling.PromptResult

    This object returned from one of synchronous prompt methods that represents the final result of a prompting attempt.

    Methods

    getConfidence

    In a prompt action of type speech, it returns the confidence of the result.

    Available In:

    Parameters

    None

    Returns

    number - Confidence of the result on a speech prompt.

    Examples

    Start prompt and then check the result confidence.

    <?php
    
    $collect = [
      'type' => 'speech',
      'end_silence_timeout' => 1,
      'speech_language' => 'en-US',
      'text' => 'Please, tell me who you want to talk to'
    ];
    $call->promptTTS($collect)->done(function($result) {
      if ($result->isSuccessful()) {
        $confidence = $result->getConfidence(); // => 83.2
      }
    });
    

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Start the prompt while playing TTS and then inspect last Relay event payload.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTS($collect)->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    getResult

    Returns the user's input in a prompt attempt. Could be both from speech or digits type.

    Available In:

    Parameters

    None

    Returns

    string - User's input in a prompt attempt.

    Examples

    Start recording and print the result in a digits prompt.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTS($collect)->done(function($result) {
      if ($result->isSuccessful()) {
        $result = $result->getResult();
    
        echo "User enter the PIN: " . $result;
      }
    });
    

    getTerminator

    In a prompt action of type digits, it returns the digit that has terminated the attempt.

    Available In:

    Parameters

    None

    Returns

    string - Digit that has terminated the prompt attempt.

    Examples

    Start prompt and then check the terminator digit.

    <?php
    
    $collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5, "terminators" => "#*" ] ];
    $tts = [ "text" => "Please, enter your 3 digits PIN" ];
    $call->promptTTS($collect)->done(function($result) {
      if ($result->isSuccessful()) {
        $terminator = $result->getTerminator(); // => "#"
      }
    });
    

    getType

    Returns the type of the attempt: digits or speech.

    Available In:

    Parameters

    None

    Returns

    string - digits or speech.

    Examples

    Start prompt and then check the type of the prompt.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTS($collect)->done(function($result) {
      if ($result->isSuccessful()) {
        $type = $result->getType(); // => "digits"
      }
    });
    

    isSuccessful

    Return true if the prompt attempt succeeded, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - True/False accordingly to the state.

    Examples

    Start the prompt while playing TTS and then check if it has ended successfully.

    <?php
    
    $collect = [
      'type' => 'digits',
      'digits_max' => 3,
      'initial_timeout' => 10,
      'text' => 'Please, enter your 3 digits PIN'
    ];
    $call->promptTTS($collect)->done(function($result) {
      if ($result->isSuccessful()) {
        // Prompt completed with success..
      }
    });
    

    Relay.Calling.PromptVolumeResult

    This object is returned by volume method and represents the final result of a volume control operation.

    Properties

    successful boolean Whether the volume has been changed successfully.

    Relay.Calling.RecordAction

    This object returned from recordAsync method that represents a recording that is currently active on a call.

    Methods

    getControlId

    Return the UUID to identify the recording.

    Available In:

    Parameters

    None

    Returns

    string - UUID to identify the action.

    Examples

    Start recording in stereo mode and print the controlId.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->recordAsync($params)->done(function($action) {
      echo $action->getControlId();
    });
    

    getResult

    Returns the final result of the recording.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.RecordResult - Final result of the recording.

    Examples

    Start recording in stereo mode and grab the result when it's completed.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->recordAsync($params)->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $result = $action->getResult();
      }
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Start recording in stereo mode and print out the payload.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->recordAsync($params)->done(function($action) {
      print_r($action->getPayload());
    });
    

    getState

    Return the current state of recording.

    Available In:

    Parameters

    None

    Returns

    string - Current state of recording.

    Examples

    Start recording in stereo mode and print the state.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->recordAsync($params)->done(function($action) {
      echo $action->getState();
    });
    

    getUrl

    Returns the HTTPS URL to the recording file.

    Note: the recording may not be present at the URL until the recording is finished.

    Available In:

    Parameters

    None

    Returns

    string - HTTPS URL to the file.

    Examples

    Start recording and print the URL.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->recordAsync($params)->done(function($action) {
      echo $result->getUrl();
    });
    

    isCompleted

    Return true if the recording has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Start recording in stereo mode and check if it has finished.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->recordAsync($params)->done(function($action) {
      if ($action->isCompleted()) {
    
      }
    });
    

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.StopResult object.

    Examples

    Start recording in stereo mode and stop it an Agent is not available.

    <?php
    
    $params = [
      "audio" => [
        "stereo" => true
      ]
    ];
    $call->recordAsync($params)->done(function($action) use ($globalAgent) {
      if ($globalAgent->isAvailable() === false) {
        $action->stop()->done(function($stopResult) {
    
        });
      }
    });
    

    Relay.Calling.RecordResult

    This object returned from record method that represents the final result of a recording.

    Methods

    getDuration

    Returns the duration of the recording in seconds.

    Available In:

    Parameters

    None

    Returns

    number - Duration of the recording in seconds.

    Examples

    Start recording and use the duration.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->record($params)->done(function($result) {
      if ($result->isSuccessful()) {
        $duration = $result->getDuration();
      }
    });
    

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Start recording in stereo mode and grab the result when it's completed.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->record($params)->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    getSize

    Returns the size of the recording file.

    Available In:

    Parameters

    None

    Returns

    number - Size of the recording file.

    Examples

    Start recording and use the size of the file.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->record($params)->done(function($result) {
      if ($result->isSuccessful()) {
        $size = $result->getSize();
      }
    });
    

    getUrl

    Returns the HTTPS URL to the recording file.

    Available In:

    Parameters

    None

    Returns

    string - HTTPS URL to the file.

    Examples

    Start recording and use the URL.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->record($params)->done(function($result) {
      if ($result->isSuccessful()) {
        $httpsUrl = $result->getUrl();
      }
    });
    

    isSuccessful

    Return true if the recording succeeded, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - True/False accordingly to the state.

    Examples

    Start the recording and then check if it has ended successfully.

    <?php
    
    $params = [
      'stereo' => true
    ];
    $call->record($params)->done(function($result) {
      if ($result->isSuccessful()) {
        // Recording completed with success
      }
    });
    

    Relay.Calling.SendDigitsAction

    This object is returned by sendDigitsAsync method that represents a send digits operation currently active on a call.

    Methods

    getControlId

    Return the UUID to identify the operation.

    Available In:

    Parameters

    None

    Returns

    string - UUID to identify the action.

    Examples

    Send some digits and print the controlId.

    <?php
    
    $call->sendDigitsAsync('1234')->done(function($action) {
      echo $action->getControlId();
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Send some digits and print out the payload.

    <?php
    
    $call->sendDigitsAsync('1234')->done(function($action) {
      print_r($action->getPayload());
    });
    

    getResult

    Returns the final result of the send digits operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.SendDigitsResult - Final result of the operation.

    Examples

    Send some digits and grab the result when it's completed.

    <?php
    
    $call->sendDigitsAsync('1234')->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $sendDigitsResult = $action->getResult();
      }
    });
    

    getState

    Return the current state of the operation.

    Available In:

    Parameters

    None

    Returns

    string - Current operation's state.

    Examples

    Send some digits and print the state.

    <?php
    
    $call->sendDigitsAsync('1234')->done(function($action) {
      echo $action->getState();
    });
    

    isCompleted

    Return true if the operation has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Send some digits and check if it has finished.

    <?php
    
    $call->sendDigitsAsync('1234')->done(function($action) {
      if ($action->isCompleted()) {
    
      }
    });
    

    Relay.Calling.SendDigitsResult

    This object is returned by sendDigits method and represents the final result of a send digits action.

    Methods

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Send some digits and then grab the last event occurred.

    <?php
    
    $call->sendDigits('1234')->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    isSuccessful

    Return true if the operation has succeeded, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - Whether the operation has completed successfully.

    Examples

    Send some digits and then check if it has ended successfully.

    <?php
    
    $call->sendDigits('1234')->done(function($result) {
      if ($result->isSuccessful()) {
        // Do other things...
      }
    });
    

    Relay.Calling.TapAction

    This object returned from tapAsync method that represents the running media tapping active on a call.

    Methods

    getControlId

    Return the UUID to identify the action.

    Available In:

    Parameters

    None

    Returns

    string - UUID to identify the action.

    Examples

    Start tapping audio and print the controlId.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tapAsync($tap)->done(function($action) {
      echo $action->getControlId();
    });
    

    getResult

    Returns the final result of this tapping action.

    Available In:

    Parameters

    None

    Returns

    Relay.Calling.TapResult - Final tap result.

    Examples

    Start tapping audio and grab the result when it's completed.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tapAsync($tap)->done(function($action) {
      // .. later in the code since it's an async method
      if ($action->isCompleted()) {
        $result = $action->getResult();
      }
    });
    

    getPayload

    Return the payload sent to Relay to initiate the request. Useful to inspect what you sent to perform this action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload sent to Relay.

    Examples

    Start tapping audio and print out the payload.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tapAsync($tap)->done(function($action) {
      print_r($action->getPayload());
    });
    

    getState

    Return the current tapping state.

    Available In:

    Parameters

    None

    Returns

    string - The current state.

    Examples

    Start tapping audio and print the state.

    <?php
    
    $tap = [ 'type' => 'audio' ];
    $device = [ 'type' => 'rtp', 'addr' => '192.168.1.1', 'port' => 1234 ];
    $call->tapAsync($tap, $device)->done(function($action) {
      echo $action->getState();
    });
    

    isCompleted

    Return true if tapping has finished, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Start tapping audio and check if it has finished.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tapAsync($tap)->done(function($action) {
      if ($action->isCompleted()) {
    
      }
    });
    

    getSourceDevice

    Return the source device sending media.

    Available In:

    Parameters

    None

    Returns

    Object - The source device.

    Examples

    Start tapping audio and then inspect the source device.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tapAsync($tap)->done(function($action) {
      $source = $action->getSourceDevice();
    });
    

    stop

    Stop the action immediately.

    Available In:

    Parameters

    None

    Returns

    React\Promise\Promise - Promise object that will be fulfilled with a Relay.Calling.StopResult object.

    Examples

    Start tapping audio and then stop the action.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tapAsync($tap)->done(function($action) {
      // For demonstration purposes only..
      $action->stop()->done(function($stopResult) {
    
      });
    });
    

    Relay.Calling.TapResult

    This object returned from tap method that represents the final result of a tapping.

    Methods

    getDestinationDevice

    Returns the destination device receiving media.

    Available In:

    Parameters

    None

    Returns

    Object - The destination device.

    Examples

    Tapping audio from the call and then inspect the destination device.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tap($tap)->done(function($result) {
      if ($result->isSuccessful()) {
        $destination = $result->getDestinationDevice();
      }
    });
    

    getEvent

    Returns the last Relay Event arrived for this operation.

    Available In:

    Parameters

    None

    Returns

    Relay.Event - Last Relay Event.

    Examples

    Tapping audio from the call and grab the result when it's completed.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tap($tap)->done(function($result) {
      $event = $result->getEvent();
      // Inspect $event->payload ..
    });
    

    getSourceDevice

    Returns the source device sending media.

    Available In:

    Parameters

    None

    Returns

    Object - The source device.

    Examples

    Tapping audio from the call and then inspect the source device.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tap($tap)->done(function($result) {
      if ($result->isSuccessful()) {
        $source = $result->getSourceDevice();
      }
    });
    

    getTap

    Returns the payload for this tap action.

    Available In:

    Parameters

    None

    Returns

    Object - Payload used to start tapping.

    Examples

    Tapping audio from the call and then inspect the tap payload.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tap($tap)->done(function($result) {
      if ($result->isSuccessful()) {
        $tap = $result->getTap();
      }
    });
    

    isSuccessful

    Return true if the tapping succeeded, false otherwise.

    Available In:

    Parameters

    None

    Returns

    Boolean - True/False accordingly to the state.

    Examples

    Tapping audio from the call and then check if it has ended successfully.

    <?php
    
    $tap = [
      'target_type' => 'rtp',
      'target_addr' => '192.168.1.1',
      'target_port' => 1234
    ];
    $call->tap($tap)->done(function($result) {
      if ($result->isSuccessful()) {
    
      }
    });
    

    Relay.Consumer

    A Relay Consumer is a simple PHP class that runs in its own process along side your application to handle calling and messaging events in realtime. Relay Consumers abstract all the setup of connecting to Relay and automatically dispatch workers to handle requests. Consumers will receive requests and delegate them to their own worker thread, allowing you to focus on your business logic without having to worry about multi-threading or blocking, everything just works. Think of Relay Consumers like a background worker system for all your calling and messaging needs.

    Creating Consumers

    A Relay Consumer is a simple object, customized by specifying contexts and event handlers to respond to incoming events.

    A consumer has 2 required properties: project, token, and usually requires at least one contexts for incoming events. Project and Token are used to authenticate your Consumer to your SignalWire account. Contexts are a list of contexts you want this Consumer to listen for. Learn more about Contexts.

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function onIncomingCall($call): Coroutine {
        yield $call->answer();
        yield $call->playTTS(['text' => 'Welcome to SignalWire!']);
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    Coroutine & yield keywords

    In the Consumer examples you can see the special keyword yield and the return type Coroutine on the onIncomingCall method. These keywords help you write asynchronous code that "seems" synchronous, avoiding the need to nest your code in multiple callbacks.

    Since the Relay PHP SDK is built on top of ReactPHP, a lot of methods return Promises that will be resolved with the result of the asynchronous operations. By flattening out the nested callbacks, you can just yield the Promises to wait for its value.

    If you are familiar with Javascript, yield is similar to the async/await syntax in JS.

    Difference between using and not using yield with a Promise.

    <?php
      public function onIncomingCall($call): Coroutine {
        // Without using yield
        $call->answer()->done(function($answerResult) {
          // .. use $answerResult here..
        });
    
        // Using yield
        $answerResult = yield $call->answer();
      }
    

    Note: within functions with return type Coroutine you must force PHP to parse the function as a Generator so, if you don't need any yield in your code, just set the first line as:

    <?php
      public function onIncomingCall($call): Coroutine {
        yield;
        // ...
      }
    

    Initializing Consumers

    You can optionally add an setup method if you need to do any initialization work before processing messages. This is useful to do any one-off work that you wouldn't want to do for each and every event, such as setting up logging or connecting to a datastore.

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function setup() {
        // Initialize anything you'd like available for all events.
        // Like logging, database connections, etc.
      }
    
      public function onIncomingCall($call): Coroutine {
        yield $call->answer();
        yield $call->playTTS(['text' => 'Welcome to SignalWire!']);
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    Properties

    client Relay.Client The underlying Relay client object.

    Event Handlers

    Event handlers are where you will write most of your code. They are executed when your consumer receives a matching event for the contexts specified by your Consumer.

    ready

    Executed once your Consumer is connected to Relay and the session has been established.

    Available In:

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function ready(): Coroutine {
        $params = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
        $dialResult = yield $this->client->calling->dial($params);
        if ($dialResult->isSuccessful()) {
          // Your active $call..
          $call = $dialResult->getCall();
        }
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    onIncomingCall

    Executed when you receive an inbound call, passes in the inbound Call object.

    Available In:

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function onIncomingCall($call): Coroutine {
        yield $call->answer();
        yield $call->playTTS(['text' => 'Welcome to SignalWire!']);
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    onTask

    Executed with your message sent through a Relay.Task.

    Available In:

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function onTask($message): Coroutine {
        yield;
        print_r($message);
        // ..Use your own $message sent in the context "default" from a Relay.Task
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    onIncomingMessage

    Executed when you receive an inbound SMS or MMS, passes in the inbound Message object.
    This method is a Coroutine to simplify writing of asynchronous code in here.

    Available In:

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function onIncomingMessage($message): Coroutine {
        yield;
        // Handle the inbound message here..
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    onMessageStateChange

    Executed when a message state changes, passes in the inbound Message object.
    This method is a Coroutine to simplify writing of asynchronous code in here.

    Available In:

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    use SignalWire\Log;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function ready(): Coroutine {
        $params = [
          'context' => 'default',
          'from' => '+1xxx',
          'to' => '+1yyy',
          'body' => 'Welcome at SignalWire!'
        ];
        $result = yield $this->client->messaging->send($params);
        if ($result->isSuccessful()) {
          Log::info('SMS queued successfully!');
        }
      }
    
      public function onMessageStateChange($message): Coroutine {
        yield;
        // Keep track of your SMS state changes..
        Log::info("Message {$message->id} state: {$message->state}.");
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    Cleaning Up on Exit

    When a Relay Consumer shuts down, you have the opportunity to clean up any resources held by the consumer. For example, you could close any open files, network connections, or send a notification to your monitoring service.

    Just implement a teardown method in your consumer and it will be called during the shutdown procedure.

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['default'];
    
      public function onIncomingCall($call): Coroutine {
        yield $call->answer();
        yield $call->playTTS(['text' => 'Welcome to SignalWire!']);
      }
    
      public function teardown(): Coroutine {
        // Clean up any resources when exiting.
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    Running Consumers

    Running a consumer is just like running any other PHP script, simply execute the script as a separate process and ensure you invoke the ->run(); method at the end of your script. The process will stay up until you shut it down.

    Shutting Down Consumers

    In order to gracefully shut down a Relay consumer process, send it the SIGTERM signal. Most process supervisors such as Runit, Docker and Kubernetes send this signal when shutting down a process, so using those systems will make things easier.

    Relay.Event

    This object represents the last Relay event that completed an operation on the Call.

    Properties

    name string The event name.
    payload object Raw JSON object of the Relay event.

    Relay.Messaging

    This represents the API interface for the Messaging Relay Service. This object is used to make requests related to managing SMS and MMS messages.

    Methods

    send

    Send a message to the destination number.

    Available In:

    Parameters

    context string required The context to receive inbound events.
    from string required The phone number to place the message from. Must be a SignalWire phone number or short code that you own.
    to string required The phone number to send to.
    body string required The content of the message.
    Optional if media is present.
    media string[] required Array of URLs to send in the message.
    Optional if body is present.
    tags string[] optional Array of strings to tag the message with for searching in the UI.

    Returns

    React\Promise\Promise - Promise that will be fulfilled with a Relay.Messaging.SendResult object.

    Examples

    Send a message in the context office.

    <?php
    
    $params = [
      'context' => 'office',
      'from' => '+1XXXXXXXXXX',
      'to' => '+1YYYYYYYYYY',
      'body' => 'Welcome at SignalWire!'
    ];
    $client->messaging->send($params)->done(function($sendResult) {
      if ($sendResult->isSuccessful()) {
        echo "Message ID: " . $sendResult->getMessageId();
      }
    });
    

    Relay.Messaging.Message

    An object representing an SMS or MMS message. It is the parameter of both onIncomingMessage and onMessageStateChange Consumer handlers.

    Properties

    id string The unique identifier of the message.
    context string The context of the message.
    from string The phone number the message comes from.
    to string The destination number of the message.
    direction string The direction of the message: inbound or outbound.
    state string The current state of the message. See Relay.Messaging.Message State Events for all the possible states.
    body string The content of the message.
    media string[] Array of URLs media.
    tags string[] Array of strings with message tags.
    segments number Number of segments of the message.
    reason string Reason why the message was not sent.
    Present only in case of failure.

    Events

    State Events

    To track the state of a message.

    queued The message has been queued in Relay.
    initiated Relay has initiate the process to send the message.
    sent Relay has sent the message.
    delivered The message has been successfully delivered. Due to the nature of SMS and MMS, receiving a delivered event is not guaranteed, even if the message is delivered successfully.
    undelivered The message has not been delivered. Due to the nature of SMS and MMS, receiving a undelivered event is not guaranteed, even if the message fails to be delivered.
    failed The call has failed.

    Relay.Messaging.SendResult

    This object returned from send method that represents the result of a send operation.

    Properties

    successful boolean Whether the send operation has successfully queued the message.
    messageId string The ID of the message.

    Methods

    getMessageId

    Returns the ID of the queued message.

    Available In:

    Parameters

    None

    Returns

    string - Message ID.

    Examples

    Send a message and retrieve the ID.

    <?php
    
    $params = [
      'context' => 'office',
      'from' => '+1XXXXXXXXXX',
      'to' => '+1YYYYYYYYYY',
      'body' => 'Welcome at SignalWire!'
    ];
    $client->messaging->send($params)->done(function($sendResult) {
      if ($sendResult->isSuccessful()) {
        $messageId = $sendResult->getMessageId();
      }
    });
    

    isSuccessful

    Return true if the message was queued, false otherwise.

    Available In:

    Parameters

    None

    Returns

    boolean - True/False accordingly to the state.

    Examples

    Send a message and then check if there were errors.

    <?php
    
    $params = [
      'context' => 'office',
      'from' => '+1XXXXXXXXXX',
      'to' => '+1YYYYYYYYYY',
      'body' => 'Welcome at SignalWire!'
    ];
    $client->messaging->send($params)->done(function($sendResult) {
      if ($sendResult->isSuccessful()) {
        // ..
      }
    });
    

    Relay.Task

    A Relay.Task is simple way to send jobs to your Relay.Consumers from a short lived process, like a web framework. Relay Tasks allow you to pass commands down to your Consumers without blocking your short lived request. Think of a Relay Task as a way to queue a job for your background workers to processes asynchronously.

    Creating Tasks

    A Task is a simple object with 2 required arguments: $project and $token. Project and Token are used to send the Task to your Consumers. Once created, the Task has only one method deliver to send jobs to your Consumer.

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use SignalWire\Relay\Tasking\Task;
    
    $task = new Task('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
    $context = 'office';
    $delivered = $task->deliver($context, [
      'key' => 'value',
      'data' => 'data for your job'
    ]);
    

    Methods

    deliver

    Send a job to your Consumer in a specific context.

    Available In:

    Parameters

    $context string required Context where to send the Task.
    $message array required Array with your custom data that will be sent to your Consumer's onTask handler.

    Returns

    boolean - Whether the Task has been sent successfully.

    Examples

    Deliver a task to your Consumer with a message to then make an outbound Call.

    <?php
    
    $delivered = $task->deliver('office', [
      'action' => 'call',
      'from' => '+18881112222'
      'to' => '+18881113333'
    ]);
    

    Examples

    Follow the examples to see how's easy to use the Relay SDK to interact with inbound or outbound calls.

    Inbound Calls

    Using RelayConsumer to manage inbound calls from both home and office contexts. Answer the call, ask the user to enter his PIN and playback the digits he sent if successful.

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['home', 'office'];
    
      public function onIncomingCall($call): Coroutine {
        $answerResult = yield $call->answer();
        if (!$answerResult->isSuccessful()) {
          echo "Error answering the call..";
          return;
        }
        $promptParams = [
          'type' => 'digits',
          'initial_timeout' => 10
          'digits_max' => 4,
          'text' => 'Welcome to SignalWire! Please, enter your PIN'
        ];
        $promptResult = yield $call->promptTTS($promptParams);
        if ($promptResult->isSuccessful()) {
          $pin = $promptResult->getResult();
          yield $call->playTTS([ "text" => "You entered: {$pin}. Thanks and good bye!" ]);
        }
        yield $call->hangup();
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();
    

    Outbound Calls

    Using RelayConsumer to make an outbound call and ask the user to enter his PIN. Once completed, print the collected digits.

    <?php
    
    require dirname(__FILE__) . '/vendor/autoload.php';
    
    use Generator as Coroutine;
    
    class CustomConsumer extends SignalWire\Relay\Consumer {
      public $project = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
      public $token = 'PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
      public $contexts = ['home', 'office'];
    
      public function ready(): Coroutine {
        $params = ['type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY'];
        $dialResult = yield $this->client->calling->dial($params);
        if (!$dialResult->isSuccessful()) {
          echo "Dial error or call not answered by the remote peer..";
          return;
        }
        $call = $dialResult->getCall();
        $promptParams = [
          'type' => 'digits',
          'digits_max' => 4,
          'digits_terminators' => '#',
          'text' => 'Welcome at SignalWire. Please, enter your 4 digits PIN and then # to proceed'
        ];
        $promptResult = yield $call->promptTTS($promptParams);
        if ($promptResult->isSuccessful()) {
          $pin = $promptResult->getResult();
          echo "User digits: {$pin} ..";
        }
      }
    }
    
    $consumer = new CustomConsumer();
    $consumer->run();