Twilio can be set up to use the REST API standard. (Wordpress has a tutorial for setting up REST routes and endpoints.)
Create a custom Twilio endpoint on Wordpress using register_rest_route
. This can be set up as POST or GET, but it has to match your Twilio fax number settings.
For example, put the following in your theme's functions.php
file (you should create a child theme before doing this if you haven't already):
function process_twilio_fax_response( $request ) {
$params = $request->get_params();
// $params should have the data Twilio POSTed as JSON to the API.
// For example, $params['account_sid'] should have the account_sid.
}
// This code registers the API endpoint and tells wordpress to call process_twilio_fax_response
// when data is POSTed to /wp-json/twilio/callback
add_action( 'rest_api_init', function () {
register_rest_route( 'twilio', '/callback', array(
// WP_REST_Server:READABLE = GET only
// WP_REST_Server:CREATABLE = POST only
// WP_REST_Server:EDITABLE = POST, PUT, PATCH
// WP_REST_Server:DELETABLE = DELETE only
// WP_REST_Server:ALLMETHODS = GET, POST, PUT, PATCH, DELETE
'methods' => WP_REST_Server:CREATABLE,
'callback' => 'process_twilio_fax_response',
) );
} );
This will create an endpoint at /wp-json/twilio/callback (e.g. https://www.example.com/wp-json/twilio/callback
) which can be configured on your Twilio fax number as the "A Fax Comes In" URL (or "Fax Status Changes", or "Primary Handler Fails").
When Twilio makes a POST request to the endpoint, the callback function (in this case process_twilio_fax_response
) will be called with the request object passed as a parameter. You can then get the JSON data as an associative array by calling get_params()
method on the parameter (in this case $request->get_params()
).
Please be aware that this example has no authentication, sanitation, or validation, all of which are necessary for any public-facing REST route.
If you are debugging on localhost
, the callback URL will be http://localhost/wp-json/twilio/callback
. Twilio won't be able to POST to localhost
since it is accessible only locally, but you can set up a web tunnel through a random, temporary URL on linux using ngrok. In your Twilio fax number setup, change any reference to localhost
domain with the ngrok domain, keeping all other URL resources, queries, etc. the same. E.g.:
https://localhost/SomeWordpressDomainName/wp-json/twilio/callback
becomes
https://randomDomainNameFromNGROK.ngrok.io/SomeWordpressDomainName/wp-json/twilio/callback