Created
March 6, 2021 08:24
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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