yii2 Alipay payment tutorial  [ 2.0 edition ]

The personal understanding of Alipay payment process is basically three steps.
1. Front page will pay information data through the immediate payment button ajax Submit to order processing layer
2. Citing Alipay's interface in order processing layer Write payment data to Alipay will throw out one. from Forms action Payment page to Alipay
3. After the user completes the payment, he will call the synchronous callback and asynchronous callback to process the business logic

First step Front end interface

/* Payment button click */
$('body').on('click', '.payBtn', function () {
var money = $('.moneylist .current').attr('data-money');
var author_id = $(this).attr('data-author-id');
var itemid = $(this).attr('data-itemid');
var pay_type = $('.payType .current').attr('data-pay-type');
//pay_type It distinguishes WeChat from Alipay. Ignore it first pay_type ==1 Of
if (pay_type == 1) {
//pay_type It distinguishes WeChat from Alipay. Ignore it first pay_type ==1 Of
} else {
type: "POST",
url: "/alipay/pay",// This is the second step to bring data into the Alipay class library for processing.
data: params,// data
async: false,
success: function success(data) {

The second step Bring the payment data into the Alipay class library.

First put a picture of the database field

* Created by PhpStorm.
* User: jayrui612
* Date: 2017/5/11
* Time: 14:27
*/ namespace frontend\controllers; use frontend\components\payment\alipay\lib\AlipaySubmit;
use frontend\components\payment\alipay\lib\AlipayNotify;
use common\models\SanDbSponsor;
use yii\web\Controller;
use Yii; class AlipayController extends Controller
{ public $enableCsrfValidation = false; public function actionPay()
// Merchant order number , The unique order number in the order system of the merchant website , Required
$out_trade_no = $_POST['WIDout_trade_no']; // Name of the order , Required
$subject = $_POST['WIDsubject']; // The payment amount , Required
$total_fee = $_POST['WIDtotal_amount']; // Commodity Description , Can be empty
$body = $_POST['WIDbody']; // Create payment order
$db = Yii::$app->db;
try {
$sponsorData = $_POST['sponsor_params'];
$sponsorData['pay_type'] = 2; // Method of payment .(1: WeChat ,2: Alipay )
$sponsorData['pay_status'] = 0; // Payment status .(0: Did not pay ,1: Successful payment ,2: Failure to pay )
$sponsorData['price'] = $total_fee;
$sponsorData['out_trade_no'] = $out_trade_no;
$sponsorData['create_time'] = time(); $db->createCommand()->insert('supe_sponsor', $sponsorData)->execute(); } catch(\Exception $e) {
//throw $e;
return $this->redirect(Yii::$app->urlManager->createUrl(["news/detail", 'itemid' => $_POST['sponsor_params']['itemid']]))->send();
} $parameter = array(
"service" => Yii::$app->params['pc_alipay']['service'],
"partner" => Yii::$app->params['pc_alipay']['partner'],
"seller_id" => Yii::$app->params['pc_alipay']['seller_id'],
"payment_type" => Yii::$app->params['pc_alipay']['payment_type'],
"notify_url" => Yii::$app->params['pc_alipay']['notify_url'],
"return_url" => Yii::$app->params['pc_alipay']['return_url'], "anti_phishing_key"=>Yii::$app->params['pc_alipay']['anti_phishing_key'],
"out_trade_no" => $out_trade_no,
"subject" => $subject,
"total_fee" => $total_fee,
"body" => $body,
"_input_charset" => trim(strtolower(Yii::$app->params['pc_alipay']['input_charset']))
); // Build request
$alipaySubmit = new AlipaySubmit(Yii::$app->params['pc_alipay']);
$html_text = $alipaySubmit->buildRequestForm($parameter,"get", " confirm "); echo $html_text; }

The third step User payment Synchronous and asynchronous callbacks

Here's a description Payment page It will be called automatically after payment Synchronous callback actionReturn_sync_ali And asynchronous callbacks actionReturn_async_ali
Synchronous callback is to do page Jump and so on Asynchronous callbacks are the main ones Make logical operation of order status

The following method is the same stay class AlipayController extends Controller below

* Alipay synchronous callback notification
public function actionReturn_sync_ali()
$alipayNotify = new AlipayNotify(Yii::$app->params['pc_alipay']);
$verify_result = $alipayNotify->verifyReturn();
if($verify_result) {// Verify success
// Merchant order number
$out_trade_no = htmlspecialchars($_GET['out_trade_no']); // But the id
$seller_id = htmlspecialchars($_GET['seller_id']); // Alipay transaction number
$trade_no = $_GET['trade_no']; // Transaction status
$trade_status = $_GET['trade_status']; if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
return $this->redirect(Yii::$app->urlManager->createUrl(["news/detail"]))->send(); } else {
echo '<script>window.close();</script>';
else {
echo " Validation failed ";
} /**
* Alipay asynchronous callback address
public function actionReturn_async_ali()
{ $alipayNotify = new AlipayNotify(Yii::$app->params['pc_alipay']); $verify_result = $alipayNotify->verifyNotify(); if($verify_result) {// Verify success // Our order number
$out_trade_no = $_POST['out_trade_no']; // Alipay transaction number
$trade_no = $_POST['trade_no']; // Transaction status
$trade_status = $_POST['trade_status']; // Order amount
$total_amount = $_POST['total_fee']; // Paid in amount
$receipt_amount = $_POST['price']; // Send time of callback notification
$notify_time = $_POST['notify_time']; if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
// Judge whether the order has been processed in the merchant website
// If you haven't dealt with it , According to order No (out_trade_no) Find the details of the order in the order system of the merchant website , And implement the business procedures of the merchant
// Please be sure to judge the total_amount And total_fee For the same
// If you've dealt with it , Do not execute merchant's business procedures
// Be careful :
// Upon completion of payment , Alipay sends the transaction status notification. if ($_POST['seller_id'] == Yii::$app->params['pc_alipay']['seller_id']
&& $receipt_amount != 0 && ($total_amount == $receipt_amount))
$hasRecord = SanDbSponsor::find()
->where(['out_trade_no' => $out_trade_no])
->one(); // update
if ($hasRecord && $hasRecord->pay_status != 1)
$hasRecord->pay_status = 1; // Payment status .(1: Successful payment )
$hasRecord->create_time = strtotime($notify_time);
} }
//—— Please write the program according to your business logic ( The above code is for reference only )—— echo "success"; // Please do not modify or delete } else { // Validation failed
echo "fail"; // Please do not modify or delete }

That's about it There are also configuration files and Alipay class library files not posted.

return [ // PC End Appreciate Alipay configuration
'pc_alipay' => [
// Signing Account No
'partner' => '111111',
// Alipay account receivable , In general, the collection account number is the signing account number
'seller_id' => '111111', // Merchant's private key ,
'private_key' => 'xxxxxxxx',
// Alipay's public key
'alipay_public_key' => 'yyyyyyyyyyyyyy',
// Asynchronous notification page path
'notify_url' => 'http://www.jay.com/alipay/return_async_ali.php', // Page Jump synchronization notification page path
'return_url' => "http://www.jay.com/alipay/return_sync_ali.php", // Signature method
'sign_type' => strtoupper('RSA'), // Character encoding format At present, we support gbk or utf-8
'input_charset' => strtolower('utf-8'), // ca Certificate path address , be used for curl in ssl check
// Please guarantee cacert.pem The file is in the current folder directory
'cacert' => getcwd().'\\cacert.pem', // Access pattern
'transport' => 'http', // Payment type , There is no need to modify
'payment_type' => '1', // The product type , There is no need to modify
'service' => "create_direct_pay_by_user", // The following anti phishing information , If the anti fishing function is not activated , If it is empty, you can
'anti_phishing_key' => '',
'exter_invoke_ip' => ''
], ];

Screenshot of class library file

The article is transferred from others , The article is very clear , For my study only

yii2 Alipay payment tutorial [ 2.0 edition ] More articles about

  1. TinkPHP Framework developed CRMEB Applet mall v4.0 Two development integrated Alipay payment

    Preface We all know that Alipay payment and WeChat payment Alipay can only be limited to their own platform. , WeChat's Alipay payment can't be used at all. , Even official account payments need to jump to external browsers to evoke Alipay payment. , also QQ Browser evoke Alipay payment is still a lot of problems. , the ...

  2. Alipay payment scan code payment ( Payment by computer website )、H5 payment ( Mobile Website Payment ) Analysis and summary of related business processes

    Preface In the last article < Code scanning payment of wechat payment . Official account payment .H5 payment . Analysis and summary of business process related to small program payment > in , This paper analyzes and summarizes the business process of wechat payment related payment types , Here, on an equal footing with WeChat, Alipay pays. ...

  3. ThinkPHP5.0 Realization app Alipay payment function

    I was working on a project the other day , Alipay interface is required. , Do it for the first time , For several days All kinds of pits , Simply write my Alipay payment process. , I hope this is also helpful to children's shoes made for the first time by Alipay. , If you don't understand, you can pay the platform first to see the documents of Alipay payment. , I'm the next one d ...

  4. asp.net core Alipay pay ( The computer 2.0)

    Alipay computer payment measurement can also wake up Alipay mobile phone mobile phone payment. , So it can also be used as Alipay mobile phone. web Method of payment . Alipay computer payment process for the use of Alipay official sdk Construction of Alipay parameters obtained DefaultAopClient example ...

  5. merchants APP How to access new Alipay payment , How to upgrade the old version

    The code address is as follows :http://www.demodashi.com/demo/14006.html Preface Alipay mobile payment 2.0 Version comparison 1.0 The version has been greatly updated , New businesses need to use the latest technology 2.0 edition SDK ...

  6. MySQL5.0 Installation diagram tutorial of version

    MySQL5.0 Version of the installation diagram tutorial is for novices to learn , At present mysql5.0.96 It's the latest stable version . mysql Download address http://www.jb51.net/softs/2193.html The following is M ...

  7. thinkphp5.0 WeChat official account access to Alipay payment

    --- Resume content start --- It's really impossible to make complaints about this demand. , I want to scold the customer , The best thing to do is to access WeChat in the official account of Alipay. , WeChat official account is rejected by Alipay. , Shielding Alipay , So when WeChat official account is connected to Alipay, it is necessary to manually copy links and jump out of WeChat. ...

  8. Thinkphp5.0 Alipay payment extension library class library

    Thinkphp5.0 Alipay payment extension library class library , Including mobile payment . Payment by computer website . Payment inquiry . refund . Refund inquiry . Statement, etc . Thinkphp5.0 Alipay calling method : Payment by computer website Pagepay.php call ...

  9. Yii2 Use Redis - From installation redis To use [ 2.0 edition ]

    Yii2 Use Redis - From installation redis To use [ 2.0 edition ] One . install Redis And simple configuration 1. download Redis Installation package Address :http://redis.io/download , This article chooses ...

Random recommendation

  1. [LeetCode] Search in Rotated Sorted Array II Searching in rotation ordered array (2)

    Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this ...

  2. CSS Accordion special effects realized

    CSS style : // The number of images @imageN:5; // Images hover The total width before @w:800px; // Images hover The width after that @imageL:640px; // Images hover The width before @ima ...

  3. Delete root subdirectories , How to recover subdirectory configuration files

    Hand base , carelessly rm -rf Problem description : Delete /root/ Subdirectory file ( With hidden profile )shell become -bash-4.2#, How to restore the original appearance resolvent : root User access , Configure related files by yourself :mkdir /roo ...

  4. spring_01

    1. frame 1. What is the framework to solve ? 1. Framework is used to solve the problem of code redundancy 2. It is conducive to the collaborative development of the team 3. Framework is used to solve the problem of low coupling and high cohesion 4. Address robustness and security 2.STRUTS2 and hibernate ...

  5. [Effective C++ --010] Let the assignment operator return a reference to *this

    Almost the most classic is this : x = y = z = ; Read as : x = (y = ( z = )); If there is no return value , The above code cannot be compiled . In fact, I can almost understand this one when I see the title , But why is continuous assignment ...

  6. ubuntu Get the hard disk uuid.

    1. use UUID There are many advantages to identifying hard disks , It is the unique code of a hard disk , So when the hard disk socket position changes , although sda Could become sdc, But the code won't change . So in fstab of use /dev/sda1 Such hard disk identification may be confusing ...

  7. be based on ZooKeeper Of Dubbo Simple sample registration centre

    One : equipment zookeeper System environment Ubuntu 14.04.2 LTS x64 IP : download zookeeper-3.4.6.tar.gz To the folder /opt. Open the zipper m ...

  8. MySQL How to execute an associated query

    This article is also published in https://github.com/zhangyachen/zhangyachen.github.io/issues/51 At present mysql The strategy is simple :mysql Performs embedding on any association ...

  9. [poj3349]Snowflake Snow Snowflakes_hash

    Snowflake Snow Snowflakes poj-3349 The main idea of the topic : give n Snowflakes , Every snowflake has 6 Corner , Each corner has a weight . If you can choose one point from each of the two snowflakes , Make it turn clockwise or counterclockwise from that point , The right to get ...

  10. 10 Minutes to understand Android Of Handler Mechanism

    Handler The mechanism is Android Quite classic asynchronous message mechanism in , stay Android The history of development plays a very important role , Whether it's the application layer we face directly or FrameWork layer , There are still quite a lot of scenes . Analysis of source code ...