search
HomeBackend DevelopmentPHP TutorialIntroduction to the callback method of thinkPHP framework docking with Alipay's instant payment interface

这篇文章主要介绍了thinkPHP框架对接支付宝即时到账接口回调操作,结合实例形式分析了thinkPHP针对支付宝接口回调操作的原理与具体操作步骤,需要的朋友可以参考下

本文实例讲述了thinkPHP框架对接支付宝即时到账接口回调操作。分享给大家供大家参考,具体如下:

关于支付宝即时收款接口的对接过程,很简单,也有很多人发过,我这里就不在啰嗦了,对接完成后,在线支付成功后的回调,相对来说,是个难点,,我重点分享下我的经验。

我在开发二代旅游CMS(http://www.erdaicms.com)的时候,在回调的时候,也花了不少时间。

不管是支付宝接口好是微信支付接口,回调都分为跳转回调和异步通知回调,跳转回调是不保险的,加入客人支付完成后马上把支付页面关闭,没跳转,就通知不到你这个订单已经支付了,所以我们要用异步通知回调:

$alipay_config['notify_url'] = "".$ss['web_url']."/v.php/Index-alipay_notify_url.html";

首先设置介绍异步回调的地址

异步回调的具体处理函数,我这里也贴处理,供参考:

/* 支付宝异步通知*/
public function alipay_notify_url()
{
  vendor('Alipay.Corefunction');
  vendor('Alipay.Md5function');
  vendor('Alipay.Notify');
  vendor('Alipay.Submit');
  $info=M('rewrite')->where(array('name'=>'alipay'))->find();
  $info=json_decode($info['content'],true);;
  //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//合作身份者ID,签约账号,以2088开头由16位纯数字组成的字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
$alipay_config['partner']    = $info['alipay_pid'];
//收款支付宝账号,以2088开头由16位纯数字组成的字符串,一般情况下收款账号就是签约账号
$alipay_config['seller_id'] = $info['alipay_pid'];
// MD5密钥,安全检验码,由数字和字母组成的32位字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
$alipay_config['key'] = $info['alipay_key'];
$ss=S('config');
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
$alipay_config['notify_url'] = "".$ss['web_url']."/v.php/Index-alipay_notify_url.html";
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
$alipay_config['return_url'] = "".$ss['web_url']."/member.php";
//签名方式
$alipay_config['sign_type'] = strtoupper('MD5');
//字符编码格式 目前支持 gbk 或 utf-8
$alipay_config['input_charset']= strtolower('utf-8');
//ca证书路径地址,用于curl中ssl校验
//请保证cacert.pem文件在当前文件夹目录中
$alipay_config['cacert'] = getcwd().'\\cacert.pem';
//访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
$alipay_config['transport'] = 'http';
// 支付类型 ,无需修改
$alipay_config['payment_type'] = "1";
// 产品类型,无需修改
$alipay_config['service'] = "create_direct_pay_by_user";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//↓↓↓↓↓↓↓↓↓↓ 请在这里配置防钓鱼信息,如果没开通防钓鱼功能,为空即可 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 防钓鱼时间戳 若要使用请调用类文件submit中的query_timestamp函数
$alipay_config['anti_phishing_key'] = "";
// 客户端的IP地址 非局域网的外网IP地址,如:221.0.0.1
$alipay_config['exter_invoke_ip'] = "";
  $alipayNotify = new \AlipayNotify($alipay_config);
  $verify_result = $alipayNotify->verifyNotify();
  if($verify_result) {//验证成功
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //请在这里加上商户的业务逻辑程序代
  //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
  //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表
  //商户订单号
  $out_trade_no = $_POST['out_trade_no'];
  //支付宝交易号
  $trade_no = $_POST['trade_no'];
  //交易状态
  $trade_status = $_POST['trade_status'];
  $total_fee=$_POST['total_fee'];
  //if( $info['alipay_pid']!=$seller_id) return ''; //收款账户不一致
  $info=M('order')->where(array('no'=>$out_trade_no))->find();
  if(!$info) return ''; //订单号不存在
  if($_POST['trade_status'] == 'TRADE_FINISHED') {
    //判断该笔订单是否在商户网站中已经做过处理
      //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
      //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
      //如果有做过处理,不执行商户的业务程序
       $data='';
      $data['status']=2;
      $data['pay_price']=$total_fee;
      $data['pay_type']='支付宝';
      $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);
        }
       }
       }
      }
    //注意:
    //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
    //调试用,写文本函数记录程序运行情况是否正常
    //logResult("这里写入想要调试的代码变量值,或其他运行的结果记录");
  }
  else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
    //判断该笔订单是否在商户网站中已经做过处理
      //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
      //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
      //如果有做过处理,不执行商户的业务程序
      $data='';
      $data['status']=2;
      $data['pay_price']=$total_fee;
      $data['pay_type']='支付宝';
      $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);
        }
       }
       }
      }
    //注意:
    //付款完成后,支付宝系统发送该交易状态通知
    //调试用,写文本函数记录程序运行情况是否正常
    //logResult("这里写入想要调试的代码变量值,或其他运行的结果记录");
  }
  //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
  echo "success";    //请不要修改或删除
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else {
  //验证失败
  echo "fail";
  //调试用,写文本函数记录程序运行情况是否正常
  //logResult("这里写入想要调试的代码变量值,或其他运行的结果记录");
}
}

因为是异步通知,所以调试是个麻烦事,不能所见即所得,也就是说,一般情况下没办法echo或者print_r打印输出结果,没办法知道他执行到哪里或者执行结果,这个时候,我们就用到log文件输出,代码:

$file = './log.txt';//要写入文件的文件名(可以是任意文件名),如果文件不存在,将会创建一个
$content = "支付成功".$bdata['total_fee']."\n"; //要写入的内容
file_put_contents($file, $content,FILE_APPEND);//写入文件

以上代码会在根目录下自动生成一个log.txt的文件,这样,就可以轻松知道执行结果,方便调试了

支付宝的异步通知接口,会多次通知,直到你返回success为止,也就是说,你提交一个测试订单,可以测试很多次,因为你没有返回success的话,他会每隔一定时间,通知一次

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

ThinkPHP写数组插入与获取最新插入数据ID的方法

关于thinkphp实现发送邮件密码找回功能的介绍

The above is the detailed content of Introduction to the callback method of thinkPHP framework docking with Alipay's instant payment interface. For more information, please follow other related articles on the PHP Chinese website!

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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools