Alipay Payment Gateway Integration PHP | Devstringx Technologies

Alipay is the most popular Payment Gateway in Asia. In China , millions of transactions are processed using Alipay each day. It is a push-based, single-use and synchronous method of payment that enables your customer to take action to authorize the push of funds through a redirect and get immediate confirmation about the success or failure of a payment.

Please follow the below steps to integrate the API.

Step 1. Login to My Alipay with your assigned account information or you can use the sandbox for buyer and sender information.

Click here to get the sandbox credentials.

Copy the PID & signature key from the sandbox and also remember to change these credentials from the live credential when you are going to the production environment.

Step 2. Create new file alipay/Alipay.php

/* — — — — — — — — — — — — — -*/

class AlipayException extends Exception {}

class Alipay {

//For testing purposes

const ENVIRONMENT = “development”;

private $_partner_id = “”;

private $_key = “”;

private $_endpoint = “”;

public function __construct()

if (self::ENVIRONMENT == “development”)

$this->_partner_id = “208810112*******”;

$this->_key = “760bdzec6y9goq7ctyx9************”;

$this->_endpoint = “https://openapi.alipaydev.com/gateway.do";

$this->_partner_id = “”; // replace with your production partner ID

$this->_key = “”; // replace with your production private key

$this->_endpoint = “https://mapi.alipay.com/gateway.do";

public function createPayment($sale_id = “”, $amount = 0, $currency = “USD”, $description = “”, $return_url = “”, $notify_url = “”, $is_mobile = false)

‘body’ => $description,

‘service’ => $is_mobile ? ‘create_forex_trade_wap’ : ‘create_forex_trade’,

‘out_trade_no’ => $sale_id,

‘currency’ => $currency,

‘total_fee’ => $amount,

‘subject’ => $description,

‘return_url’ => $return_url,

‘notify_url’ => $notify_url,

‘partner’ => $this->_partner_id,

‘_input_charset’ => “utf-8”

return $this->_endpoint . “?” . $this->_prepData($data);

public function verifyPayment($data = array())

$sign = $data[‘sign’];

unset($data[‘sign’], $data[‘sign_type’]);

$new_sign = $this->_sign($data);

if ($sign != $new_sign)

throw new AlipayException(“Hashes do not match: $sign — $new_sign (Transaction #{$data[‘out_trade_no’]}).”);

‘service’ => ‘notify_verify’,

‘partner’ => $this->_partner_id,

‘notify_id’ => $data[‘notify_id’]

$response = $this->_send(http_build_query($request), “GET”);

if (preg_match(“/true$/i”, $response))

if ($data[‘trade_status’] == “TRADE_FINISHED”)

return true;

throw new AlipayException(“Alipay transaction is invalid (Transaction #{$data[‘out_trade_no’]}).”);

return false;

private function _send($data = array(), $method = “GET”)

$method = strtoupper($method);

if ($method == “GET”)

$curl = curl_init($this->_endpoint . “?$data”);

curl_setopt($curl, CURLOPT_POST, false);

$curl = curl_init($this->_endpoint . “?_input_charset=utf-8”);

curl_setopt($curl, CURLOPT_POST, true);

curl_setopt($curl, CURLOPT_HEADER, 0);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_SSLVERSION, 3);

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);

curl_setopt($curl, CURLOPT_CAINFO, “./alipay_ca.pem”);

$response = curl_exec($curl);

$error = curl_error($curl);

curl_close($curl);

throw new Exception($error);

return $response;

private function _prepData($data = array())

$data[‘sign’] = $this->_sign($data);

$data[‘sign_type’] = “MD5”;

return http_build_query($data);

private function _sign($data = array())

foreach ($data as $k => $v)

return md5(substr($query, 0, -1) . $this->_key);

/* — — — — — — — — — — — — — -*/

Remember to these changes:

1.ENVIRONMENT var value should not “development”on production environment.

2.Change Pid value and signature key (use sandbox credential for development environment and real credentials for production environment.

Step 3. Create new folder alipay/test

Step 4. Create new file alipay/test/transaction.php

/* — — — — — — — — — — — — — — */

require_once getcwd() . “/../Alipay.php”;

$sale_id = uniqid();

$amount = 10.25;

$description = “A pair of shoes”;

// Associate the sale id with uuid in your database for a look up once Alipay

// pings your notify_url

$return_url = “http://localhost/alipay/tests/return.php?sale_id=$sale_id";

$notify_url = “http://localhost/alipay/tests/notify.php?id=$uuid";

function uuid()

$data = openssl_random_pseudo_bytes(16);

$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0010

$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6–7 to 10

return vsprintf(‘%s%s-%s-%s-%s-%s%s%s’, str_split(bin2hex($data), 4));

$alipay = new Alipay();

// Generates a one-time URL to redirect the Buyer to

$approve = $alipay->createPayment($sale_id, $amount, “USD”, $description, $return_url, $notify_url);

echo “<a href=’$approve’>Test Transaction Link</a>”;

/* — — — — — — — — — — — */

Change the value of $sale_id, $description, $amount

Step 4. Create the new file alipay/test/return.php

/* — — — — — — — — — — — */

$sale_id = $_GET[‘sale_id’];

echo “<h4>Your payment is being processed. Thank you!</h4>”;

echo “<small>Sale ID: $sale_id.</small>”;

/* — — — — — — — — — — — -*/

Step 5. Create the new file alipay/test/notify.php

require_once getcwd() . “/../Alipay.php”;

$tid = $_POST[‘out_trade_no’];

$tno = $_POST[‘trade_no’];

$total_amount = $_POST[‘total_fee’]; // don’t forget to substract Alipay Transaction fee

$alipay = new Alipay();

// @todo: Verify system transaction ID hasn’t been used by looking it up in your DB.

if ($alipay->verifyPayment($_POST) === false) // Transaction isn’t complete

echo “Unable to verify payment.”;

return false;

} catch (Exception $e) { // Connection error

echo $e->getMessage();

return false;

} catch (AlipayException $e) { // Hash or invalid transaction error

echo $e->getMessage();

return false;

// @todo: Update the transaction in your DB and add funds for the user

/* — — — — — — — — — — — — — -*/

Now Hit the url and access the file transaction.php

Click on Test Transaction link and do payment

For Reference, Alipay api documentation link

Originally published at https://www.devstringx.com on May 1, 2020.

--

--

--

Devstringx Technologies is highly recommended IT company for custom software development, mobile app development and automation testing services

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Hey guys. I have this simple snake python game.

Why you should use CDK

Getting Data from API in Colab

How to Fix PS4 Error SU-41350–3? [Simplest Solutions]

Summer Internship-Online Examination Based Web Application

Automated Airtable follow-up emails can boost your CRM workflows

Configure Docker Compose startup order for Django, REST Framework and Celery/RabbitMQ/Redis…

Get Accurate Data From Your Competitors With An API

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Devstringx Technologies

Devstringx Technologies

Devstringx Technologies is highly recommended IT company for custom software development, mobile app development and automation testing services

More from Medium

PHPUnit Testing Anonymous Functions

How can I create a Mediumblob within the Laravel schema builder?

Create Unit tests for WordPress Plugin

Laravel Security Vulnerabilities Challenge And How to Address Them Using