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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.