SoFunction
Updated on 2025-03-02

ThinkPHP framework docking Alipay instant account arrival interface callback operation example

This article describes the callback operation of the thinkPHP framework docking Alipay instant account arrival interface. Share it for your reference, as follows:

The docking process of Alipay’s instant payment interface is very simple, and many people have sent it. I won’t talk about it here. After the docking is completed, the callback after the online payment is successful is relatively difficult. I will focus on sharing my experience.

When I was developing the second-generation tourism CMS(), I also spent a lot of time during callbacks.

Whether it is the Alipay interface or the WeChat payment interface, the callbacks are divided into jump callbacks and asynchronous notification callbacks. Jump callbacks are not insured. After joining the customer, the payment page will be closed immediately. If you do not jump, you will not notify that the order has been paid. Therefore, we need to use asynchronous notification callbacks:

Copy the codeThe code is as follows:
$alipay_config['notify_url'] = "".$ss['web_url']."//Index-alipay_notify_url.html";

First, set the address that introduces the asynchronous callback

I will also post the specific processing function of asynchronous callbacks here for reference:

/* Alipay asynchronous notification*/
public function alipay_notify_url()
{
  vendor('');
  vendor('Alipay.Md5function');
  vendor('');
  vendor('');
  $info=M('rewrite')->where(array('name'=>'alipay'))->find();
  $info=json_decode($info['content'],true);;
  //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ Please configure your basic information here↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓�//Cooperating identity ID, signing account, a string composed of 16 pure numbers starting with 2088, view address: /order/$alipay_config['partner']    = $info['alipay_pid'];
//The Alipay account for the payment collection is a string composed of 16 pure numbers starting with 2088. Generally speaking, the payment collection account is the signing account$alipay_config['seller_id'] = $info['alipay_pid'];
// MD5 key, security verification code, 32-bit string composed of numbers and letters, view address: /order/$alipay_config['key'] = $info['alipay_key'];
$ss=S('config');
// The server asynchronous notification page path requires the complete path in the format http:// format. You cannot add custom parameters such as ?id=123. It must be accessed normally by the external network.$alipay_config['notify_url'] = "".$ss['web_url']."//Index-alipay_notify_url.html";
// Page jump synchronous notification page path requires the complete path of http:// format, and cannot add custom parameters such as ?id=123, and must be accessed normally by the external network.$alipay_config['return_url'] = "".$ss['web_url']."/";
//Signature method$alipay_config['sign_type'] = strtoupper('MD5');
//Character encoding format currently supports gbk or utf-8$alipay_config['input_charset']= strtolower('utf-8');
//Ca certificate path address, used for ssl verification in curl//Please make sure the file is in the current folder directory$alipay_config['cacert'] = getcwd().'\\';
//Access mode, depending on whether your server supports SSL access, if it supports, please select https; if it does not support, please select http.$alipay_config['transport'] = 'http';
// Payment type, no modification required$alipay_config['payment_type'] = "1";
// Product type, no modification required$alipay_config['service'] = "create_direct_pay_by_user";
//↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑�//↓↓↓↓↓↓↓↓↓↓↓↓↓↓ Please configure anti-fishing information here. If the anti-fishing function is not enabled, it is empty ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓�// Anti-phishing timestamp. To use, please call the query_timestamp function in the submit class file$alipay_config['anti_phishing_key'] = "";
// Client IP address The external network IP address of non-local network, such as: 221.0.0.1$alipay_config['exter_invoke_ip'] = "";
  $alipayNotify = new \AlipayNotify($alipay_config);
  $verify_result = $alipayNotify->verifyNotify();
  if($verify_result) {//Verification is successful  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //Please add the business logic program of the merchant here  //—Please write the program according to your business logic (the following code is for reference only)—  //Get the notification return parameters of Alipay, please refer to the technical document for the server asynchronous notification parameter list.  // Merchant Order Number  $out_trade_no = $_POST['out_trade_no'];
  //Alipay transaction number  $trade_no = $_POST['trade_no'];
  //Trading status  $trade_status = $_POST['trade_status'];
  $total_fee=$_POST['total_fee'];
  //if( $info['alipay_pid']!=$seller_id) return ''; //The collection account is inconsistent  $info=M('order')->where(array('no'=>$out_trade_no))->find();
  if(!$info) return ''; //The order number does not exist  if($_POST['trade_status'] == 'TRADE_FINISHED') {
    //Judge whether the order has been processed on the merchant website      //If there is no processing, find the details of the order in the order system of the merchant website according to the order number (out_trade_no), and execute the merchant's business procedures.      //Please be sure to determine that the total_fee and seller_id at the request are consistent with the total_fee and seller_id obtained at the notification.      //If there has been any processing, the merchant's business procedures will not be executed       $data='';
      $data['status']=2;
      $data['pay_price']=$total_fee;
      $data['pay_type']='Alipay';
      $data['buyer']=$_POST['buyer_email'];
      $data['trade_no']=$trade_no;
      $data['pay_time']=time();
      M('order')->where(array('no'=>$out_trade_no))->save($data);
      $c=M('smtp_templates')->where(array('id'=>5))->find();
      if($c['status']==1)
      {
        $content = str_replace('{title}', $info['goods_name'], $c['content']);
        $content = str_replace('{id}', $info['goods_id'], $content);
        $content = str_replace('{price}',$total_fee, $content);
        $content = str_replace('{time}',date('Y-m-d H:i:s',time()), $content);
       $c=M('email_note')->where(array('pay_id'=>$out_trade_no))->find();
       if(!$c)
       {
       $e='';
       $e['email']=$info['c_email'];
       $e['content']=$content;
       $e['pay_id']=$out_trade_no;
       M('email_note')->add($e);
       $m=explode('|',$c['ather']);
       foreach($m as $mail)
       {
        if(validate_email($mail))
        {
         $e['email']=$mail;
         M('email_note')->add($e);
        }
       }
       }
      }
    //Notice:    //After the refund date exceeds the refundable period (if you can refund for three months), the Alipay system will send a notification of the transaction status    //For debugging, write text functions to record whether the program runs normally    //logResult("Write the code variable value you want to debug, or other running result record");  }
  else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
    //Judge whether the order has been processed on the merchant website      //If there is no processing, find the details of the order in the order system of the merchant website according to the order number (out_trade_no), and execute the merchant's business procedures.      //Please be sure to determine that the total_fee and seller_id at the request are consistent with the total_fee and seller_id obtained at the notification.      //If there has been any processing, the merchant's business procedures will not be executed      $data='';
      $data['status']=2;
      $data['pay_price']=$total_fee;
      $data['pay_type']='Alipay';
      $data['buyer']=$_POST['buyer_email'];
      $data['trade_no']=$trade_no;
      $data['pay_time']=time();
      M('order')->where(array('no'=>$out_trade_no))->save($data);
       $c=M('smtp_templates')->where(array('id'=>5))->find();
      if($c['status']==1)
      {
        $content = str_replace('{title}', $info['goods_name'], $c['content']);
        $content = str_replace('{id}', $info['goods_id'], $content);
        $content = str_replace('{price}',$total_fee, $content);
        $content = str_replace('{time}',date('Y-m-d H:i:s',time()), $content);
       $c=M('email_note')->where(array('pay_id'=>$out_trade_no))->find();
       if(!$c)
       {
       $e='';
       $e['email']=$info['c_email'];
       $e['content']=$content;
       $e['pay_id']=$out_trade_no;
       M('email_note')->add($e);
       $m=explode('|',$c['ather']);
       foreach($m as $mail)
       {
        if(validate_email($mail))
        {
         $e['email']=$mail;
         M('email_note')->add($e);
        }
       }
       }
      }
    //Notice:    //After the payment is completed, the Alipay system will send a notification of the transaction status    //For debugging, write text functions to record whether the program runs normally    //logResult("Write the code variable value you want to debug, or other running result record");  }
  //—Please write the program according to your business logic (the above code is for reference only)—  echo "success";    //Please do not modify or delete  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else {
  //Verification failed  echo "fail";
  //For debugging, write text functions to record whether the program runs normally  //logResult("Write the code variable value you want to debug, or other running result record");}
}

Because it is an asynchronous notification, debugging is a troublesome thing, and what you see is what you get. That is to say, in general, there is no way to echo or print_r print output result, and there is no way to know where it is executed or the result of the execution. At this time, we use the log file output, code:

$file = './';//The file name to be written to the file (can be any file name). If the file does not exist, a$content = "Payment Success".$bdata['total_fee']."\n"; //What to writefile_put_contents($file, $content,FILE_APPEND);//Write to file

The above code will automatically generate a file in the root directory, so that you can easily know the execution result and facilitate debugging.

Alipay's asynchronous notification interface will notify many times until you return success. That is to say, if you submit a test order, you can test it many times, because if you do not return success, it will notify you every certain time.

For more information about thinkPHP related content, please check out the topic of this site:ThinkPHP Introduction Tutorial》、《Summary of thinkPHP template operation skills》、《Summary of common methods of ThinkPHP》、《Basic tutorial on getting started with smarty templates"and"PHP template technical summary》。

I hope that the description in this article will be helpful to everyone's PHP programming based on the ThinkPHP framework.