Alipay payment function implemented in PHP: Combined with the example form analysis, PHP uses the Alipay interface to implement the payment function. First, the interface code is organized to ensure the stability of the operation; then, the signature verification in the callback processing achieves the function by verifying the parameters. accomplish.
Problem details:
This article describes the payment function of Alipay implemented in PHP.
Share it with everyone for your reference, the details are as follows:
When making the Alipay payment interface for the app, the collected content is organized as follows:
Interface:
import('alipay.AopClient', EXTEND_PATH); import('alipay.request.AlipayTradeAppPayRequest', EXTEND_PATH); $aop = new \AopClient(); $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do"; $aop->appId = Config::get('alipay.app_id'); $aop->rsaPrivateKey = Config::get('alipay.rsa_private_key'); $aop->format = "json"; $aop->charset = "UTF-8"; $aop->signType = "RSA2"; $aop->alipayrsaPublicKey = Config::get('alipay.alipay_rsa_public_key'); //Config::get('alipay.rsa_public_key'); // $request = new \AlipayTradeAppPayRequest(); $bizcontent = json_encode([ 'body' => '红包支付', 'subject' => '用户红包支付', 'out_trade_no' => $orderSn, 'timeout_express' => '30m', 'total_amount' => $amount, 'product_code' => 'QUICK_MSECURITY_PAY' ]); $request->setNotifyUrl("https://" . $_SERVER['HTTP_HOST'] . "/api/callback/alipay"); $request->setBizContent($bizcontent);//这里和普通的接口调用不同,使用的是sdkExecute $response = $aop->sdkExecute($request); $return['aliresponse'] = $response;//htmlspecialchars($response);//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 $this->returnSuccess($return);
Callback processing:
public function alipay() { import('alipay.AopClient', EXTEND_PATH); $aop = new \AopClient(); $aop->alipayrsaPublicKey = Config::get('alipay.alipay_rsa_public_key');// file_get_contents($_SERVER['DOCUMENT_ROOT']."/key/alipay/alipay_public_key.txt"); $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2"); if ($flag){ //验签通过后核实如下参数trade_status、out_trade_no、total_amount、seller_id if (isset($_POST['trade_status']) && ($_POST['trade_status'] == 'TRADE_SUCCESS' || $_POST['trade_status'] == 'TRADE_FINISHED') ) { // 业务处理 } else { $msg = var_export($_POST, true); $fileName = mt_rand(10,1000) .'00alisuccessAnother.log' ; file_put_contents($fileName, $msg); } echo "success"; } else { $msg = var_export($_POST, true); $fileName = mt_rand(10,1000) .'00alicheckSignFail.log'; file_put_contents($fileName, $msg); } }
More learning recommendations: Alipay instant payment online payment practice Project development video tutorial
Attachment: The asynchronous callbacks of Alipay payment and WeChat payment have been called
I have recently been developing Alipay payment, and the preliminary work has been completed It's done, but when the asynchronous callback is taking the value, the asynchronous callback keeps calling, causing my data to be repeatedly stored in the database. After thinking about it carefully, a solution that immediately comes to mind is to add another value in the asynchronous callback. Write an interface. After each callback to get the data, query the database to see if there is data. If there is data, it will not be saved again. But if you think about it carefully, it is wrong. This is treating the symptoms rather than the root cause. No, since there is a problem, There must be a root cause and a correct solution. So, to find the basis, check the documentation:
1. Alipay documentation, here is the documentation for Alipay asynchronous callback:
Server asynchronous notification page Features
Must ensure that there are no characters on the server asynchronous notification page (notify_url), such as spaces, HTML tags, exception prompts thrown by the development system, etc.;
Alipay uses POST to send notification information , so the methods for obtaining parameters on this page, such as: request.Form("out_trade_no"), $_POST['out_trade_no'];
This method will be enabled only when Alipay actively initiates a notification;
Only when Alipay Only when the transaction exists in the transaction management and the transaction status changes, Alipay will initiate a server notification through this method (the default status of the instant arrival transaction status is "Waiting for buyer payment"
will not send notifications );
Interaction between servers, unlike page jump synchronization notifications that can be displayed on the page, this interaction method is invisible;
The first transaction status changes (immediately at this time When the transaction status is transaction completed), not only will the synchronous processing result be returned, but the server asynchronous notification page will also receive the processing result notification from Alipay;
After the program is executed, "success" must be printed out (without quotation marks) . If the characters fed back to Alipay by the merchant are not the 7 characters of success, the Alipay server will continue to resend the notification until it exceeds 24 hours and 22 minutes.
Under normal circumstances, 8 notifications are completed within 25 hours (the interval frequency of notifications is generally: 4m, 10m, 10m, 1h, 2h, 6h, 15h);
After the program execution is completed, the page cannot be executed. Jump. If a page jump is executed, Alipay will not receive the success character, and the Alipay server will determine that the page program is running abnormally, and will resend the processing result notification;
cookies, sessions, etc. will be invalid on this page, that is, they cannot be obtained. These data;
The debugging and operation of this method must be on the server, that is, it can be accessed on the Internet;
The function of this method is mainly to prevent the loss of orders, that is, the page jump synchronization notification does not process the order update, it will process it ;
When the merchant receives the server asynchronous notification and prints out success, the server asynchronous notification parameter notify_id will become invalid. That is to say, when Alipay sends the same asynchronous notification
(including the fact that the merchant did not successfully print out the success and caused Alipay to resend the notification several times), the server asynchronous notification parameter notify_id remains unchanged.
Did you see that the program must be printed outsuccess
before Alipay will stop spewing blood? When I looked back at the program, I found that I had indeed not returned success
, so after the program ends, just return a success
. Since I'm using php, after the program ends. Just use the following sentence.
eg: echo "success";
2. WeChat Document
支付完成后,微信会把相关支付结果和用户信息发送给商户,商户需要接收处理,并返回应答。
对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,微信会通过一定的策略定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知
最终能成功。 (通知频率为15/15/30/180/1800/1800/1800/1800/3600,单位:秒)
注意:同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。
推荐的做法是,当收到通知进行处理时,首先检查对应业务数据的状态,判断该通知是否已经处理过,如果没有处理过再进行处理,如果处理过直接返回结果成功。
在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱。
特别提醒:商户系统对于支付结果通知的内容一定要做签名验证,并校验返回的订单金额是否与商户侧的订单金额一致,防止数据泄漏导致出现“假通知”,造成资金损失。
技术人员可登进微信商户后台扫描加入接口报警群。
看到没,在此文档也是,在微信的异步通知后,也需要给微信服务器,返回一个信息,只不过,微信的所有数据格式都是xml的。所以我们在返回一个数据给微信即可。
echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
在进行返回的时候,格式没问题,可能在输出的时候,存在问题。使用下面方式即可:
echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
就是这么简单,完美结局!
相关学习推荐:php视频教程
The above is the detailed content of How to implement Alipay payment function in PHP (detailed explanation with pictures and text). For more information, please follow other related articles on the PHP Chinese website!