Navbar

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.

Latest Version:

Source Code: signalwire/signalwire-php

Support: SignalWire Community Slack Channel

Installation

Install the package using Composer:

Note: To run the Relay SDK you must have PHP 7.1+ installed on your system.

composer require signalwire/signalwire

In order to use the PHP client, you must get your host, project, and token from your SignalWire dashboard.

<?php

$client = new SignalWire\Relay\Client([
  "host" => "example.signalwire.com",
  "project" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
  "token" => "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
]);

Note: If your environment does not handle autoloading you must require the autoload file generated by Composer.

<?php

require 'path-to/vendor/autoload.php';

You can then use $client to make requests.

Configuration Options

\React\EventLoop

The Relay SDK is built on top of ReactPHP to handle the WebSocket connection with non-blocking I/O operations. If you want to integrate the SDK in a long-running application that already use an EventLoop, or you need to interact with the EventLoop itself (see ReactPHP LoopInterface), you can set a custom EventLoop passing it directly in constructor.
By default a React\EventLoop\Factory will be used.

Passing a custom eventLoop to the client.

<?php

$loop = React\EventLoop\Factory::create();
// Setup your loop ...

$client = new SignalWire\Relay\Client([
  "host" => "example.signalwire.com",
  "project" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
  "token" => "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "eventLoop" => $loop
]);

// connect() automatically run the EventLoop.
$client->connect();

Using the SDK

The PHP SDK can be used to get up and running quickly. Below is an example of setting up a connection to Relay and making an outbound call.

Quick Start Example

<?php

$client = new SignalWire\Relay\Client([
  "host" => "example.signalwire.com",
  "project" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
  "token" => "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
]);

$client->on('signalwire.ready', function($client) {

  $client->calling->newCall([
    'type' => 'phone',
    'from' => '+1XXXXXXXXXX',
    'to' => '+1YYYYYYYYYY'
  ])->then(
    function($call) {
      $call->on('answered', function($call) {
        // Call has been picked up!
      });
      $call->begin();
    },
    function ($error) {
      // An error occurred..
    }
  );

});

$client->connect();

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

host string required The endpoint URI to send requests to. The SignalWire Space URL, should be a string similar {your-space}.signalwire.com.
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([
  "host" => "example.signalwire.com",
  "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
// Make sure you have attached the listeners you need **before** connecting the client, or you might miss some events.
$client->connect();

disconnect()

Disconnect the client from Relay.

Available In:

Returns

void

Examples

<?php

$client->disconnect();

on(string $event, callable $callback)

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 callable required Function to call 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(string $event, callable $callback)

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

Parameters

$event string required Event name. Full list of events Relay.Client Events
$callback callable optional Function 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.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

newCall(array $params)

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

Available In:

Parameters

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 - A Promise that will be fulfilled with the new Call object.

Examples

Create a new Call object.

<?php

$options = [
  'type' => 'phone',
  'from' => '+1XXXXXXXXXX',
  'to' => '+1YYYYYYYYYY'
];
$client->calling->newCall($options)->then(
  function($call) {
    // Use $call ...
  },
  function ($error) {
    // An error occurred..
  }
);

onInbound(string $context, callable $callback)

Attach an event handler that will be called with inbound calls on the specified $context.

Available In:

Parameters

$context string required The $context you want to listen on. You can create and manage these contexts, such as "pbx", "office" or "work" from your SignalWire Space.
$callback callable required Callback that instructs SignalWire on what to do when receiving an inbound call from the specified $context.

Returns

React\Promise\Promise - A Promise that will be fulfilled when the callback has been registered properly.

Examples

Listen for inbound calls on the office context.

<?php

$client->calling->onInbound('office', function($call) {
  // Got an inbound call in the "office" context..
});

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.

Methods

on(string $event, callable $callback)

Attach an event handler for the $event.

Available In:

Parameters

$event string required Event name. Full list of events Relay.Calling.Call Events
$callback callable required Function 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('answered', function($call) {
  // Call has been answered from the remote party!
})->on('ended', function($call) {
  // Call has ended.. cleanup something?
});

off(string $event, callable $callback)

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

Available In:

Parameters

$event string required Event name. Full list of events Relay.Calling.Call Events
$callback callable optional Function 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.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);

begin()

This will start a call that was created with the newCall() method.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

<?php

$options = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
$client->calling->newCall($options)->then(
  function($call) {
    // Attach listeners you need on $call ...

    $call->begin();
  },
  function ($error) {
    // An error occurred creating the Call object.
  }
);

hangup()

Hangup the call.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Hangup all inbound calls in the pbx context if the $agent is not available.

<?php

$client->calling->onInbound('pbx', function($call) {
  if (!$agent->isAvailable()) {
    $call->hangup()->then(
      function($result) {
        // Call hanged up successfully
      },
      function ($error) {
        // An error occurred hanging up the call.
      }
    );
  }
});

answer()

Answer an inbound call.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Answer inbound calls in the office context.

<?php

$client->calling->onInbound('office', function($call) {
  // Attach listeners you need on $call ...

  $call->answer()->then(
    function($result) {
      // Call picked up successfully.
    },
    function ($error) {
      // An error occurred answering the call.
    }
  );
});

connect(device [, device2, ..., deviceN])

Attempt to connect an existing call to a new outbound call. 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

device ... deviceN Device or Device[] required A single, a list or an array of Device. Nested depends on whether to dial in serial or parallel.

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

PRO TIP: In the examples below we attach listeners on connect.connected and connect.failed to be notified about those events!

 

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

<?php

$options = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
$client->calling->newCall($options)->then(
  function($call) {
    $call->on('connect.connected', function($call) {
      // Your call has been connected to the first one that answered
    })->on('connect.failed', function($call) {
      // Your call failed to connect
    })->on('answered', function($call) {

      $call->connect(
        [ "type" => "phone", "to" => "+18991114444", "timeout" => 30 ],
        [ "type" => "phone", "to" => "+18991114445", "timeout" => 20 ]
      )->then($successCallback, $errorCallback);

    });

    $call->begin();
  },
  function ($error) {
    // An error occurred creating the Call object.
  }
);

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

$options = [ 'type' => 'phone', 'from' => '+1XXXXXXXXXX', 'to' => '+1YYYYYYYYYY' ];
$client->calling->newCall($options)->then(
  function($call) {
    $call->on('connect.connected', function($call) {
      // Your call has been connected to the first one that answered
    })->on('connect.failed', function($call) {
      // Your call failed to connect
    })->on('answered', function($call) {

      $call->connect(
        [ "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 ]
        ]
      )->then($successCallback, $errorCallback);

    });

    $call->begin();
  },
  function ($error) {
    // An error occurred creating the Call object.
  }
);

playMedia(array $media [, array $media2, ..., array $mediaN])

Play one or multiple media in a call.

Available In:

Parameters

media ... mediaN array required One or more associative arrays with the following structure:
[type] string required audio, tts or silence
[params][url] string required Http(s) URL to audio resource to play.
[params][text] string required TTS to play.
[params][language] string optional Default to en-US.
[params][gender] string optional male or female. Default to female.
[params][duration] number required Seconds of silence to play.

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlayMediaAction or Rejected with the exception.

Examples

Play an Mp3 file.

<?php

$media = [
  "type" => "audio",
  "params" => [
    "url" => "https://example.domain.com/audio.mp3"
  ]
];
$call->playMedia($media)
  ->then(function ($action) {
    // Use $action to interact with the media..
  })
  ->otherwise($errorCallback);

Play Text-to-Speech.

<?php

$media = [
  "type" => "tts",
  "params" => [
    "text" => "Welcome to SignalWire!"
  ]
];
$call->playMedia($media)
  ->then(function ($action) {
    // Use $action to interact with the media..
  })
  ->otherwise($errorCallback);

Play 5 seconds of silence.

<?php

$media = [
  "type" => "silence",
  "params" => [
    "duration" => 5
  ]
];
$call->playMedia($media)
  ->then(function ($action) {
    // Use $action to interact with the media..
  })
  ->otherwise($errorCallback);

Play multiple media elements in the call.

<?php

$call->playMedia(
  [ "type" => "silence", "params" => [ "duration" => 2 ] ],
  [ "type" => "tts", "params" => [ "text" => "Listen this awesome file!" ] ],
  [ "type" => "audio", "params" => [ "url" => "https://example.domain.com/audio.mp3" ] ],
  [ "type" => "silence", "params" => [ "duration" => 5 ] ],
  [ "type" => "tts", "params" => [ "text" => "Did you like it?" ] ]
)->then(function ($action) {
  // Use $action to interact with the media..
})
->otherwise($errorCallback);

playAudio(string $url)

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

Available In:

Parameters

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

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlayAudioAction or Rejected with the exception.

Examples

Play an Mp3 file.

<?php

$call->playAudio("https://example.domain.com/audio.mp3")->then(
  function($action) {
    // Use $action to interact with the media..
  },
  function ($error) {
    // An error occurred playing audio..
  }
);

playTTS(array $params)

This is a helper function that refines the use of playMedia(). This simplifies playing TTS.

Available In:

Parameters

[text] string required TTS to play.
[language] string optional Default to en-US.
[gender] string optional male or female. Default to female.

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlayTTSAction or Rejected with the exception.

Examples

Play TTS.

<?php

$params = ["text" => "Welcome to SignalWire!", "gender" => "male"];
$call->playTTS($params)->then(
  function($action) {
    // Use $action to interact with the media..
  },
  function ($error) {
    // An error occurred playing TTS..
  }
);

playSilence(int $duration)

This is a helper function that refines the use of playMedia(). This simplifies playing silence.

Available In:

Parameters

$duration integer required Seconds of silence to play.

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlaySilenceAction or Rejected with the exception.

Examples

Play silence for 5 seconds.

<?php

$call->playSilence(5)->then(
  function($action) {
    // Use $action to interact with the media..
  },
  function ($error) {
    // An error occurred playing silence..
  }
);

playMediaAndCollect(array $collect, array $media [, array $media2, ..., array $mediaN])

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

Available In:

Parameters

[collect] array required Object with initial_timeout, digits and speech keys.
[collect][initial_timeout] number required Timeout in seconds.
[collect][digits] array Optional if [collect][speech] is set.
[collect][digits][max] number required Max digits to collect.
[collect][digits][digit_timeout] number required Timeout in seconds between each digit.
[collect][digits][terminators] string optional DTMF digits that will end the recording.
Default not set.
[collect][speech] array Optional if [collect][digits] is set.
[collect][speech][end_silence_timeout] number optional How much silence to wait for end of speech.
Default 1 second.
[collect][speech][language] string optional Language to detect.
Default to en-US.
[collect][speech][hints] array optional Array of expected phrases to detect.
media ... mediaN array required One or more Media objects with the same structure used in .playMedia()

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlayMediaAndCollectAction or Rejected with the exception.

Examples

Attach a listener for the collect event and start collecting digits while playing a TTS.

<?php

$call->on('collect', function($call, $result) {
  // Inspect $result->params to see the digits..
});

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$tts = [ "type" => "tts", "params" => [ "text" => "Listen this awesome file!" ] ];
$call->playMediaAndCollect($collect, $tts)->then(
  function($action) {
    // Use $action to interact with the media..
  },
  function ($error) {
    // An error occurred collecting..
  }
);

playAudioAndCollect(array $collect, string $url)

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

Available In:

Parameters

$collect array required See the parameters of playMediaAndCollect() for all the properties.
$url string required Http(s) URL to audio resource to play.

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlayAudioAndCollectAction or Rejected with the exception.

Examples

Collect digits while playing an Mp3 file.

<?php

$call->on('collect', function($call, $result) {
  // Inspect $result->params to see the digits..
});

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$call->playAudioAndCollect($collect, 'https://example.domain.com/audio.mp3')->then(
  function($action) {
    // Use $action to interact with the media..
  },
  function ($error) {
    // An error occurred collecting..
  }
);

playTTSAndCollect(array $collect, array $params)

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

Available In:

Parameters

$collect array required See the parameters of playMediaAndCollect() for all the properties.
[params] array required Object with the following properties:
[params][text] string required TTS to play.
[params][language] string optional Default to en-US.
[params][gender] string optional male or female. Default to female.

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlayTTSAndCollectAction or Rejected with the exception.

Examples

Collect digits while playing TTS.

<?php

$call->on('collect', function($call, $result) {
  // Inspect $result->params to see the digits..
});

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$params = [ "text" => "Listen this awesome file!", "gender" => "male" ];
$call->playTTSAndCollect($collect, $params)->then(
  function($action) {
    // Use $action to interact with the media..
  },
  function ($error) {
    // An error occurred collecting..
  }
);

playSilenceAndCollect(array $collect, int $duration)

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

Available In:

Parameters

$collect array required See the parameters of playMediaAndCollect() for all the properties.
$duration integer required Seconds of silence to play.

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.PlaySilenceAndCollectAction or Rejected with the exception.

Examples

Collect digits while playing 5 seconds of silence.

<?php

$call->on('collect', function($call, $result) {
  // Inspect $result->params to see the digits..
});

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$call->playSilenceAndCollect($collect, 5)->then(
  function($action) {
    // Use $action to interact with the media..
  },
  function ($error) {
    // An error occurred collecting..
  }
);

record(array $params)

Start recording the call.

Available In:

Parameters

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

Returns

React\Promise\Promise - A Promise Resolved with a Relay.Calling.RecordAction or Rejected with the exception.

Examples

Start recording the call for both direction in stereo mode.

<?php

$params = [
  "audio" => [
    "stereo" => true,
    "direction" => "both"
  ]
];
$call->record($params)->then(
  function($action) {
    // Use $action to interact with the recording..
  },
  function ($error) {
    // An error occurred playing silence..
  }
);

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.

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.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.playing A playback in 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.recording The call is being recorded.
record.no_input The recording failed due to no input.
record.finished The recording has ended.

Collect Events

To track a collect state.

collect The collect action on the call has ended.

Relay.Calling.RecordAction

This object represents a recording action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Start recording in stereo mode and stop it if $agent is not available.

<?php

$params = [
  "audio" => [
    "stereo" => true
  ]
];
$call->record($params)
  ->then(function($action) {
    if ($agent->isAvailable() === false) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);
);

Relay.Calling.PlayMediaAction

This object represents a media action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Play an audio file and stop it if $agent is not available.

<?php

$media = [
  "type" => "audio",
  "params" => [
    "url" => "https://example.domain.com/audio.mp3"
  ]
];
$call->playMedia($media)
  ->then(function ($action) {
    if ($agent->isAvailable() === false) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Relay.Calling.PlayAudioAction

This object represents an audio action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Play an audio file and stop it if $agent is not available.

<?php

$call->playAudio("https://example.domain.com/audio.mp3")
  ->then(function ($action) {
    if ($agent->isAvailable() === false) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Relay.Calling.PlayTTSAction

This object represents a TTS action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Play TTS in the call and stop it if $agent is not available.

<?php

$params = ["text" => "Hey There! Welcome to SignalWire."];
$call->playTTS($params)
  ->then(function ($action) {
    if ($agent->isAvailable() === false) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Relay.Calling.PlaySilenceAction

This object represents a silence action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Play 10 seconds of silence and then stop it if $agent is available.

<?php

$call->playSilence(10)
  ->then(function ($action) {
    if ($agent->isAvailable()) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Relay.Calling.PlayMediaAndCollectAction

This object represents a media & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Collecting digits while playing an audio file and stop it if $agent is not available.

<?php

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$media = [
  "type" => "audio",
  "params" => [
    "url" => "https://example.domain.com/audio.mp3"
  ]
];
$call->playMediaAndCollect($collect, $media)
  ->then(function ($action) {
    if ($agent->isAvailable() === false) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Relay.Calling.PlayAudioAndCollectAction

This object represents an audio & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Collecting digits while playing an audio file and stop it if $agent is not available.

<?php

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$call->playAudioAndCollect($collect, "https://example.domain.com/audio.mp3")
  ->then(function ($action) {
    if ($agent->isAvailable() === false) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Relay.Calling.PlayTTSAndCollectAction

This object represents a TTS & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Collecting digits while playing TTS in the call and stop it if $agent is not available.

<?php

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$params = ["text" => "Hey There! Welcome to SignalWire."];
$call->playTTSAndCollect($collect, $params)
  ->then(function ($action) {
    if ($agent->isAvailable() === false) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Relay.Calling.PlaySilenceAndCollectAction

This object represents a silence & collect action that is currently active on a call.

Properties

call Relay.Calling.Call This is the call the action is occurring on.

Methods

stop()

Stop the action immediately.

Available In:

Parameters

None

Returns

React\Promise\Promise - A Promise Resolved or Rejected with the Relay response.

Examples

Collecting digits while playing 10 seconds of silence and then stop it if $agent is available.

<?php

$collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
$call->playSilenceAndCollect($collect, 10)
  ->then(function ($action) {
    if ($agent->isAvailable()) {
      $action->stop()->then($successCallback, $errorCallback);
    }
  })
  ->otherwise($errorCallback);

Examples

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

Inbound Calls

Receive inbound calls from the office context, answer them and play an Mp3 audio. Write logs when the play state change.

<?php

$client = new SignalWire\Relay\Client([
  "host" => "example.signalwire.com",
  "project" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
  "token" => "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
]);

$errorHandler = function($error) {
  echo "Error: " . $error->getMessage();
};

$inboundCallHandler = function($call) use ($errorHandler) {
  echo "\n New inbound call in context: '{$call->context}' \n";

  $call->on('play.stateChange', function($call, $params) {
    echo "\n CallId: {$call->id} - Play state changed to: {$params->state} \n";
  });

  $call->on('answered', function($call) use ($errorHandler) {
    $audioUrl = 'https://cdn.signalwire.com/default-music/welcome.mp3';
    $call->playAudio($audioUrl)->otherwise($errorHandler);
  });

  $call->answer()->otherwise($errorHandler);
};

$client->on('signalwire.ready', function($client) use ($inboundCallHandler, $errorHandler) {
  $client->calling->onInbound('office', $inboundCallHandler)
    ->then(function() {
      echo "\n You are listening for inbound calls from 'office' context.. \n";
    })
    ->otherwise($errorHandler);
});

$client->connect();

Outbound Calls

Make a call and, on answered, start collect user digits while playing TTS. When collect has completed, logs the result.

<?php

$client = new SignalWire\Relay\Client([
  "host" => "example.signalwire.com",
  "project" => "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
  "token" => "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
]);

$errorHandler = function($error) {
  echo "Error: " . $error->getMessage();
};

$client->on('signalwire.ready', function($client) use ($errorHandler) {

  $params = [
    'type' => 'phone',
    'from' => '+1XXXXXXXXXX',
    'to' => '+1YYYYYYYYYY'
  ];
  $client->calling->newCall($params)->then(function($call) use ($errorHandler) {

    $call->on('answered', function($call) use ($errorHandler) {
      $collect = [ "initial_timeout" => 10, "digits" => [ "max" => 3, "digit_timeout" => 5 ] ];
      $params = [ "text" => "Welcome to SignalWire!" ];
      $call->playTTSAndCollect($collect, $params)->otherwise($errorHandler);
    });

    $call->on('collect', function($call, $result) {
      echo "Digits collected: " . $result->params->digits;
      print_r($result->params);
    });

    $call->begin()->otherwise($errorHandler);

  })->otherwise($errorHandler);

});

$client->connect();