Home Backend Development PHP Tutorial How to integrate Alipay APP payment into PHP server

How to integrate Alipay APP payment into PHP server

Jul 03, 2018 pm 04:57 PM

Let me share with you an example of PHP server integrating Alipay APP payment. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

Alipay payment is divided into many scenarios. Here we only describe the integration of Alipay APP payment function. We encountered particularly big pitfalls during the process, so I will briefly describe the integration process and outline the problems encountered. And solution

Since the company's business is simple and only supports Alipay payment, there is no need to care about refunds, inquiries and other additional functions. Therefore, this article only describes how the server prepares the APP to pull payment orders when using the Alipay payment interface. The general process is as follows

1. Create application and configuration

First, you need to go to the Ant Financial development platform (open.alipay. com) to register the application, obtain the application ID, and configure the application. The configuration here mainly involves signing a contract, generating the application's RSA2 public and private keys, and obtaining the payment public key provided by Alipay. There are prompts in the background of this part of the official website, which is relatively simple.

2. Download the corresponding SDK

Here I am integrating the service in the PHP background, so I downloaded the PHP SDK, address: https:/ /docs.open.alipay.com/54/103419/

3. Prepare an accessible real domain name

4. Case

After the above three steps are completed, we can now configure our own business code

4.1. Organize APP payment Payment order information at the time

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

<?php

 

require_once (__DIR__.&#39;/alipay-sdk-PHP-20171023143822/AopSdk.php&#39;);

 

class Alipay

{

 /**

 * 应用ID

 */

 const APPID = &#39;你的应用ID&#39;;

 /**

 *请填写开发者私钥去头去尾去回车,一行字符串

 */

 const RSA_PRIVATE_KEY = &#39;应用对应开发者私钥&#39;;

 /**

 *请填写支付宝公钥,一行字符串

 */

 const ALIPAY_RSA_PUBLIC_KEY = &#39;支付宝提供的公钥&#39;;

 /**

 * 支付宝服务器主动通知商户服务器里指定的页面

 * @var string

 */

 private $callback = "http://www.test.com/notify/alipay_notify.php";

 

 /**

 *生成APP支付订单信息

 * @param string $orderId 商品订单ID

 * @param string $subject 支付商品的标题

 * @param string $body 支付商品描述

 * @param float $pre_price 商品总支付金额

 * @param int $expire 支付交易时间

 * @return bool|string 返回支付宝签名后订单信息,否则返回false

 */

 public function unifiedorder($orderId, $subject,$body,$pre_price,$expire){

 try{

  $aop = new \AopClient();

  $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";

  $aop->appId = self::APPID;

  $aop->rsaPrivateKey = self::RSA_PRIVATE_KEY;

  $aop->format = "json";

  $aop->charset = "UTF-8";

  $aop->signType = "RSA2";

  $aop->alipayrsaPublicKey = self::ALIPAY_RSA_PUBLIC_KEY;

  //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay

  $request = new \AlipayTradeAppPayRequest();

  //SDK已经封装掉了公共参数,这里只需要传入业务参数

  $bizcontent = "{\"body\":\"{$body}\"," //支付商品描述

  . "\"subject\":\"{$subject}\"," //支付商品的标题

  . "\"out_trade_no\":\"{$orderId}\"," //商户网站唯一订单号

  . "\"timeout_express\":\"{$expire}m\"," //该笔订单允许的最晚付款时间,逾期将关闭交易

  . "\"total_amount\":\"{$pre_price}\"," //订单总金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000]

  . "\"product_code\":\"QUICK_MSECURITY_PAY\""

  . "}";

  $request->setNotifyUrl($this->callback);

  $request->setBizContent($bizcontent);

  //这里和普通的接口调用不同,使用的是sdkExecute

  $response = $aop->sdkExecute($request);

  //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题

  return htmlspecialchars($response);//就是orderString 可以直接给客户端请求,无需再做处理。

 }catch (\Exception $e){

  return false;

 }

 

 }

}

Copy after login

4.2. Asynchronous callback processing after successful Alipay payment

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

<?php

/**

 * alipay_notify.php.

 * User: lvfk

 * Date: 2017/10/26 0026

 * Time: 13:48

 * Desc: 支付宝支付成功异步通知

 */

include_once (__DIR__.&#39;/../alipay-sdk-PHP-20171023143822/AopSdk.php&#39;);

 

//验证签名

$aop = new \AopClient();

$aop->alipayrsaPublicKey = \Comm\Pay\Alipay::ALIPAY_RSA_PUBLIC_KEY;

$flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");

 

//验签

if($flag){

 //处理业务,并从$_POST中提取需要的参数内容

 if($_POST[&#39;trade_status&#39;] == &#39;TRADE_SUCCESS&#39;

 || $_POST[&#39;trade_status&#39;] == &#39;TRADE_FINISHED&#39;){//处理交易完成或者支付成功的通知

 //获取订单号

 $orderId = $_POST[&#39;out_trade_no&#39;];

 //交易号

 $trade_no = $_POST[&#39;trade_no&#39;];

 //订单支付时间

 $gmt_payment = $_POST[&#39;gmt_payment&#39;];

 //转换为时间戳

 $gtime = strtotime($gmt_payment);

 

 //此处编写回调处理逻辑

 

        //处理成功一定要返回 success 这7个字符组成的字符串,

        //die(&#39;success&#39;);//响应success表示业务处理成功,告知支付宝无需在异步通知

  

 }

}

Copy after login

5. Problems Encountered

##5.1. Keep reporting error 40001=>isv.invalid- signature

In order to find out the reason, I regenerated the application's RSA2 public and private keys several times, but found that it had no effect. Finally, combined with online information, I discovered that

turned out to be the Alipay callback address notifyUrl cannot have '?' and add parameters after ?

##5.2, Alipay asynchronous notification It succeeded, but $_POST was empty

It also took a while to find this. When I started doing it, I followed Alipay's suggestion and used HTTS to request it. But in this way, the application background keeps notifying that there is no parameter content. Finally, I remembered that because our application uses HTTS two-way authentication, the parameters of Alipay's server callback are empty. Finally, change the callback address to HTTP method, and verify that it passes

If you encounter problems, first check Alipay's document description and the error code explanation provided by Alipay. If it doesn't work, use Baidu or Google, plus you continue to After testing and verification, the problem will definitely be solved in the end

At this point, the payment function of Alipay APP has been completed, and other APP refund, statement and other functions have not been continued. However, according to the official website documents of Alipay and the SDK provided by Alipay , it is only a matter of time before it is integrated into your own application.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

PDO preprocessing statement PDOStatement object


PHP full-featured non-deformation image cropping operation class and Introduction to usage


The above is the detailed content of How to integrate Alipay APP payment into PHP server. 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)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles