PHP code --ThinkPHP5.1 using Alipay computer website payment

1, Description

1. Overall process

No payment has been made before, so it is still a bit confusing for payment. This time, it is mainly a record of the completion of Alipay computer website payment. Explain (Alipay payment, WeChat payment in fact there are many types, such as Alipay, face to face pay, APP payment, mobile phone website payment, WeChat JSAPI payment, payment code payment, Native payment, H5 payment, we choose the corresponding official website development document according to the company's business needs, and then introduce it. This development uses the thinkPHP5.1 version.

2. Steps involved

Alipay payment process description

The use of Alipay's official damo

Alipay's callback notify_url asynchronous notification writing

The process of introducing Alipay damo under the integrated thinkPHP framework.

Two, payment business and Alipay process description

1, first of all, our business needs and Alipay processes are as follows:

2. In practice, most of the page scenarios are as follows:

 

III. Development preparation steps:

1, check Alipay's "Alipay payment open platform" address. https://open.alipay.com/developmentDocument.htm

 

2. There is a very detailed introduction in the document. We don't make any specific description here. We need to understand the interface description in the actual development. Here we click to download the official PHP Demo

 

3. After downloading, it should be a compressed package, alipay.trade.page.pay-PHP-UTF-8.zip. We unzip it and rename it to alipayPc.

 

4. After the above preparations are completed, we will enter into the actual development steps next.

IV. actual development process, using demo in the framework

1. Steps involved

: copy the extracted folder alipayPc to the framework

: separate the official payment, callback and business code to separate a custom AliPayPc() class

: configure config.php payment related parameters,

In the controller, call AliPayPc() class to pay.

: add callback file, write callback code

2. After decompressing, we can see that the demo file is as follows. I will not explain the details of the file. I will only talk about the files that need to be referenced this time. For details, I can see the official website manual.

 

 

3. The above return ﹐ url.php is an official callback file, mainly for verification

$arr=$_POST;
$alipaySevice = new AlipayTradeService($config); 
$alipaySevice->writeLog(var_export($_POST,true));
$result = $alipaySevice->check($arr);//Signature verification method

 

4. Then there is the official reference code for payment, transaction query, closing transaction, refund and refund query in the pagepay folder. We will write our own AliPayPc() class later, basically by reference.

 

 

5. As explained here, the extracted files are placed in the extend directory of thinkPHP. Some people may be used to put them in the vendor directory. As mentioned on the thinkPHP official website, vendor is used as the directory of extension files installed using composer, and extend is a third-party file directory introduced manually. Therefore, it is better for us to develop according to the specifications.

6. Next, we did not create a new lib folder in the Lib directory under extend. We created the user-defined payment class AliPayPc.php file just mentioned.

 

 

 

7. The code is as follows. Here we separate the official payment code just mentioned

 <?php
/**
 * Created by PhpStorm.
 * User: WuYan
 * Date: 2020/4/28
 * Time: 20:00
 * Alipay computer website payment
 */
namespace lib;
class AliPayPc
{
    /**
     * Alipay collection
     */
    public static function setAilPay()
    {
        
    }
}

 

8. Directly copy and modify the pagepay.php file in the pagepay directory, mainly to modify the file import path and parameter import mode

<?php

/**
 * Created by PhpStorm.
 * User: WuYan
 * Date: 2020/4/28
 * Time: 20:00
 * Alipay computer website payment
 */

namespace lib;

class AliPayPc
{
    /**
     * Alipay collection
     * @param [type] $out_trade_no Merchant order number
     * @param [type] $subject Order name
     * @param [type] $total_amount Payment amount
     * @param [type] $body Product description, can be blank
     * @param [type] $config_data Payment parameter, array type; if it is blank, the default parameter will be taken
     * @return void
     */
    public static function setAilPay($out_trade_no,$subject,$total_amount,$body,$config_data = [])
    {
        require_once env('extend_path').'/alipayPc/config.php';//Introduce the path to refer to your own actual storage path
        require_once env('extend_path').'/alipayPc/pagepay/service/AlipayTradeService.php';
        require_once env('extend_path').'/alipayPc/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';

        //Construction parameters
        $payRequestBuilder = new \AlipayTradePagePayContentBuilder();//Class name preceded by \ To call an external class, you need to prefix the class name with \ 
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);

        $aop = new \AlipayTradeService($config);

        /**
         * pagePay Payment request of computer website
         * @param $builder Business parameters, generated using the object in buildmodel.
         * @param $return_url Synchronous jump address, accessible by the public network
         * @param $notify_url Asynchronous notification address, accessible by the public network
         * @return $response Information returned by Alipay
         */
        $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);
    
        //Output form
        var_dump($response);
    }
}

 

9. As above, we have created the payment class. Now we configure the config.ph file.

 

 

10, the main configuration here is to use id, business private key, Alipay public key, Alipay gateway (pay attention to official account or sandbox test account).

Added, how to open payment and how to apply for sandbox account in Alipay. There is no explanation, no explanation, next generation, and then generate the key.

 

 

11. After writing the payment class AliPayPc() and configuring config.php, we start to call it in the controller.

<?php
namespace app\admin\controller;

use lib\AliPayPc;//Import payment class

class User extends Base
{


