search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP docking with PayPal payment

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 Log in using the account registered in the previous step
  • Click Accounts on the left navigation bar to create two sandbox accounts and a personal account (personal) for payment , a merchant account (business) is used to collect payments. The system has created two by default. You can choose to create one by yourself to facilitate memory; after creating the account, remember to add a balance to the current account for subsequent testing.
    Detailed explanation of PHP docking with 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 PHP docking with 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());//错误提示
          }
      }

    Detailed explanation of PHP docking with 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());
          }
      }

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 balance of the user account will increase

    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());//发生异常
          }
      }
  • http://paypal. github.io/PayPal-PHP-SDK/sample/

Recommended: "
PHP Video Tutorial"

The above is the detailed content of Detailed explanation of PHP docking with PayPal payment. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

Video Face Swap

Video Face Swap

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

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool