How to Process Form Results with PHP and a Webhook
In this tutorial, we’ll show you how to process the data submitted when a user fills out a form with PHP.
About Webhooks
A webhook is computing code that executes on your website or on the cloud whenever a form is submitted. FormSmarts triggers the code’s execution by sending an HTTP request to a callback URL you’ve set up. The code receives the form data from the request, allowing you to perform useful actions with it.
Webhook Example in PHP
The code below shows how to read the form response sent by a webhook in PHP. We've also created more complete webhook examples with the FormSmarts API & Webhook Client for Python:
- How to send an SMS confirmation when someone submits a form
- A simple online election application
- A property maintenance form that sends urgent requests to Slack
<?php
// Parse the form response sent by FormSmarts (JSON in the request body)
$form = json_decode(file_get_contents('php://input'));
print("{$form->form_name} ({$form->form_id}): {$form->fs_ref_num}, {$form->api_date}\n");
// Iterate over the fields, in the order they appear on the form
foreach ($form->fields as $field) {
print("{$field->field_name} ({$field->field_datatype}): {$field->field_value}\n");
// Form attachments have additional properties (field_value is empty)
if ($field->field_datatype === 'attachment') {
print("{$field->attachment_filename}: {$field->attachment_url}\n");
}
}
// Payment information, if applicable
if (isset($form->payment)) {
$pay = $form->payment;
print("Paid {$pay->amount} {$pay->currency} with {$pay->processor_name}: {$pay->transaction_id}\n");
}
// Form context, if available
if (isset($form->context)) {
print("Context {$form->context->label}: {$form->context->value}\n");
}
The webhook documentation describes all the attributes of the form response.
Webhook Authentication
Before taking any actions based on the data received, you should always authenticate the webhook message to verify that the request genuinely originates from FormSmarts. Otherwise, anyone who knows the URL of your webhook could send it fake form responses.
How to Authenticate a Webhook Message
Webhook callbacks are signed with a JSON Web Token (JWT) in the Authorization header. You can verify a request with the API & Webhook Client for Python or Node.js, with a PHP module as shown below, or with a JWT library in any other language. The token must be:
- Signed with your Webhook Key (HMAC SHA-256). You will find your Webhook Key in the Security Settings of your account. Your Webhook Key is secret: don't share it with anyone.
- Issued by
formsmarts.com(iss claim) for a webhook (aud claim:webhook) - Valid at the time of the request (nbf and exp claims): tokens expire after 15 minutes
Complete Example with Authentication
Let's now revisit the example above and add message authentication. We verify the token with the lcobucci/jwt PHP module (PHP 8.1 or later). Install it with Composer:
composer require lcobucci/jwt lcobucci/clock Downloads
You can download the PHP source of this example:
The Code
First edit formsmarts_webhook_example_auth_v2_config.php and paste your Webhook Key:
<?php
// Your secret Webhook Key: Security Settings of your account, https://formsmarts.com/account/view#security-settings
// Keep it secret: don't commit it to source control or share it.
const FORMSMARTS_WEBHOOK_KEY = '';
The callback script, formsmarts_webhook_example_auth_v2.php, becomes:
<?php
declare(strict_types=1);
// Requires PHP 8.1+ and: composer require lcobucci/jwt lcobucci/clock
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Encoding\CannotDecodeContent;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token\InvalidTokenStructure;
use Lcobucci\JWT\Token\Parser;
use Lcobucci\JWT\Token\UnsupportedHeaderFound;
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
use Lcobucci\JWT\Validation\Constraint\LooseValidAt;
use Lcobucci\JWT\Validation\Constraint\PermittedFor;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Lcobucci\JWT\Validation\Validator;
require 'vendor/autoload.php';
require_once 'formsmarts_webhook_example_auth_v2_config.php';
function reject(string $reason): never
{
http_response_code(401);
error_log("FormSmarts webhook rejected: $reason");
exit;
}
// Get the bearer token from the Authorization header
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$parts = explode(' ', $header, 2);
if (count($parts) !== 2 || strcasecmp($parts[0], 'Bearer') !== 0) {
reject('Authorization header missing or invalid.');
}
// Verify the request was sent by FormSmarts: the token must be signed with your Webhook Key,
// issued by FormSmarts for a webhook, and not expired.
try {
$token = (new Parser(new JoseEncoder()))->parse($parts[1]);
(new Validator())->assert(
$token,
new SignedWith(new Sha256(), InMemory::plainText(FORMSMARTS_WEBHOOK_KEY)),
new IssuedBy('formsmarts.com'),
new PermittedFor('webhook'),
new LooseValidAt(SystemClock::fromSystemTimezone(), new DateInterval('PT5S'))
);
} catch (CannotDecodeContent | InvalidTokenStructure | UnsupportedHeaderFound | RequiredConstraintsViolated $e) {
reject($e->getMessage());
}
// The request is from FormSmarts: process the form response.
// Note: don't use the request's data before this line!
$form = json_decode(file_get_contents('php://input'));
// Log file for demonstration & debugging
$fh = fopen('/tmp/formsmarts_webhook_call.log', 'a');
fwrite($fh, "{$form->form_name} ({$form->form_id}): {$form->fs_ref_num}, {$form->api_date}\n");
// Iterate over the fields, in the order they appear on the form
foreach ($form->fields as $field) {
fwrite($fh, "{$field->field_name} ({$field->field_datatype}): {$field->field_value}\n");
// Form attachments have additional properties (field_value is empty)
if ($field->field_datatype === 'attachment') {
fwrite($fh, "{$field->attachment_filename}: {$field->attachment_url}\n");
}
}
// Payment information, if applicable
if (isset($form->payment)) {
$pay = $form->payment;
fwrite($fh, "Paid {$pay->amount} {$pay->currency} with {$pay->processor_name}: {$pay->transaction_id}\n");
}
// Form context, if available
if (isset($form->context)) {
fwrite($fh, "Context {$form->context->label}: {$form->context->value}\n");
}
fclose($fh);
Set Up the Webhook on FormSmarts
Follow the instructions in the webhook documentation to register the callback URL for the form you've created earlier.