Home Backend Development PHP Problem How to implement Alipay interface in php?

How to implement Alipay interface in php?

Jul 17, 2020 am 11:48 AM
php Alipay 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文件中对支付宝相关参数进行配置:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

//支付宝配置参数

  

'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',

  

),

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

<?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 "支付失败!";

  

    }

  

}

  

}

  

?>

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

//////////////////////////////////////////////////////

//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;

    }

}

Copy after login

三、总结几点

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles