search
HomeBackend DevelopmentPHP ProblemHow to implement Alipay interface in php?

How to implement Alipay interface in php?

Jul 17, 2020 am 11:48 AM
phpAlipay interface

php实现支付宝接口的方法:首先下载支付宝接口包;然后在项目中调用支付宝接口,并对支付宝相关参数进行配置;最后新建一个PayAction控制器即可。

How to implement Alipay interface in php?

php实现支付宝接口的方法:

一、下载支付宝接口包

下载地址:

https://doc.open.alipay.com/doc2/detail?treeId=62&articleId=103566&docType=1

二、在项目中调用支付宝接口

调用分两步:

1、在配置文件中Conf/Config.php文件中对支付宝相关参数进行配置:

//支付宝配置参数
 
'alipay_config'=>array(
 
       'partner' =>'20********50',   //这里是你在成功申请支付宝接口后获取到的PID;
 
    'key'=>'9t***********ie',//这里是你在成功申请支付宝接口后获取到的Key
 
    'sign_type'=>strtoupper('MD5'),
 
    'input_charset'=> strtolower('utf-8'),
 
    'cacert'=> getcwd().'\\cacert.pem',
 
    'transport'=> 'http',
 
      ),
 
//以上配置项,是从接口包中alipay.config.php 文件中复制过来,进行配置;
 
'alipay'   =>array(
 
 //这里是卖家的支付宝账号,也就是你申请接口时注册的支付宝账号
 
'seller_email'=>'pay@xxx.com',
 
//这里是异步通知页面url,提交到项目的Pay控制器的notifyurl方法;
 
'notify_url'=>'http://www.xxx.com/Pay/notifyurl', 
 
//这里是页面跳转通知url,提交到项目的Pay控制器的returnurl方法;
 
'return_url'=>'http://www.xxx.com/Pay/returnurl',
 
//支付成功跳转到的页面,我这里跳转到项目的User控制器,myorder方法,并传参payed(已支付列表)
 
'successpage'=>'User/myorder?ordtype=payed',   
 
//支付失败跳转到的页面,我这里跳转到项目的User控制器,myorder方法,并传参unpay(未支付列表)
 
'errorpage'=>'User/myorder?ordtype=unpay', 
 
),

2、新建一个PayAction控制器代码如下:

<?php
 
class PayAction extends Action{
 
       //在类初始化方法中,引入相关类库    
 
       public function _initialize() {
 
        vendor(&#39;Alipay.Corefunction&#39;);
 
        vendor(&#39;Alipay.Md5function&#39;);
 
        vendor(&#39;Alipay.Notify&#39;);
 
        vendor(&#39;Alipay.Submit&#39;);    
 
    }
 
    
 
    //doalipay方法
 
        /*该方法其实就是将接口文件包下alipayapi.php的内容复制过来
 
          然后进行相关处理
 
        */
 
    public function doalipay(){
 
            /*********************************************************
 
            把alipayapi.php中复制过来的如下两段代码去掉,
 
            第一段是引入配置项,
 
            第二段是引入submit.class.php这个类。
 
           为什么要去掉??
 
            第一,配置项的内容已经在项目的Config.php文件中进行了配置,我们只需用C函数进行调用即可;
 
            第二,这里调用的submit.class.php类库我们已经在PayAction的_initialize()中已经引入;所以这里不再需要;
 
            *****************************************************/
 
       // require_once("alipay.config.php");
 
       // require_once("lib/alipay_submit.class.php");
 
       
 
       //这里我们通过TP的C函数把配置项参数读出,赋给$alipay_config;
 
       $alipay_config=C(&#39;alipay_config&#39;);  
 
 
 
        /**************************请求参数**************************/
 
        $payment_type = "1"; //支付类型 //必填,不能修改
 
        $notify_url = C(&#39;alipay.notify_url&#39;); //服务器异步通知页面路径
 
        $return_url = C(&#39;alipay.return_url&#39;); //页面跳转同步通知页面路径
 
        $seller_email = C(&#39;alipay.seller_email&#39;);//卖家支付宝帐户必填
 
        $out_trade_no = $_POST[&#39;trade_no&#39;];//商户订单号 通过支付页面的表单进行传递,注意要唯一!
 
        $subject = $_POST[&#39;ordsubject&#39;];  //订单名称 //必填 通过支付页面的表单进行传递
 
        $total_fee = $_POST[&#39;ordtotal_fee&#39;];   //付款金额  //必填 通过支付页面的表单进行传递
 
        $body = $_POST[&#39;ordbody&#39;];  //订单描述 通过支付页面的表单进行传递
 
        $show_url = $_POST[&#39;ordshow_url&#39;];  //商品展示地址 通过支付页面的表单进行传递
 
        $anti_phishing_key = "";//防钓鱼时间戳 //若要使用请调用类文件submit中的query_timestamp函数
 
        $exter_invoke_ip = get_client_ip(); //客户端的IP地址 
 
        /************************************************************/
 
    
 
        //构造要请求的参数数组,无需改动
 
    $parameter = array(
 
        "service" => "create_direct_pay_by_user",
 
        "partner" => trim($alipay_config[&#39;partner&#39;]),
 
        "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[&#39;input_charset&#39;]))
 
        );
 
        //建立请求
 
        $alipaySubmit = new AlipaySubmit($alipay_config);
 
        $html_text = $alipaySubmit->buildRequestForm($parameter,"post", "确认");
 
        echo $html_text;
 
    }
 
    
 
        /******************************
 
        服务器异步通知页面方法
 
        其实这里就是将notify_url.php文件中的代码复制过来进行处理
 
        
 
        *******************************/
 
    function notifyurl(){
 
                /*
 
                同理去掉以下两句代码;
 
                */ 
 
                //require_once("alipay.config.php");
 
                //require_once("lib/alipay_notify.class.php");
 
                
 
                //这里还是通过C函数来读取配置项,赋值给$alipay_config
 
        $alipay_config=C(&#39;alipay_config&#39;);
 
        //计算得出通知验证结果
 
        $alipayNotify = new AlipayNotify($alipay_config);
 
        $verify_result = $alipayNotify->verifyNotify();
 
        if($verify_result) {
 
               //验证成功
 
                   //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表
 
           $out_trade_no   = $_POST[&#39;out_trade_no&#39;];      //商户订单号
 
           $trade_no       = $_POST[&#39;trade_no&#39;];          //支付宝交易号
 
           $trade_status   = $_POST[&#39;trade_status&#39;];      //交易状态
 
           $total_fee      = $_POST[&#39;total_fee&#39;];         //交易金额
 
           $notify_id      = $_POST[&#39;notify_id&#39;];         //通知校验ID。
 
           $notify_time    = $_POST[&#39;notify_time&#39;];       //通知的发送时间。格式为yyyy-MM-dd HH:mm:ss。
 
           $buyer_email    = $_POST[&#39;buyer_email&#39;];       //买家支付宝帐号;
 
                   $parameter = array(
 
             "out_trade_no"     => $out_trade_no, //商户订单编号;
 
             "trade_no"     => $trade_no,     //支付宝交易号;
 
             "total_fee"     => $total_fee,    //交易金额;
 
             "trade_status"     => $trade_status, //交易状态
 
             "notify_id"     => $notify_id,    //通知校验ID。
 
             "notify_time"   => $notify_time,  //通知的发送时间。
 
             "buyer_email"   => $buyer_email,  //买家支付宝帐号;
 
           );
 
           if($_POST[&#39;trade_status&#39;] == &#39;TRADE_FINISHED&#39;) {
 
                       //
 
           }else if ($_POST[&#39;trade_status&#39;] == &#39;TRADE_SUCCESS&#39;) {                           if(!checkorderstatus($out_trade_no)){
 
               orderhandle($parameter); 
 
                           //进行订单处理,并传送从支付宝返回的参数;
 
               }
 
            }
 
                echo "success";        //请不要修改或删除
 
         }else {
 
                //验证失败
 
                echo "fail";
 
        }    
 
    }
 
    
 
    /*
 
        页面跳转处理方法;
 
        这里其实就是将return_url.php这个文件中的代码复制过来,进行处理; 
 
        */
 
    function returnurl(){
 
                //头部的处理跟上面两个方法一样,这里不罗嗦了!
 
        $alipay_config=C(&#39;alipay_config&#39;);
 
        $alipayNotify = new AlipayNotify($alipay_config);//计算得出通知验证结果
 
        $verify_result = $alipayNotify->verifyReturn();
 
        if($verify_result) {
 
            //验证成功
 
            //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表
 
        $out_trade_no   = $_GET[&#39;out_trade_no&#39;];      //商户订单号
 
        $trade_no       = $_GET[&#39;trade_no&#39;];          //支付宝交易号
 
        $trade_status   = $_GET[&#39;trade_status&#39;];      //交易状态
 
        $total_fee      = $_GET[&#39;total_fee&#39;];         //交易金额
 
        $notify_id      = $_GET[&#39;notify_id&#39;];         //通知校验ID。
 
        $notify_time    = $_GET[&#39;notify_time&#39;];       //通知的发送时间。
 
        $buyer_email    = $_GET[&#39;buyer_email&#39;];       //买家支付宝帐号;
 
            
 
        $parameter = array(
 
            "out_trade_no"     => $out_trade_no,      //商户订单编号;
 
            "trade_no"     => $trade_no,          //支付宝交易号;
 
            "total_fee"      => $total_fee,         //交易金额;
 
            "trade_status"     => $trade_status,      //交易状态
 
            "notify_id"      => $notify_id,         //通知校验ID。
 
            "notify_time"    => $notify_time,       //通知的发送时间。
 
            "buyer_email"    => $buyer_email,       //买家支付宝帐号
 
        );
 
        
 
if($_GET[&#39;trade_status&#39;] == &#39;TRADE_FINISHED&#39; || $_GET[&#39;trade_status&#39;] == &#39;TRADE_SUCCESS&#39;) {
 
        if(!checkorderstatus($out_trade_no)){
 
             orderhandle($parameter);  //进行订单处理,并传送从支付宝返回的参数;
 
    }
 
        $this->redirect(C(&#39;alipay.successpage&#39;));//跳转到配置项中配置的支付成功页面;
 
    }else {
 
        echo "trade_status=".$_GET[&#39;trade_status&#39;];
 
        $this->redirect(C(&#39;alipay.errorpage&#39;));//跳转到配置项中配置的支付失败页面;
 
    }
 
}else {
 
    //验证失败
 
    //如要调试,请看alipay_notify.php页面的verifyReturn函数
 
    echo "支付失败!";
 
    }
 
}
 
}
 
?>

3、这里有几个支付处理过程中需要用到的函数,我把这些函数写到了项目的Common/common.php中,这样不用手动调用,即可直接使用这些函数,代码如下:

//////////////////////////////////////////////////////
//Orderlist数据表,用于保存用户的购买订单记录;
/* Orderlist数据表结构;
CREATE TABLE `tb_orderlist` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(11) DEFAULT NULL,购买者userid
  `username` varchar(255) DEFAULT NULL,购买者姓名
  `ordid` varchar(255) DEFAULT NULL,订单号
  `ordtime` int(11) DEFAULT NULL,订单时间
  `productid` int(11) DEFAULT NULL,产品ID
  `ordtitle` varchar(255) DEFAULT NULL,订单标题
  `ordbuynum` int(11) DEFAULT &#39;0&#39;,购买数量
  `ordprice` float(10,2) DEFAULT &#39;0.00&#39;,产品单价
  `ordfee` float(10,2) DEFAULT &#39;0.00&#39;,订单总金额
  `ordstatus` int(11) DEFAULT &#39;0&#39;,订单状态
  `payment_type` varchar(255) DEFAULT NULL,支付类型
  `payment_trade_no` varchar(255) DEFAULT NULL,支付接口交易号
  `payment_trade_status` varchar(255) DEFAULT NULL,支付接口返回的交易状态
  `payment_notify_id` varchar(255) DEFAULT NULL,
  `payment_notify_time` varchar(255) DEFAULT NULL,
  `payment_buyer_email` varchar(255) DEFAULT NULL,
  `ordcode` varchar(255) DEFAULT NULL,       //这个字段不需要的,大家看我西面的修正补充部分的说明!
  `isused` int(11) DEFAULT &#39;0&#39;,
  `usetime` int(11) DEFAULT NULL,
  `checkuser` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
 
*/
//在线交易订单支付处理函数
//函数功能:根据支付接口传回的数据判断该订单是否已经支付成功;
//返回值:如果订单已经成功支付,返回true,否则返回false;
function checkorderstatus($ordid){
    $Ord=M(&#39;Orderlist&#39;);
    $ordstatus=$Ord->where(&#39;ordid=&#39;.$ordid)->getField(&#39;ordstatus&#39;);
    if($ordstatus==1){
        return true;
    }else{
        return false;    
    }
}
 
//处理订单函数
//更新订单状态,写入订单支付后返回的数据
function orderhandle($parameter){
    $ordid=$parameter[&#39;out_trade_no&#39;];
    $data[&#39;payment_trade_no&#39;]      =$parameter[&#39;trade_no&#39;];
    $data[&#39;payment_trade_status&#39;]  =$parameter[&#39;trade_status&#39;];
    $data[&#39;payment_notify_id&#39;]     =$parameter[&#39;notify_id&#39;];
    $data[&#39;payment_notify_time&#39;]   =$parameter[&#39;notify_time&#39;];
    $data[&#39;payment_buyer_email&#39;]   =$parameter[&#39;buyer_email&#39;];
    $data[&#39;ordstatus&#39;]             =1;
    $Ord=M(&#39;Orderlist&#39;);
    $Ord->where(&#39;ordid=&#39;.$ordid)->save($data);
} 
 
 
 
/*-----------------------------------
2013.8.13更正
下面这个函数,其实不需要,大家可以把他删掉,
具体看我下面的修正补充部分的说明
------------------------------------*/
 
//获取一个随机且唯一的订单号;
function getordcode(){
    $Ord=M(&#39;Orderlist&#39;);
    $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=&#39;".$ordcode."&#39;")->getField(&#39;ordcode&#39;);
    if($oldcode){
        getordcode();
    }else{
        return $ordcode;
    }
}

三、总结几点

1、接口包中lib文件中的文件复制到Vendor后,重命名为TP规范的命名规则,为的是调用方便,当然你要改成其他名称也可以;

2、把执行支付操作(doalipay),处理异步返回结果(notifyurl),处理跳转返回结果(returnurl)三个支付接口的核心页面写到一个PayAction控制器中。

3、提交支付的页面中,可以在提交之前先把一些参数要传递的内容先通过隐藏域的方法组合好,比如金额先计算好,订单名称,订单描述等先用字符串组合好。然后提交表单,这样,在doalipay方法中只要直接构造传递参数,直接进行提交就行过了。

4、支付返回后的处理因为要在异步和跳转两个方法中都要进行相应的判断和处理,所以,把这些判断和处理写到一个自定义函数中,这样只要调用函数即可,使得代码更加清晰明了。

5、notify_urlreturn_url两种模式的返回url必须使用http://xxxxxxx这样的绝对路径,因为里是从支付宝平台返回到你的项目页面。不能使用相对路径。

相关学习推荐:PHP编程从入门到精通

The above is the detailed content of How to implement Alipay interface in php?. 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),