Example of Alipay payment function implemented by PHP


This article describes the Alipay payment function implemented by PHP. To share with you for your reference, as follows:

When making Alipay payment interface for app, collect the contents as follows:


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' = > red packet payment ',
  'subject' = > 'user red packet payment',
  '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); // it's different from the normal interface call here. It uses SDK execute
$response = $aop->sdkExecute($request);
$return ['aliresponse '] = $response; // htmlspecialchars ($response); // htmlspecialchars are used to prevent the key parameter HTML from being escaped by the browser when outputting to the page. This problem will not exist in the actual printing to the log and HTTP transmission

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){
      //After passing the verification, verify the following parameters trade_ status、out_ trade_ no、total_ amount、seller_ ID
      if (isset($_POST['trade_status']) && ($_POST['trade_status'] == 'TRADE_SUCCESS' || $_POST['trade_status'] == 'TRADE_FINISHED') ) {
        //Business processing
      } 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);

Attachment: Alipay payment and WeChat payment asynchronous callback has been called

Recently, the company has been developing WeChat payment and Alipay payment. The previous work has been done, but when the asynchronous callback value is taken, the asynchronous callback has been calling, so that my data has been stored repeatedly in the database. I really feel that my aunt has come and can not stop at all. Ha ha, don’t drive anymore. When you see the problem and think about it carefully, one of the solutions that comes to mind immediately is to write another interface in the asynchronous callback. After each callback gets the data, query the database to see if there is any data. If there is any data, don’t save it repeatedly. But think carefully, no, it’s a cure for the symptoms or the root. No, since there is a problem There must be root causes and correct solutions. So, to find the basis, it is to view the document:

1. Alipay documentationHere’s the Alipay asynchronous callback document: click open the official link.

Server asynchronous notification page features
The server asynchronous notification page (notify) must be guaranteed_ URL) without any characters, such as space, HTML tag, exception prompt information provided by the development system;
Alipay sends the notification information in POST mode, so the way to get the parameters in the page is as follows: request.Form (“out_ trade_ no”)、$_ POST[‘out_ trade_ no’];
Alipay initiatively announced that the way would be activated.
Only when the transaction exists in the transaction management of Alipay, and the transaction state changes, will Alipay initiate the server notification through this way (the status of the instant arrival transaction is the state of “waiting for the buyer to pay”).
No notice will be sent);
The interaction between servers, unlike the page Jump synchronization notice can be displayed on the page, this interaction mode is invisible;
The first transaction state change (when the transaction status is immediately completed in the arrival account) is not only going to return the synchronization result, but also the server asynchronous notification page will receive the notification of Alipay’s processing results.
The program must print out “success” (without quotes) after execution. If the merchant’s feedback to Alipay’s characters is not success’s 7 characters, the Alipay server will continue to reissue the notification until more than 24 hours and 22 minutes.
Generally, 8 notices shall be completed within 25 hours (the interval frequency of notices is generally: 4m, 10m, 10m, 1H, 2h, 6h, 15h);
After the program is executed, the page cannot jump. If the page is skipping, Alipay will not receive the success character. It will be judged by the Alipay server to run an exception for the page program and reissue the result notification.
Cookies, sessions, etc. will fail on this page, i.e. these data cannot be obtained;
The debugging and operation of this mode must be on the server, that is, the Internet can access;
The function of this method is mainly to prevent order loss, that is, the page Jump synchronization notice does not process the order update, it processes it;
When the merchant receives the asynchronous notification from the server and prints out success, the asynchronous notification parameter notify from the server_ ID will be invalid. That is to say, when sending the same asynchronous notification at Alipay,
(including merchants did not print success successfully, resulting in repeated notification of Alipay), server asynchronous notification parameter notify_ The ID is the same.

See, the program must print out success, Alipay will stop bleeding, when I look back at the program again, I found that I did not return to success, so after the program is finished, return to a success. Because of the PHP I use, after the end of the program. Use the following sentence.

echo "success";

2. Wechat documentsClick to open the official link

After the payment is completed, wechat will send the relevant payment results and user information to the merchant, which needs to receive and process and return the response.
When interacting with back-end notifications, if wechat receives a response from a merchant that is not successful or overtime, wechat considers the notification to be failed, wechat will periodically re launch the notification through a certain strategy to improve the success rate of the notification as much as possible, but wechat does not guarantee the notification
It’s going to work. (notification frequency is 15 / 15 / 30 / 180 / 1800 / 1800 / 1800 / 1800 / 3600, unit: Second)
Note: the same notification may be sent to the merchant system multiple times. The merchant system must be able to correctly handle duplicate notifications.
It is recommended to check the status of the corresponding business data when receiving the notice for processing, and judge whether the notice has been processed. If it has not been processed, process it again. If it has been processed, directly return the result successfully.
Before checking and processing the status of business data, data lock should be used for concurrency control to avoid data confusion caused by function re-entry.
Special reminder: the merchant system must conduct signature verification for the content of payment result notification, and verify whether the returned order amount is consistent with the order amount on the merchant side, so as to prevent data leakage leading to “false notification” and capital loss.
Technicians can log in the wechat merchant background scan to join the interface alarm group.

See? This document also needs to return a message to the wechat server after the asynchronous notification of wechat. However, all the data formats of wechat are XML. So we are returning a data to wechat.

echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"; 

When returning, there is no problem with the format. Maybe there is a problem with the output. Use the following methods:

echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');

It is so simple that immediately stopped WeChat and Alipay’s blood, the perfect ending!

Reference link:

Mobile Website Payment result asynchronous notification https://docs.open.alipay.com/203/105286/

Demo & SDK of APP payment server https://docs.open.alipay.com/54/106370/

Reference article:


For more information about PHP, readers who are interested in PHP, please refer to the following topics: summary of PHP wechat development skills, summary of PHP curl usage, summary of PHP network programming skills, summary of PHP string usage, summary of JSON format data operation skills in PHP and summary of PHP operation skills for XML files

I hope this article is helpful for PHP programming.

Recommended Today

IView, upload component beforeupload compress image

critical code <Upload multiple :format=”[‘jpg’,’jpeg’,’png’]” :beforeUpload=”beforeUpload” action=”” :on-success=”upload” > < button icon = “IOS cloud upload outline” > upload picture < / button > </Upload> import Compressor from “compressorjs” beforeUpload(file) { return new Promise((resolve, reject) => { let isLt1M = file.size / 1024 / 1024 < 1; if (isLt1M) { resolve(file); } new Compressor(file, { […]