search
HomeBackend DevelopmentPHP TutorialThinkPHP implements Alipay interface function example, thinkphp example_PHP tutorial

ThinkPHP implements Alipay interface function example, thinkphp example

The example in this article describes how ThinkPHP implements the Alipay interface function. Share it with everyone for your reference. The specific analysis is as follows:

When I was working on a system recently, I needed to implement the online payment function. Without any hesitation, I chose Alipay’s interface payment function. Here I used the instant payment interface. The specific implementation steps are as follows:

1. Download the Alipay interface package

Download address: https://b.alipay.com/order/productDetail.htm?productId=2012111200373124&tabId=4#ps-tabinfo-hash

I won’t go into details on how to download it~~

2. Reorganize the interface package file . This step should be considered critical (in my opinion). The downloaded interface package file has source code in many languages ​​

We choose the interface file named create_direct_pay_by_user-PHP-UTF-8, which includes the following files:

The images file contains pictures of some logos related to Alipay. We will ignore them for now. The lib file is very important and is the core class file of the entire interface;

alipay.config.php is the configuration file of related parameters

alipayapi.php is the Alipay interface entry file

notify_url.php is the server asynchronous notification page file;

return_url.php is the page jump synchronization notification file;

Under the ThinkPHP framework file, find Extend and enter, then enter Vendor. Under the Vendor folder, create a new folder Alipay, introduce Alipay as a third-party class library, and then copy the lib file in the Alipay interface file package. All files, a total of 4 files, are as follows:

Now rename the above files.

alipay_core.function.php is renamed to: Corefunction.php;

alipay_md5.function.php is renamed to: Md5function.php;

alipay_notify.class.php is renamed to: Notify.php;

alipay_submit.class.php is renamed to: Submit.php;

Then, open the Submit.php file and remove the following code;

require_once("alipay_core.function.php");

require_once("alipay_md5.function.php");Similarly, open the Notify.php file and remove the following two pieces of code require_once("alipay_core.function.php");

require_once("alipay_md5.function.php"); Why should I remove these two pieces of code in the above two files? Because when calling the interface file in the project, I pass all four core files through the vendor. Introduction. So, this no longer requires an import.

At this point, the organization of the core class libraries related to the Alipay interface package is basically completed. Now start calling in the project;

3. Call the Alipay interface in the project

The call is divided into two steps:

1. Configure Alipay-related parameters in the Conf/Config.php file in the configuration file

Copy code The code is as follows:
//Alipay configuration parameters

'alipay_config'=>array(
'partner' =>'20********50', //Here is the PID you obtained after successfully applying for the Alipay interface;
'key'=>'9t****************ie',//Here is the Key you obtained after successfully applying for the Alipay interface
'sign_type'=>strtoupper('MD5'),
'input_charset'=> strtolower('utf-8'),
'cacert'=> getcwd().'\cacert.pem',
'transport'=> 'http',
),
//The above configuration items are copied from the alipay.config.php file in the interface package and configured;
       
'alipay' =>array(
//This is the seller’s Alipay account, which is the Alipay account you registered when applying for the interface
'seller_email'=>'pay@xxx.com',

//Here is the asynchronous notification page URL, submitted to the notifyurl method of the project's Pay controller;
'notify_url'=>'http://www.xxx.com/Pay/notifyurl',

//Here is the page jump notification url, submitted to the returnurl method of the project's Pay controller;
'return_url'=>'http://www.xxx.com/Pay/returnurl',

//The page that jumps to after successful payment. I jump to the project's User controller, myorder method, and pass the parameter paid (paid list)
'successpage'=>'User/myorder?ordtype=payed', 

//The page that jumps to when payment fails. I jump here to the project's User controller, myorder method, and pass the parameter unpay (unpaid list)
'errorpage'=>'User/myorder?ordtype=unpay',
),

2. Create a new PayAction controller code as follows
Copy code The code is as follows:
class PayAction extends Action{
//In the class initialization method, introduce the relevant class library Public function _initialize() {
vendor('Alipay.Corefunction');
vendor('Alipay.Md5function');
vendor('Alipay.Notify');
Vendor('Alipay.Submit');
}  
       
