Skip to content

Instantly share code, notes, and snippets.

@xthexder
Last active May 22, 2022 11:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save xthexder/6091823 to your computer and use it in GitHub Desktop.
Save xthexder/6091823 to your computer and use it in GitHub Desktop.
ShopifyMultipass - Ported to PHP
<?php
date_default_timezone_set("UTC");
class ShopifyMultipass {
private $encryption_key;
private $signature_key;
public function __construct($multipass_secret) {
// Use the Multipass secret to derive two cryptographic keys,
// one for encryption, one for signing
$key_material = hash("sha256", $multipass_secret, true);
$this->encryption_key = substr($key_material, 0, 16);
$this->signature_key = substr($key_material, 16, 16);
}
public function generate_token($customer_data_hash) {
// Store the current time in ISO8601 format.
// The token will only be valid for a small timeframe around this timestamp.
$customer_data_hash["created_at"] = date("c");
// Serialize the customer data to JSON and encrypt it
$ciphertext = $this->encrypt(json_encode($customer_data_hash));
// Create a signature (message authentication code) of the ciphertext
// and encode everything using URL-safe Base64 (RFC 4648)
return strtr(base64_encode($ciphertext . $this->sign($ciphertext)), '+/', '-_');
}
private function encrypt($plaintext) {
// Use a random IV
$iv = openssl_random_pseudo_bytes(16);
// Use IV as first block of ciphertext
return $iv . openssl_encrypt($plaintext, "AES-128-CBC", $this->encryption_key, OPENSSL_RAW_DATA, $iv);
}
private function sign($data) {
return hash_hmac("sha256", $data, $this->signature_key, true);
}
}
$customer_data = array(
"email" => "bob@shopify.com",
"remote_ip" => "127.0.0.1"
);
$multipass = new ShopifyMultipass("multipass secret from shop admin");
$token = $multipass->generate_token($customer_data);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment