PHP Library

Add SADAD Pay to a PHP website with the official Composer package.

The SADAD Pay PHP Library is a Composer package that wraps the main API calls: tokens, creating an invoice, getting an invoice and refunding it. Use it to add SADAD Pay to a PHP website or plugin without writing the HTTP requests yourself.

ItemDetails
Packagesadad-payment/library
Source codegithub.com/sadad-pay/php-library
Latest version1.0.0
RequirementsPHP 7 or later, with the curl and json extensions
LicenceGPL-3.0

📘

What the library covers

The library uses the Hosted Payment Page flow: you create an invoice and send the customer to the SADAD Pay payment page. For other features, such as Embedded Payment or Product Links, call the API directly. See What the library does not cover.

Step 1: Install

Run this in your project folder:

composer require sadad-payment/library

Then load Composer's autoloader and import the class:

<?php
require __DIR__ . '/vendor/autoload.php';

use Sadad\Library\SadadLibrary;

Step 2: Connect to SADAD Pay

Create a SadadLibrary object with your Client Key and Client Secret. You find them in the portal under Profile → Update Profile → API. See API Keys & Authentication.

$sadad = new SadadLibrary([
    'clientId'     => getenv('SADAD_CLIENT_KEY'),    // Client Key
    'clientSecret' => getenv('SADAD_CLIENT_SECRET'), // Client Secret
    'isTest'       => true,                          // true = Sandbox, false = Live
    'log'          => __DIR__ . '/logs/sadad.log',   // optional: log every request and response
]);
OptionRequiredDescription
clientIdYesYour Client Key
clientSecretYesYour Client Secret
isTestYestrue sends requests to Sandbox (apisandbox.sadadpay.net), false to Live (api.sadadpay.net). Must be a boolean.
logNoPath to a log file. When set, the library writes each request and response to it.

🚧

Keep your keys out of your code

Load the Client Key and Client Secret from environment variables or a secure config file, never from code you commit. Sandbox and Live have different keys: use the keys for the environment that matches isTest.

Step 3: Get a refresh token

The library authenticates with a refresh token. Generate it once and store it securely, for example in your database or config.

$sadad->generateRefreshToken();

$refreshToken = $sadad->refreshToken; // store this securely

You pass the refresh token to every other method. The library uses it to get a new access token for each request, so you do not manage access tokens yourself.

If generateRefreshToken() throws an exception, check that the Client Key and Client Secret are correct and belong to the same environment as isTest.

Step 4: Create an invoice

Build the invoice and pass it inside an Invoices array.

$invoice = [
    'ref_Number'      => 'ORDER-1001',                         // your order number
    'amount'          => 12.500,                               // in KWD
    'customer_Name'   => 'Ahmed Ali',
    'customer_Mobile' => SadadLibrary::validatePhone('99999999'),
    'customer_Email'  => '[email protected]',
    'currency_Code'   => 'KWD',
];

try {
    $result = $sadad->createInvoice(['Invoices' => [$invoice]], $refreshToken);

    $invoiceId  = $result['InvoiceId'];  // save it with your order
    $invoiceUrl = $result['InvoiceURL']; // the payment page

    header('Location: ' . $invoiceUrl);
    exit;
} catch (Exception $e) {
    // $e->getMessage() is the SADAD Pay errorKey, for example "CustomerNameRequired"
    error_log('SADAD Pay: ' . $e->getMessage());
}

createInvoice() returns:

KeyDescription
InvoiceIdThe SADAD Pay invoice ID. Save it with your order: you need it to check the payment.
InvoiceURLThe payment page, for example https://sandbox.sadadpay.net/pay/5527187292968. Redirect the customer here.

The invoice accepts the same fields as POST /api/Invoice/insert, such as items, expiry_Date and lang. See Hosted Payment Page for the full list.

Prices in other currencies

If your store prices are in another currency, convert them to KWD with getKWDAmount(). It uses SADAD Pay's current exchange rates.

// Convert 40 USD to KWD. The third argument must match isTest.
$amountKwd = SadadLibrary::getKWDAmount('USD', 40, true);

$invoice['amount']        = $amountKwd;
$invoice['currency_Code'] = 'USD';

🚧

Pass the environment to getKWDAmount()

The third argument chooses Sandbox (true) or Live (false), and it defaults to false. Pass the same value you use for isTest. If the currency is not supported, the method throws an exception.

Clean up phone numbers

validatePhone() turns a phone number into digits only. It converts Arabic and Persian digits, removes spaces, + and a leading 00, and checks the length is 3 to 14 digits.

SadadLibrary::validatePhone('+965 9999 9999'); // "96599999999"
SadadLibrary::validatePhone('٩٩٩٩٩٩٩٩');       // "99999999"

Step 5: Check the payment

When the customer comes back to your Success or Fail URL, get the invoice and check its status. Never mark an order as paid just because the customer reached your Success URL.

$info    = $sadad->getInvoiceInfo($invoiceId, $refreshToken);
$invoice = $info['response'];

if (
    $invoice['status'] === 'Paid'
    && $invoice['ref_Number'] === $order->number
    && abs($invoice['amount'] - $order->total) < 0.001
) {
    $order->markPaid($invoice['transactionID']);
}

getInvoiceInfo() returns the full response of GET /api/Invoice/getbyid. See Verify Payment Status for every field and the checks to make. Set your Success and Fail URLs in the portal under Profile → Update Profile → API.

To get notified even when the customer does not come back, also set up Webhooks.

Refund an invoice

try {
    $refund = $sadad->refundInvoice([
        'invoice_Id'    => $invoiceId,
        'amount'        => 5.000,               // in KWD
        'refund_Type'   => 'DeductFromBalance',
        'currency_Code' => 'KWD',
        'note'          => 'Item returned',
    ], $refreshToken);

    $refundId = $refund['response']['refund_Id'];
} catch (Exception $e) {
    error_log('SADAD Pay refund: ' . $e->getMessage());
}

The fields are the same as POST /api/Refund/insert. See Refunds.

❗️

Refund invoices throw an exception

refundInvoice() only succeeds when the response contains a refund_Id, that is, when the refund is taken from your balance. When you use PayAmount, or your balance is too low, SADAD Pay creates a refund invoice instead and returns an invoice_Key. The library treats this as a failure and throws an exception, even though the refund invoice was created. Check Refunds and Invoices in the portal before trying again, or call POST /api/Refund/insert directly to handle both responses.

Methods

MethodReturnsDescription
new SadadLibrary($config)objectConnects to Sandbox or Live. Throws an exception if an option is missing or wrong.
generateRefreshToken()—Gets a refresh token and stores it in $sadad->refreshToken
getAccessToken($refreshToken)stringGets an access token. The other methods call this for you.
createInvoice($request, $refreshToken)arrayCreates an invoice. Returns InvoiceId and InvoiceURL.
getInvoiceInfo($invoiceId, $refreshToken)arrayGets the invoice, as returned by Invoice/getbyid
refundInvoice($request, $refreshToken)arrayRefunds a paid invoice from your balance
SadadLibrary::getKWDAmount($currency, $amount, $isTest)stringConverts an amount to KWD
SadadLibrary::getCurrencyList($isTest)arrayThe supported currencies and their exchange rates
SadadLibrary::validatePhone($phone)stringCleans a phone number to digits only
SadadLibrary::filterInput($name, $type)stringReads a value from $_GET, $_POST and so on, with HTML escaped
sendRequest($url, $headers, $request, $type)arraySends any request to the API. Use it for endpoints the library does not wrap.

All methods throw an Exception when something goes wrong. Wrap calls in try/catch.

What the library does not cover

The library wraps invoices and refunds only. For anything else, call the API directly, either with your own HTTP client or with sendRequest():

// Example: call an endpoint the library does not wrap
$accessToken = $sadad->getAccessToken($refreshToken);

$links = $sadad->sendRequest(
    'https://apisandbox.sadadpay.net/api/PaymentLink/getall',
    ['Content-Type: application/json', 'Authorization: Bearer ' . $accessToken],
    [],
    'GET'
);

Troubleshooting

ProblemWhat to check
Ops, you have to provide the "isTest" mode.Add 'isTest' => true or false. It must be a boolean, not "true".
Ops, we could not generate Sadad refresh token.The Client Key or Client Secret is wrong, or belongs to the other environment
Ops, we could not generate Sadad access token.The refresh token is wrong or no longer valid. Generate a new one with generateRefreshToken().
Curl extension is not loadedAsk your hosting provider to enable the PHP curl extension
Currency … is not found in Sadad Currency listThat currency is not supported. Check getCurrencyList().
An errorKey such as CustomerNameRequiredThe invoice is missing a field. See the errors in Hosted Payment Page.

Next steps

  • Follow the Go-Live Checklist before you switch isTest to false.
  • Using WooCommerce, Magento or another platform? See the ready-made plugins.