//doalipay method
                                                                            Public function doalipay(){
                                                                      // require_once("alipay.config.php");
// require_once("lib/alipay_submit.class.php");
                                   
//Here we read the configuration item parameters through the C function of TP and assign them to $alipay_config;
         $alipay_config=C('alipay_config');                                     
                                                                           
$payment_type = "1"; //Payment type //Required, cannot be modified
          $notify_url = C('alipay.notify_url'); // Server asynchronous notification page path
$return_url = C('alipay.return_url'); //Page jump synchronization notification page path
         $seller_email = C('alipay.seller_email');//Seller’s Alipay account is required
           $out_trade_no = $_POST['trade_no']; // Merchant order number is passed through the form on the payment page, be sure to be unique!
$subject = $_POST['ordsubject']; //Order name //Required Pass through the form on the payment page
          $total_fee = $_POST['ordtotal_fee']; //Payment amount //Required Pass through the form on the payment page
$body = $_POST['ordbody']; //Order description is passed through the form on the payment page
$show_url = $_POST['ordshow_url']; //The product display address is passed through the form on the payment page
$anti_phishing_key = "";//Anti-phishing timestamp //If you want to use it, please call the query_timestamp function in the class file submit
           $exter_invoke_ip = get_client_ip(); //Client’s IP address
       
//Construct the parameter array to be requested, no changes are needed
$parameter = array(
"service" => "create_direct_pay_by_user",
"partner" => trim($alipay_config['partner']),
"payment_type" => $payment_type,
"notify_url" => $notify_url,
"return_url" => $return_url,
"seller_email" => $seller_email,
"out_trade_no" => $out_trade_no,
"subject" => $subject,
"total_fee" => $total_fee,
"body" "body" => $body,
"show_url" => $show_url,
"anti_phishing_key" => $anti_phishing_key,
"exter_invoke_ip" => $exter_invoke_ip,
"_input_charset" => trim(strtolower($alipay_config['input_charset']))
);
//Create request
$alipaySubmit = new AlipaySubmit($alipay_config);
          $html_text = $alipaySubmit->buildRequestForm($parameter,"post", "Confirm");
echo $html_text;
}  
                                                                            Function notifyurl(){
                                                                                                   //require_once("alipay.config.php");
                        //require_once("lib/alipay_notify.class.php");
                                                                              //Here we still use the C function to read the configuration items and assign them to $alipay_config
         $alipay_config=C('alipay_config');

//Calculate the notification verification result
         $alipayNotify = new AlipayNotify($alipay_config);
          $verify_result = $alipayNotify->verifyNotify();

If($verify_result) {
//Verification successful
//Get Alipay’s notification return parameters, please refer to the server asynchronous notification parameter list in the technical documentation
$ OUT_TRADE_NO = $ _post ['Out_trade_no']; //               $trade_no                                    = $_POST['trade_no']; $ Trade_status = $ _post ['trade_status']; // trading status
             $total_fee                                                                                                             = $_POST['total_fee']; $ Notify_id = $ _post ['notify_id']; // Notify the verification ID.
$ Notify_time = $ _post ['notify_time']; // The sending time of notification. The format is yyyy-MM-dd HH:mm:ss.
             $buyer_email                                                                                                                                                                                        $_POST $parameter = array(
"out_trade_no" => $out_trade_no, //Merchant order number;
"trade_no" => $trade_no, //Alipay transaction number;
"total_fee" => $total_fee, //Transaction amount;
"trade_status" => $trade_status, //Trading status
"notify_id" => $notify_id, //Notification verification ID.
"notify_time" => $notify_time, //Notification sending time.
"buyer_email" => $buyer_email, //Buyer's Alipay account;
);
If($_POST['trade_status'] == 'TRADE_FINISHED') {
                                                                                                                                                                                                                                                                                                                                  Orderhandle($parameter);
//Proceed with order processing and send parameters returned from Alipay;
                                                                                                                                                                                                                                                              Echo "Success"; // Please do not modify or delete
                                                                               //Verification failed
echo "fail";
                                                                   }  
       
Function returnurl(){
// The handling of the head is the same as the above two methods.
         $alipay_config=C('alipay_config');
          $alipayNotify = new AlipayNotify($alipay_config);//Calculate the notification verification result
          $verify_result = $alipayNotify->verifyReturn();
If($verify_result) {
//Verification successful
//Get Alipay’s notification return parameters, please refer to the page jump synchronization notification parameter list in the technical documentation
                $out_trade_no   =  $_GET['out_trade_no'];                                                                                                                                                                                                                                                                   $trade_no = $_GET['trade_no']; //Alipay transaction number
                            $trade_status         =                                                                                           $total_fee = $_GET['total_fee']; //Transaction amount
          $notify_id                                                                                                   = $_GET['notify_id']
$ Notify_time = $ _get ['notify_time']; // The sending time of notification.
$buyer_email = $_GET['buyer_email']; //Buyer’s Alipay account;
                                                                                      $parameter = array(                             "out_trade_no" => $out_trade_no, //Merchant order number;
"trade_no" => $trade_no, //Alipay transaction number;
"total_fee" => $total_fee, //Transaction amount;
"trade_status" => $trade_status, //Trading status
"notify_id" => $notify_id, "notify verification ID."
"notify_time" => $notify_time, //Notification sending time.
"buyer_email" => $buyer_email, //Buyer's Alipay account
);
                                                                            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
If(!checkorderstatus($out_trade_no)){
                orderhandle($parameter); //Process the order and transmit the parameters returned from Alipay;
}  
            $this->redirect(C('alipay.successpage'));//Jump to the payment success page configured in the configuration item;
}else {
echo "trade_status=".$_GET['trade_status'];
​​​​ $this->redirect(C('alipay.errorpage'));//Jump to the payment failure page configured in the configuration item;
}  
}else {
//Verification failed
//If you want to debug, please see the verifyReturn function on the alipay_notify.php page
echo "Payment failed!";
}  
}
}
?>
3. Here are several functions that need to be used in the payment processing process. I wrote these functions into the project's Common/common.php, so that you can use these functions directly without calling them manually. The code is as follows:

