Alipay Payment Gateway Integration PHP

Back to Blog
Alipay Payment Gateway Integration PHP

Alipay Payment Gateway Integration PHP

Alipay

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.

API Integration

Please follow the below steps to integrate the API. 

Step 1. Log in 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.

sendbox 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 a 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";

}

else

{

$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)

{

$data = [

'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']}).");

}

$request = [

'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;

}

}

else

{

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);

}

else

{

$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);

if ($error)

{

throw new Exception($error);

}

return $response;

}

private function _prepData($data = array())

{

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

$data['sign_type'] = "MD5";

ksort($data);

return http_build_query($data);

}

private function _sign($data = array())

{

ksort($data);

$query = "";

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

{

if ($v == "")

continue;

$query .= "$k=$v&";

}

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

}

}

/*--------------------------------------------------------------------------------*/

Remember these changes:

  • ENVIRONMENT var value should not “development” in the production environment.
  • Change Pid value and signature key (use sandbox credential for the development environment and real credentials for the production environment.

Step 3. Create a new folder Alipay/test

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

/*----------------------------------------------------------------------------------*/

require_once getcwd() . "/../Alipay.php";

$sale_id = uniqid();

$amount = 10.25;

$description = "A pair of shoes";

$uuid = uuid();

// 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 5. 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 6. Create the new file alipay/test/notify.php

<?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.

try {

    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

transaction

Click on the Test Transaction link and do a payment

Test Transaction link

 

For Reference, the Alipay API documentation link’ click here

Alipay api documentation

FAQs

  • Is Alipay a payment gateway?

Alipay has revolutionized the way people pay for goods and services in Asia and beyond. This cutting-edge digital platform now boasts an impressive 1 billion users, making it one of the most popular e-wallet systems on earth! What started out as a simple payment gateway is now much more; Alipay provides consumers with endless possibilities to enjoy safe, convenient transactions without ever leaving their homes.

  • How to integrate a Paytm payment gateway in PHP?

Ready to get your business rolling? Create an account with Paytm Payment Gateway, and select the option that best suits you – whether it be a website or app! During registration, insert the URL of where customers should end up after they’ve completed their payment. Now, all there’s left is for them to make purchases from you!

  • What is a payment gateway in PHP?

Payment Gateway is the cashless connection between credit card holders and financial providers, enabling the safe transfer of data for fast transactions.

  • Is Alipay part of PayPal?

Alipay is the revolutionary e-wallet that has taken China by storm, providing users with a secure and convenient way to make mobile payments. As an equivalent of PayPal, Alipay offers all the same features for a superior digital payment experience.

  • What payment methods does Alipay accept?

Alipay offers a range of secure payment options, from the convenience of using an eWallet to traditional methods such as credit cards and bank transfers. With Alipay, you can shop online with ease – no matter your preferred payment method!

  • How do I integrate a payment gateway?

Integrating a payment gateway into your website is an easy process that requires no coding knowledge. First, select the payment gateway of your choice and obtain the necessary API credentials – this will be provided by the provider itself. Once you have these details, insert them into your checkout page so customers can start making payments through your website!


I hope that after reading this blog you can easily do the Alipay payment gateway integration. Our developers have written a lot of other development-related blogs So feel free to check & if you have any questions or want to know more about our services so please contact us!

Share this post

Back to Blog