PHP Encryption v2
Encryption Class
Create a new Encryption.php file and paste in the following PHP code.
<?php
class Encryption
{
/**
* Encrypt the string containing customer details with the IV and secret
* key provided in the developer portal
*
* @return $encryptedPayload
*/
public function encrypt($ivKey, $secretKey, $payload = []) {
//The encryption method to be used
$encrypt_method = "AES-256-CBC";
// Hash the secret key
$key = hash('sha256', $secretKey);
// Hash the iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $ivKey), 0, 16);
$encrypted = openssl_encrypt(
json_encode($payload, true), $encrypt_method, $key, 0, $iv
);
//Base 64 Encode the encrypted payload
$encryptedPayload = base64_encode($encrypted);
return $encryptedPayload;
}
}
?>
Encryption Class Usage (Apache)
Create the file below in your web server root document, e.g /var/www/html/checkout-demo
. Create a file CheckoutEncryption
and paste in the following PHP code.
To test the PHP script without a web server, use the following command on the script:
**$ php -S localhost:3000 CheckoutEncryption.php**
<?php
// Alternatively configure this on your web server(apache/nginx) to avoid CORS error
header("Access-Control-Allow-Origin: *");
class CheckoutEncryption {
private $accessKey;
private $ivKey;
private $secretKey;
private $request;
public function __construct() {
$this->accessKey = "<YOUR_ACCESS_KEY>";
$this->ivKey = "<YOUR_IV_KEY>";
$this->secretKey = "<YOUR_SECRET_KEY>";
$this->request = json_decode(file_get_contents('php://input'), true);
}
public function processEncryption() {
$encryptedParams = $this->encrypt($this->ivKey, $this->secretKey, $this->request);
$result = [
'params' => $encryptedParams,
'accessKey' => $this->accessKey,
'countryCode' => $this->request['countryCode']
];
echo json_encode($result);
}
/**
* Encrypt the string containing customer details with the IV and secret
* key provided in the developer portal
*
* @return $encryptedPayload
*/
public function encrypt($ivKey, $secretKey, $payload = []) {
//The encryption method to be used
$encrypt_method = "AES-256-CBC";
// Hash the secret key
$key = hash('sha256', $secretKey);
// Hash the iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $ivKey), 0, 16);
$encrypted = openssl_encrypt(
json_encode($payload, true), $encrypt_method, $key, 0, $iv
);
//Base 64 Encode the encrypted payload
$encryptedPayload = base64_encode($encrypted);
return $encryptedPayload;
}
}
$class = new CheckoutEncryption();
$class->processEncryption();