Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michaelphipps/2351edcfcd38a9a578d6ced89b860be3 to your computer and use it in GitHub Desktop.
Save michaelphipps/2351edcfcd38a9a578d6ced89b860be3 to your computer and use it in GitHub Desktop.
Send a JSON message with Ably.com using JWT Authentication in PHP without using the official Ably PHP SDK.
<?php
// $ composer require lcobucci/jwt
require __DIR__ . '/vendor/autoload.php';
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Hmac\Sha256;
$ably_publish_key = <YOUR PUBLISH KEY HERE>
list($api_key, $api_secret) = explode(":", $ably_publish_key);
$secret = base64_encode($api_secret);
$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::base64Encoded($secret));
assert($config instanceof Configuration);
$now = new DateTimeImmutable();
$token = $config->builder(\Lcobucci\JWT\Encoding\ChainedFormatter::withUnixTimestampDates()) // withUnixTimestampDates removes microseconds
->withHeader('kid', $api_key)
->issuedAt($now)
->expiresAt($now->modify('+5 minutes'))
->withClaim('x-ably-capability', "{\"*\":[\"*\"]}")
->getToken($config->signer(), $config->signingKey());
$params = http_build_query(["data"=> json_encode(["message"=>"Hello World"])]);
$headers[] = "Authorization: Bearer ".$token->toString();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://rest.ably.io/channels/<YOUR CHANNEL>/publish");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$output = curl_exec($ch);
curl_close($ch);
// inspect the contents of $output to see if it worked!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment