thinkphp realization of Alipay interface function instance _php instance

Source: Internet
Author: User
Tags documentation ord

This article illustrates the Thinkphp method to realize the function of Alipay interface. Share to everyone for your reference. The specific analysis is as follows:

Recently do the system, the need to realize online payment function, without hesitation, the choice is Alipay's interface payment function, here I use the instant to the account interface, the implementation of the following steps:

First, download Alipay interface package

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

Specific how to download, I will not be wordy ~ ~

second, reorganize the interface package file , this step should be considered more critical (personally think), download the interface package file has a lot of language source code

We select the interface file Create_direct_pay_by_user-php-utf-8 this name, which includes the following files:

Images file is Alipay related to some of the logo pictures, we temporarily ignore him, lib file is very important, is the entire interface of the core class files;

Alipay.config.php is a configuration file for related parameters

alipayapi.php is Alipay interface entry file

Notify_url.php is the server asynchronous notification paging file;

return_url.php is a page jump synchronization notification file;

In the thinkphp frame file, find extend enter, and then into the vendor, vendor folder, the new folder Alipay, the Alipay as a Third-party class library introduced, and then, copy Alipay interface package in the Lib file in the file, a total of 4 files, the following :

Now rename the files above.

alipay_core.function.php renamed as: corefunction.php;

alipay_md5.function.php renamed as: md5function.php;

alipay_notify.class.php renamed as: notify.php;

alipay_submit.class.php renamed as: submit.php;

Then, open the submit.php file, remove the following code;

Require_once ("alipay_core.function.php");

Require_once ("alipay_md5.function.php"); Similarly, open notify.php file, remove the following two paragraphs of code require_once ("alipay_core.function.php");

Require_once ("alipay_md5.function.php") why remove these two pieces of code from the above two files, because when calling interface files in a project, I introduce all 4 core files through vendor. So, this no longer requires import.

To this end, Alipay interface package related core Class library collation is basically completed. Now start calling in the project;

Iii. Call the Alipay interface in the project

The call is divided into two steps:

1, in the configuration file in the conf/config.php file in the allocation of the relevant parameters of Alipay

Copy Code code as follows:
Alipay Configuration Parameters





' Alipay_config ' =>array (


' Partner ' => ' 20********50 ',//Here is the PID you get after you successfully apply for the Alipay interface;


' Key ' => ' 9t***********ie ',//Here is the key you acquired after you successfully applied 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 (


Here is the seller's Alipay account number, which is the Alipay account you registered when you applied for the interface.


' Seller_email ' => ' pay@xxx.com ',





Here is the asynchronous notification page URL, submitted to the project by the Pay controller Notifyurl method;


' Notify_url ' => ' Http://www.xxx.com/Pay/notifyurl ',





Here is the page jump notification URL, submitted to the project's pay controller ReturnUrl method;


' Return_url ' => ' Http://www.xxx.com/Pay/returnurl ',





Payment successfully jump to the page where I jump to the project's user controller, Myorder method, and payed (paid list)


' Successpage ' => ' user/myorder?ordtype=payed ',





Payment failed to jump to the page where I jump to the project's user controller, Myorder method, and Unpay (unpaid list)


' ErrorPage ' => ' User/myorder?ordtype=unpay ',


),



2, a new payaction controller code as follows


Copy Code code as follows:
<?php


Class Payaction extends action{


In the class initialization method, the related class library is introduced


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 Sync notification page path


$seller _email = C (' alipay.seller_email ');/seller Alipay account required


$out _trade_no = $_post[' trade_no '];//merchant order number is passed through the form of the payment page, pay attention to the only one!


$subject = $_post[' Ordsubject ']; The order name//must be filled out by the form of the payment page


$total _fee = $_post[' Ordtotal_fee ']; Payment//required to be passed through the form of the payment page


$body = $_post[' ordbody ']; The order description is passed through the Payment page's form


$show _url = $_post[' Ordshow_url ']; The product presentation address is passed through the form of the payment page


$anti _phishing_key = "";//anti-phishing timestamp//To use please call the Query_timestamp function in the class file submit


$exter _invoke_ip = Get_client_ip (); IP address of the client





Constructs the array of parameters to request without changing


$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,


"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 a 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 is also the C function to read the configuration items, assigned to $alipay_config


$alipay _config=c (' alipay_config ');





Calculate the results of the notification validation


$alipayNotify = new Alipaynotify ($alipay _config);


$verify _result = $alipayNotify->verifynotify ();





if ($verify _result) {


Validation successful


Get the notification return parameter for Alipay, refer to the list of server asynchronous notification parameters in technical documentation


$out _trade_no = $_post[' out_trade_no ']; Merchant Order Number


$trade _no = $_post[' trade_no ']; Alipay Trading Number


$trade _status = $_post[' trade_status ']; Trading status


$total _fee = $_post[' Total_fee ']; Transaction amount


$notify _id = $_post[' notify_id ']; Notifies the checksum ID.


$notify _time = $_post[' notify_time ']; The time the notification was sent. The format is Yyyy-mm-dd HH:mm:ss.


$buyer _email = $_post[' Buyer_email ']; Buyer pay Treasure Account number;


$parameter = Array (


"Out_trade_no" => $out _trade_no,//merchant order number;


"Trade_no" => $trade _no,//Alipay trading number;


"Total_fee" => $total _fee,//Transaction amount;


"Trade_status" => $trade _status,//transaction status


"notify_id" => $notify _id,//notification checksum ID.


"Notify_time" => $notify _time,//notification time of delivery.


"Buyer_email" => $buyer _email,//buyer Alipay account;


);


if ($_post[' trade_status '] = = ' trade_finished ') {


//


}else if ($_post[' trade_status '] = = ' trade_success ') {if (!checkorderstatus ($out _trade_no)) {


Orderhandle ($parameter);


Carry out order processing, and transmit the parameters returned from Alipay;


}


}


echo "Success"; Please do not modify or delete


}else {


Validation failed


echo "fail";


}


}





function ReturnUrl () {


The head treatment is the same as the above two methods, here is not wordy!


$alipay _config=c (' alipay_config ');


$alipayNotify = new Alipaynotify ($alipay _config)//calculation to notify validation results


$verify _result = $alipayNotify->verifyreturn ();


if ($verify _result) {


Validation successful


Get the notification return parameter of Alipay, refer to the page Jump synchronization notification parameter list in technical documentation


$out _trade_no = $_get[' out_trade_no ']; Merchant Order Number


$trade _no = $_get[' trade_no ']; Alipay Trading Number


$trade _status = $_get[' trade_status ']; Trading status


$total _fee = $_get[' Total_fee ']; Transaction amount


$notify _id = $_get[' notify_id ']; Notifies the checksum ID.


$notify _time = $_get[' notify_time ']; The time the notification was sent.


$buyer _email = $_get[' Buyer_email ']; Buyer pay Treasure Account number;





$parameter = Array (


"Out_trade_no" => $out _trade_no,//merchant order number;


"Trade_no" => $trade _no,//Alipay trading number;


"Total_fee" => $total _fee,//Transaction amount;


"Trade_status" => $trade _status,//transaction status


"notify_id" => $notify _id,//notification checksum ID.


"Notify_time" => $notify _time,//notification time of delivery.


"Buyer_email" => $buyer _email,//Buyer Alipay Account


);





if ($_get[' trade_status '] = = ' trade_finished ' | | $_get[' trade_status '] = = ' trade_success ') {


if (!checkorderstatus ($out _trade_no)) {


Orderhandle ($parameter); Carry out order processing, 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 {


Validation failed


To debug, see the Verifyreturn function of the alipay_notify.php page


echo "Failed to pay!" ";


}


}


}


?>



3, there are several payment processing needs to use the function, I wrote these functions in the project common/common.php, so no manual call, you can directly use these functions, the code is as follows:


Copy Code code as follows:
OrderList data Sheet, used to save the user's purchase order record;





Online transaction order payment processing function


Function: Based on the data returned by the payment interface to determine whether the order has been paid successfully;


Return value: Returns True if the order has been successfully paid, otherwise returns false;


function Checkorderstatus ($ordid) {


$Ord =m (' orderlist ');


$ordstatus = $Ord->where (' ordid= '. $ordid)->getfield (' Ordstatus ');


if ($ordstatus ==1) {


return true;


}else{


return false;


}


}





Processing order functions


Update order status, write the data returned after the order is paid


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);


}





Obtain 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;


}


}



Iv. Summary of the points

1, the interface package in the Lib file in the file copied to the vendor, renamed the TP specification naming rules, in order to invoke convenience, of course, you want to change to other names can also;

2, the implementation of payment operations (Doalipay), processing asynchronous return results (Notifyurl), processing jump return results (ReturnUrl) Three payment interface of the core page written to a payaction controller.

3, submitted to pay the page, you can submit before the submission of some parameters to pass the content first through the hidden domain method combination, such as the amount of the first calculation, order name, order description, such as the first combination of strings. The form is then submitted so that, as long as the pass parameter is constructed directly in the Doalipay method, the direct commit is done.

4, payment after the return of processing because to be in the asynchronous and jump two methods should be the corresponding judgment and processing, so that these judgments and processing into a custom function, so long as the call function can make the code more clear.

The return URL for the 5, Notify_url and return_url two modes must use an absolute path such as http://xxxxxxx, because it is returned from the Alipay platform to your project page and cannot use a relative path.

The above code in the ThinkPHP3.0 normal use!!

More interested in thinkphp related content readers can view the site topics: "thinkphp Introductory Course" and "thinkphp Common methods Summary"

I hope this article will be helpful to everyone's thinkphp framework program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.