Home Backend Development PHP Tutorial Detailed explanation of how to connect PHP to PayPal payment

Detailed explanation of how to connect PHP to PayPal payment

Oct 30, 2020 pm 03:05 PM
paypal php

Recommended: "PHP Video Tutorial"

##Environment preparation

    Register paypal account
  • Register paypal developer account
  • Create paypal sandbox test account
  • Create paypal application
  • Download PHP SDK
  • Realize payment
  • Realize payment success callback
  • Realize refund
  • More API code templates

Register paypal account

    www.paypal.com Register merchant account
  • Select, "Create merchant user", fill in the information as required, and go to your email to activate after registration

Register a paypal developer account

    developer.paypal.com Use the account registered in the previous step to log in
  • Click Accounts in the left navigation bar and create two sandbox accounts, one personal account (personal) for payment and one merchant account (business) for collection. The system has created two by default. You can choose to create them yourself. Easy to remember; after creating an account, remember to add a balance to the current account for subsequent testing.

  • Detailed explanation of how to connect PHP to PayPal payment
  • Use the test account you just created to log in to the sandbox test site and view the amount and transaction information www.sandbox.paypal.com

##Create Sandbox Application APP

A Default Application is created by default for the account. Click to view to obtain the ClientId and Secret; save them and use them in subsequent interface calls; ( Please re-create a Live application when going online)

  • Detailed explanation of how to connect PHP to PayPal payment

Download SDK

I use it laravel framework, use composer to download the paypal package
  • composer require paypal/rest-api-sdk-php

implementation Payment

    The following is the code snippet to generate payment, the pseudo code
  • function createPayPal(){
          $shippingPrice = 2;
          $taxPrice = 0;
          $subTotal = 26;
          $item1 = new PayPal\Api\Item();
          $item1->setName("产品2")->setCurrency("USD")->setQuantity(1)->setPrice(10);
          $item2 = new PayPal\Api\Item();
          $item2->setName("产品1")->setCurrency("USD")->setQuantity(2)->setPrice(8);
    
          $itemList = new PayPal\Api\ItemList();
          $itemList->addItems([$item1,$item2]);
    
          // Set payment details
          $details = new PayPal\Api\Details();
          $details->setShipping($shippingPrice)->setTax($taxPrice)->setSubtotal($subTotal);
    
          // Set payment amount
          //注意,此处的subtotal,必须是产品数*产品价格,所有值必须是正确的,否则会报错
          $total = $shippingPrice + $subTotal + $taxPrice;
          $amount = new PayPal\Api\Amount();
          $amount->setCurrency("USD")->setTotal($total)->setDetails($details);
    
          // Set transaction object
          $transaction = new PayPal\Api\Transaction();
          $transaction->setAmount($amount)->setItemList($itemList)->setDescription("这是交易描述")
              ->setInvoiceNumber(uniqid());//setInvoiceNumber为支付唯一标识符,在使用时建议改成订单号
    
          $payer = new PayPal\Api\Payer();
          $payer->setPaymentMethod('paypal');//["credit_card", "paypal"]
          $redirectUrls = new PayPal\Api\RedirectUrls();
          $redirectUrl = "http://test.com/redirect/success";//支付成功跳转的回调
          $cancelUrl = "http://test.com/redirect/cancel";//取消支付的回调
          $redirectUrls->setReturnUrl($redirectUrl)->setCancelUrl($cancelUrl);
    
          // Create the full payment object
          $payment = new PayPal\Api\Payment();
          $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->addTransaction($transaction);
    
          try {
              $clientId = "xxxxxx";//上面应用的clientId和secret
              $secret = "XXXXXX";
              $oAuth = new \PayPal\Auth\OAuthTokenCredential($clientId, $secret);
              $apiContext =  new \PayPal\Rest\ApiContext($oAuth);
              if(env('APP_DEBUG') === false ){
                  $apiContext->setConfig(['mode' => 'live']);//设置线上环境,默认是sandbox
              }
              $payment->create($apiContext);
              $approvalUrl = $payment->getApprovalLink();
              dd($approvalUrl);//这个是请求支付的链接,在浏览器中请求此链接就会跳转到支付页面
          } catch (\Exception $e) {
              dd($e->getMessage());//错误提示
          }
      }
    Copy after login

    Detailed explanation of how to connect PHP to PayPal payment

  • The following is Callback code snippet for successful payment, pseudo code
  • function payRedirect(Request $request)
      {
          $paymentID = $request->get('paymentId');
          $payerId = $request->get('PayerID');
    
          $clientId = "xxxxxx";//上面应用的clientId和secret
          $secret = "XXXXXX";
          $oAuth = new \PayPal\Auth\OAuthTokenCredential($clientId, $secret);
          $apiContext =  new \PayPal\Rest\ApiContext($oAuth);       
          if(env('APP_DEBUG') === false ){
              $apiContext->setConfig(['mode' => 'live']);//设置线上环境,默认是sandbox
          }
          $payment = \PayPal\Api\Payment::get($paymentID, $apiContext);
    
          $execute = new \PayPal\Api\PaymentExecution();
          $execute->setPayerId($payerId);
    
          try{
              $payment = $payment->execute($execute, $apiContext);//执行,从paypal获取支付结果
              $paymentState = $payment->getState();//Possible values: created, approved, failed.
              $invoiceNum = $payment->getTransactions()[0]->getInvoiceNumber();
              $payNum = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getId();//这是支付的流水单号,必须保存,在退款时会使用到
              $total = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getAmount()->getTotal();//支付总金额
              $transactionState = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getState();//Possible values: completed, partially_refunded, pending, refunded, denied.
    
              if($paymentState == 'approved' && $transactionState == 'completed'){
                  //处理成功的逻辑,例如:判断支付金额与订单金额,更新订单状态等
                  return "success";//返回成功标识
              }else{
                  //paypal回调错误,paypal状态不正确
                  return "error";//返回错误标识
              }
          }catch(\Exception $e){
              dd($e->getMessage());
          }
      }
    Copy after login

Refund

    Refund You must have a slip number for successful payment
  • One slip number can be used for multiple refunds
  • After the refund is successful, the account number It is not reflected in the transaction record. During the test, please log in to the test account and record the changes in the balance yourself to determine whether the refund is successful.
  • The merchant account will reduce the balance and increase the handling fee (processing fee) (The fee was overcharged for previous payments), the user account will increase the balance
  • function refundOrder()
      {
          try{
              $refundRequest = new \PayPal\Api\RefundRequest();
              $amount = new \PayPal\Api\Amount();
              $amount->setCurrency("USD")->setTotal(10);//退总金额
              $refundRequest->setAmount($amount);
              $refundRequest->setDescription("退款测试");
              $sale = new \PayPal\Api\Sale();
              $sale->setId("XXXXXXXXX");//支付单号,支付成功时保存的支付流水单号
              $clientId = "xxxxxx";//上面应用的clientId和secret
              $secret = "XXXXXX";
              $oAuth = new \PayPal\Auth\OAuthTokenCredential($clientId, $secret);
              $apiContext =  new \PayPal\Rest\ApiContext($oAuth);
              if(env('APP_DEBUG') === false ){
                  $apiContext->setConfig(['mode' => 'live']);//设置线上环境,默认是sandbox
              }
              $detailedRefund = $sale->refundSale($refundRequest, $apiContext);//调接口
              $refundState = $detailedRefund->getState();//Possible values: pending, completed, cancelled, failed.
    
              //var_dump($refundedSale);
              if($refundState == 'completed'){
                  //退款成功,返回
              }else{
                  dd('paypal 退款失败, 状态不正确');
              }
          }catch (\Exception $exception){
              dd($exception->getMessage());//发生异常
          }
      }
    Copy after login

    More interface code examples

  • http://paypal.github.io/PayPal-PHP-SDK/sample/

The above is the detailed content of Detailed explanation of how to connect PHP to PayPal payment. 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

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

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

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