Home  >  Article  >  Backend Development  >  ThinkPHP implements Alipay interface function example, thinkphp example_PHP tutorial

ThinkPHP implements Alipay interface function example, thinkphp example_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:12:42818browse

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