    public function MtAliPay(Request $request)
    {
        $out_trade_no = "19982019121202021000";//order number
        $subject = "Test item 000";//Commodity name
        $total_amount = 0.1;//Commodity amount yuan
        $body = "This is for testing";//Product description
        $config_data = [
            'return_url'=>$request->domain().'/index.php/admin/user/return_url',//Sync jump to write
            'notify_url'=>$request->domain().'/index.php/admin/callback/notify_url',//Asynchronous jump to write
        ];
     //-------------
      Write business code, such as generate order record
     //-------------
//Because it is declared as a static class, it is called directly AliPayPc::setAilPay($out_trade_no,$subject,$total_amount,$body,$config_data = []); } }

 

12. Click your domain name /index.php/admin/user/userAliPay Found that if there is no problem, it can be directly transferred to the Alipay payment page, if you can directly scan the code payment, you can log on to your account to pay, if the payment is successful, the page will jump to your written synchronization address index.php/admin/login/return_url.

 

 

13, of course, after the successful payment, there is another most important asynchronous callback. The following is the official statement of Alipay: https://opendocs.alipay.com/open/270/105902

: the program must print out "success" (without quotes) after execution. If the merchant's feedback to Alipay's characters is not success's 7 characters, the Alipay server will continue to reissue the notification until more than 24 hours and 22 minutes.
Generally, 8 notices shall be completed within 25 hours (the interval frequency of notices is generally: 4m,10m,10m,1h,2h,6h,15h);

: after the program is executed, the page cannot jump.
If the page is skipping, Alipay will not receive the success character. It will be judged by the Alipay server to run an exception for the page program and reissue the result notification.

 

14, the callback means that, by setting up the notify_url callback address, Alipay will bring your participation (such as business parameter class: transaction number, transaction amount, public parameter: authorized appid, signature) to request your address after the payment is successful, to tell you that the Alipay has received the money, how, and how, and then there may be a Malicious request of three parties (forged request). So you validate these, then identify the callbacks of Alipay, and then do business processes. For example, modify the order payment status.

15. Finally, we write a callback. Of course, we write a callback class first. Add setNotify_url() / / in the previous AliPayPc() class to verify the signature

<?php

/**
 * Created by PhpStorm.
 * User: WuYan
 * Date: 2020/4/20
 * Time: 10:59
 * Alipay
 */

namespace lib;

class AliPay
{
    /**
     * Alipay collection
     *
     * @param [type] $out_trade_no Merchant order number
     * @param [type] $subject Order name
     * @param [type] $total_amount Payment amount
     * @param [type] $body Product description, can be blank
     * @param [type] $config_data Payment parameter, array type; if it is blank, the default parameter will be taken
     *
     * @return void
     */
    public static function setAilPay($out_trade_no,$subject,$total_amount,$body,$config_data = [])
    {
        require_once env('extend_path') . '/alipayPc/config.php';
        require_once env('extend_path'). '/alipayPc/pagepay/service/AlipayTradeService.php';
        require_once env('extend_path') .'/alipayPc/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
        $config = array_merge($config, $config_data);
        //Construction parameters
        $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
        if(!empty($body)){
            $payRequestBuilder->setBody($body);
        }
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $aop = new \AlipayTradeService($config);
        /**
         * pagePay Payment request of computer website
         * @param $builder Business parameters, generated using the object in buildmodel.
         * @param $return_url Synchronous jump address, accessible by the public network
         * @param $notify_url Asynchronous notification address, accessible by the public network
         * @return $response Information returned by Alipay
         */
        $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);
        //Output form
        // var_dump($response);
    }

    /**
     * Alipay server asynchronous notification page
     *
     * @param [type] $arr Payment success return message post
     *
     * @return void
     */
    public static function setNotify_url($arr)
    {
        require_once env('extend_path') . '/alipayPc/config.php';
        require_once env('extend_path'). '/alipayPc/pagepay/service/AlipayTradeService.php';

        $alipaySevice = new \AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($arr,true));
        $result = $alipaySevice->check($arr);//Conduct signature verification
        if($result) {//Verification successful
            //Transaction status
            if($arr['trade_status'] == 'TRADE_FINISHED' || $arr['trade_status'] == 'TRADE_SUCCESS') {
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }
}

16. Then add a callback method in the controller

<?php
/**
 * Third party request, no validation required
 */
namespace app\api\controller;

use think\Controller;
use lib\AliPayPc;

class callback extends Controller
{
    /**
     * Alipay merchants receive asynchronous callbacks
     */
    public function notify_url()
    {
        $arr = $_POST;
        $result = AliPayPc::setNotify_url($arr);//Conduct signature verification
        //After successful signature verification
        //Determine whether the order number exists in the database
        //Conduct business processing----------------------
    }
}

 

5, Conclusion

1, Alipay computer web payment, as a whole, because Alipay official documents and their integration is relatively easy, mainly in practice, for payment logs, callback logs, prevent duplication of submission, prevent forgery requests, and repeat callbacks of these code business side to write reasonably.

2. If you still have questions, you can leave a message or consult with QR code in the upper left corner of the page.

Tags: PHP network PhpStorm Mobile

Posted on Tue, 28 Apr 2020 00:10:52 -0700 by savio_mf