I want to send and manage faxes using PHP only (no JavaScript or cron, if possible) through Twilio from my linux+Apache+Wordpress site. (Development is on a Wordpress site through my localhost using ngrok.)
I have been able to set up a Wordpress page (template) to send faxes using Twilio's fax API. After the fax is sent, though, Twilio is replying with JSON in a POST response (I think), and expecting my site to respond in some way. I have a callback URL in place, but this seems to be an asynchronous call, which I don't know how to handle though Wordpress. (I want to stay within Wordpress site if possible for security and convenience.)
I have no experience with managing this type of communication between servers; I have been reading the Twilio docs, but I think I am making a fundamental mistake somewhere...I get the gist of what needs to be done, but not how it works.
How does managing Twilio's asynchronous calls work using PHP within Wordpress?
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.phpfile (you should create a child theme before doing this if you haven't already):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 callingget_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 behttp://localhost/wp-json/twilio/callback. Twilio won't be able to POST tolocalhostsince 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 tolocalhostdomain with the ngrok domain, keeping all other URL resources, queries, etc. the same. E.g.:becomes