Copy code The code is as follows:
//Orderlist data table, used to save user purchase order records;

//Online transaction order payment processing function
//Function: Determine whether the order has been paid successfully based on the data returned by the payment interface;
//Return value: If the order has been paid successfully, return true, otherwise return false;
function checkorderstatus($ordid){
$Ord=M('Orderlist');
$ordstatus=$Ord->where('ordid='.$ordid)->getField('ordstatus');
If($ordstatus==1){
         return true;                                }else{
         return false;                                              }  
}

//Processing order function
//Update order status and write the data returned after order payment
function orderhandle($parameter){
$ordid=$parameter['out_trade_no'];
$data['payment_trade_no'] =$parameter['trade_no'];
$data['payment_trade_status'] =$parameter['trade_status'];
$data['payment_notify_id'] =$parameter['notify_id'];
$data['payment_notify_time'] =$parameter['notify_time'];
$data['payment_buyer_email'] =$parameter['buyer_email'];
$data['ordstatus'] =1;
$Ord=M('Orderlist');
$Ord->where('ordid='.$ordid)->save($data);
}

//Get a random and unique order number;
function getordcode(){
$Ord=M('Orderlist');
$numbers = range (10,99);
Shuffle ($numbers);
$code=array_slice($numbers,0,4);
$ordcode=$code[0].$code[1].$code[2].$code[3];
$oldcode=$Ord->where("ordcode='".$ordcode."'")->getField('ordcode');
If($oldcode){
         getordcode();
}else{
           return $ordcode;                                  }  
}

4. Summary

1. After copying the files in the lib file in the interface package to Vendor, rename them to the naming rules of TP specification for the convenience of calling. Of course, you can change it to other names;

2. Write the core pages of the three payment interfaces of executing payment operations (doalipay), processing asynchronous return results (notifyurl), and processing jump return results (returnurl) into a PayAction controller.

3. In the page for submitting payment, you can combine the contents of some parameters to be passed through the hidden field method before submitting. For example, the amount is calculated first, the order name, order description, etc. are first combined with strings. . Then submit the form. In this way, in the doalipay method, you only need to directly construct and pass parameters and submit directly.

4. The processing after payment returns requires corresponding judgment and processing in both asynchronous and jump methods. Therefore, these judgments and processing are written into a custom function, so that as long as the function is called Yes, it makes the code clearer.

5. The return URLs in notify_url and return_url modes must use absolute paths such as http://xxxxxxx, because they are returned to your project page from the Alipay platform and relative paths cannot be used.

The above code can be used normally in ThinkPHP3.0! !

I hope this article will be helpful to everyone’s ThinkPHP framework programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/920605.htmlTechArticleThinkPHP implements the Alipay interface function example, thinkphp example This article describes the method of ThinkPHP implementing the Alipay interface function. Share it with everyone for your reference. The specific analysis is as follows:...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.