---
title: "Notes on Integrating PayPal"
description: "Complete PayPal REST API v2 integration notes, covering frontend React SDK integration, backend C# for creating orders, authorization, and capture flows, and an explanation of advanced Braintree payment features."
canonical_url: "https://blog.markkulab.net/en/post/integrate-paypal-checkout"
author: "Mark Ku"
author_url: "https://blog.markkulab.net/en/author/mark-ku"
site: "Mark Ku's Tech Notes"
date_published: "2024-03-02 01:01:35 +0800"
category: "Payment"
tags: ["paypal", "payment", "checkout", "react", "csharp", "integration", "braintree"]
language: "en"
license: "CC BY 4.0"
license_url: "https://creativecommons.org/licenses/by/4.0/"
attribution: "when reusing or quoting, credit the author and link back to the original"
---

# Notes on Integrating PayPal

## Context
According to [statistics](https://www.rapyd.net/blog/ecommerce-and-payment-trends-germany/), PayPal has over 22% market share in Germany and is also quite popular throughout the EU. However, due to severe e-commerce fraud in the past, the client decided to disable PayPal. With the rebuild of the German website, we are reintegrating PayPal, pairing it with the [Riskified](https://www.riskified.com/) insurance service to mitigate the operational risks of online e-commerce fraud.
![Riskified fraud prevention process with approval, decline, and chargeback guaran](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/riskified.png)

## PayPal Integration
PayPal's API seems to have been upgraded, and the official recommendation is to integrate using the new REST API v2.

### Relevant Documentation
* [Frontend Integration Documentation](https://developer.paypal.com/docs/checkout/standard/integrate/#link-integratefrontend)
* [Get API Access Token](https://developer.paypal.com/api/rest/authentication/)
* [API Request Information](https://developer.paypal.com/api/rest/requests/)
* [APIs for Creating Orders, Authorization, and Capture](https://developer.paypal.com/docs/api/orders/v2/#orders_create)

### API Endpoint
```
Sandbox. https://api-m.sandbox.paypal.com
Live. https://api-m.paypal.com
```
### Getting API Keys
[Link](https://developer.paypal.com/dashboard/applications/sandbox)
![Get API key](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/get-api-key.png)

## The new version is quite convenient, allowing [debugging](https://developer.paypal.com/dashboard/dashboard/sandbox) via Event Logs

![debug-tools](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/debug-tools.png)

## Frontend errors can also be debugged through the browser
![console-debug.png](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/console-debug.png)
## Advanced Payment Features
The advanced mode adds Venmo (social payments), Debit or Credit Card, and PayPal Pay Later (buy now, pay later), but it requires applying for PayPal's Braintree payment gateway.

P.S. PayPal's Braintree is a comprehensive payment solution, similar to a payment gateway. It primarily helps merchants accept, process, and distribute payments, solving multiple issues related to accepting online payments by providing a secure, flexible, and easy-to-integrate platform.

## Integration Flowchart
![Integration diagram](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/integration-diagram.png)

## Starting the Integration
First, you can refer to the examples in the official [Integration builder](https://developer.paypal.com/integration-builder/). They are actually quite well-written, and you can basically complete the integration by following them.
![Integration-builder-1](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/integration-builder-1.png)![Integration-builder-2](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/integration-builder-2.png)![Integration-builder-3](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/integration-builder-3.png)


### Frontend Example (Next.js App Router)
#### Install the SDK
```
npm install @paypal/react-paypal-js --save
```

### Writing the Frontend Integration Code

```
'use client'; // next js client component
import { PaymentOptions } from '@/const/payment/payment-option';
import { useCaptureMutation, useGetConfigQuery, useProcessMutation } from '@/redux/api/test-payment-apiSlice';
import { IGernalPaymentParams } from '@/typing/cart';
import { PayPalButtons, PayPalScriptProvider } from '@paypal/react-paypal-js';
import { v4 as uuidv4 } from 'uuid';

export default function TestPaypal() {
    const { data: paymentInitOption, isLoading: isPaymentInitLoading } = useGetConfigQuery(); // rtk query 取得 payal sdk 前端初始化的參數

    const [Process] = useProcessMutation(); // rtk query 用來呼叫建立建立授權訂單的api

    const [Capture] = useCaptureMutation(); // rtk query 用來呼叫提取信用請款的api

    const gernalPaymentParams: IGernalPaymentParams = {
        paymentTypeCode: PaymentOptions[PaymentOptions.Paypal],
        orderNo: uuidv4(),        
    } as IGernalPaymentParams;

    const createOrder = (): Promise<string> => {
        return Process(gernalPaymentParams)
            .unwrap()
            .then((res: ApiResponse<IGeneralPaymentResult>) => {
                if (res.isSuccess) {
                    const orderId = res.data.paymentReturnValue;

                    return orderId;
                }
                return '';
            });
    };

    const onApprove = (data: any) => {
        return Capture(gernalPaymentParams)
            .unwrap()
            .then((res: ApiResponse<IGeneralPaymentResult>) => {
                if (res.isSuccess) {
                    debugger;
                    paypalOrderId.current = res.data.paymentReturnValue;
                    alert('Payment success');
                }
            });
    };

    return (
        <>
            {!isPaymentInitLoading && (
                <PayPalScriptProvider options={paymentInitOption}>
                    <PayPalButtons
                        createOrder={createOrder}
                        onApprove={onApprove}
                        style={{ layout: 'horizontal', color: 'white', tagline: true }}
                    />
                </PayPalScriptProvider>
            )}
        </>
    );
}
```

## Backend Example (C#)
### Define Backend Environment Settings - Appsetting.json
```
  "Payment": {
    "PaymentOptions": [
      {
        "PaymentName": "Paypal",
        "IsSandbox": true,
        "ClientId": "Your paypal clientId",
        "Secret": "Your paypal secret",             
        "EndPoint": "https://api-m.sandbox.paypal.com" // sandbox		 
      }]
  }
```

### Construct SDK Initialization Parameters for the Frontend from Backend Environment Variables
```
     public async Task<Result<Dictionary<string, string>>> GetConfig()
     {
        var dic = new Dictionary<string, string>();
        dic.Add("client-id", GeneralPaymentConfig.ClientId);
        dic.Add("currency", HardCodeKey.BasedCurrency);
		// dic.Add("disable-funding", "credit,card"); // 關閉信用卡及借記卡

        var result = new Result<Dictionary<string, string>> { IsSuccess = true, Message = "", Data = dic };
        return result;
     }
```
### PayPal API Request Authorization - PayPal supports two token types; here we use <client_id:secret> as the login token

According to the official documentation, we can either call the API to get an Access-Token or use `client_id:secret` as the token to call the PayPal API.

```
// To make REST API calls, include the bearer token in this header with the Bearer authentication scheme. The value is Bearer <Access-Token> or Basic <client_id:secret> 

public async Task<string> Authorization()
   {
      return Convert.ToBase64String(Encoding.ASCII.GetBytes($"{GeneralPaymentConfig.ClientId}:{GeneralPaymentConfig.Secret}")); ;
}
```
### Next, we implement /api/orders to create and authorize an order

```
public async Task<Result<GeneralPaymentResult>> ProcessAsync(GernalPaymentParameter paymentParameter)
{
   var result = new Result<GeneralPaymentResult>
   {
      IsSuccess = false,
      Message = "",
      Data = new GeneralPaymentResult
      {
         PaymentReturnType = PaymentReturnType.OrderId,
      }
   };

   try
   {
      var headers = new Dictionary<string, string>
    {
      { "Authorization", $"Basic  {Authorization()}" },
      { "PayPal-Request-Id",  HttpContext.Current.TraceIdentifier},
    };

      var paymentCapture = new PaymentCapture
      {
         Intent = "CAPTURE",
         PurchaseUnits = new List<PurchaseUnit>
   {
   new PurchaseUnit
   {
      ReferenceId = paymentParameter.OrderNo,
      Amount = new Model.ViewModels.Payment.Amount
      {
          CurrencyCode = "EUR",
          Value = "1.00"
      },
      Shipping = new PaypalShipping
      {
          Address =  new PaypalAddress
          {
              AddressLine1 = "2211 N First Street",
              AddressLine2 = "Building 17",
              AdminArea2 = "San Jose",
              AdminArea1 = "CA",
              PostalCode = "95131",
              CountryCode = "US"
          }
      }
      }
      },
         PaymentSource = new PaymentSource
         {
            PayPal = new PayPal
            {
               ExperienceContext = new ExperienceContext
               {
                  PaymentMethodPreference = "IMMEDIATE_PAYMENT_REQUIRED",
                  BrandName = "EXAMPLE INC",
                  Locale = "en-US",
                  LandingPage = "LOGIN",
                  ShippingPreference = "SET_PROVIDED_ADDRESS",
                  UserAction = "PAY_NOW",
                  ReturnUrl = "https://example.com/returnUrl",
                  CancelUrl = "https://example.com/cancelUrl"
               }
            }
         }
      };

      // Use Newtonsoft.Json to serialize the object to JSON (for demonstration)
      string body = JsonConvert.SerializeObject(paymentCapture, Formatting.Indented);

      var orderRsult = await HttpHelper.PostAsync<PaypalOrderResponse>(GeneralPaymentConfig.EndPoint + "/v2/checkout/orders", body, headers);
      result.Data.PaymentReturnValue = orderRsult.Id;
      result.Success();
   }
   catch (Exception ex)
   {
      result.Fail(ex.Message);
      NLogUtil.WriteSEQLog($"[Paypal][ProcessAsync]Error:{ex.Message},StackTrace:{ex.StackTrace}", NLog.LogLevel.Error);
   }

   return result;
}
```

### Finally, we implement /api/orders for payment capture
```
public virtual async Task<Result<GeneralPaymentResult>> CaptureAsync(GernalPaymentParameter paymentParameter)
{
   // Sandbox have some issue.cannot use capture
   var result = new Result<GeneralPaymentResult>
   {
      IsSuccess = false,
      Message = "Capture fail!",
      Data = new GeneralPaymentResult
      {
      }
   };

   try
   {
      var url = GeneralPaymentConfig.EndPoint + $"/v2/checkout/orders/{paymentParameter.PaymentGatewayOrderId}/capture";
      var requestBody = "";

      var headers = new Dictionary<string, string>
    {
      { "Authorization", $"Basic  {Authorization()}" },
      { "PayPal-Request-Id",  HttpContext.Current.TraceIdentifier},
    };

      var response = await HttpHelper.PostAsync<PaypalOrderResponse>(url, requestBody, headers);

      if (response.Status == "COMPLETED")
      {
         result.IsSuccess = true;
         result.Message = "Capture success";
      }

   }
   catch (Exception ex)
   {
      result.Fail(ex.Message);
      NLogUtil.WriteSEQLog($"[Paypal][CaptureAsync]Error:{ex.Message},StackTrace:{ex.StackTrace}", NLog.LogLevel.Error);
   }

   return result;
}
```
## Use a Credit Card with PayPal Without Logging In
![PayPal credit card](https://blog.markkulab.net/content/markku/posts/integrate-paypal-checkout/images/paypal-credit-card.png)

## Addendum - Pay Upon Invoice
An interesting feature: a third-party payment method from PayPal where goods are shipped before payment is made. PayPal guarantees that the merchant will receive the money.

### References
* [US E-commerce Practice Notes - Credit Card Authorization and Capture](https://blog.markkulab.net/usa-ecommerce-note-credit-card-authorize-and-capture/)
* [PayPal Express Checkout Integration Guide](https://www.paypalobjects.com/webstatic/lvm/tw/zh/using-paypal/integration-guide.pdf)
* [Integrate Apple Pay with JS SDK for direct merchants](https://developer.paypal.com/docs/checkout/apm/apple-pay/#link-howitworks)
* [Integrate Google Pay with JS SDK for direct merchants](https://developer.paypal.com/docs/checkout/apm/google-pay/)

---

## About this article and its author

Originally published on [Mark Ku's Tech Notes](https://blog.markkulab.net/en/post/integrate-paypal-checkout)

License: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — when reusing or quoting, credit the author and link back to the original

### About the author

**[Mark Ku](https://blog.markkulab.net/en/author/mark-ku)** — Software Solution Provider

- 10+ years senior software engineer, now an AI Builder
- Focused on large-platform architecture — North-American e-commerce, AI SaaS subscription billing
- Combining AI Agents and automation to build evolvable product foundations

### Free tools built by the author

All of these are free to use:

- [Free PDF Sign Tool](https://blog.markkulab.net/en/tools/pdf-sign): Online PDF sign tool — draw, type, or upload a signature, then drag, resize, and download. Everything runs in your browser; nothing is uploaded.
- [VS Code Refactory](https://blog.markkulab.net/en/tools/refactory): Refactory is a VS Code refactoring extension: 34 actions plus a 37-rule code-smell inspection layer with a Code Health dashboard, across 18 languages, backed by 534 tests. It learns your repo's conventions: where interfaces live, where DI is registered, whether 'use client' belongs. It ranks files by git churn × complexity so you know what to fix first, and hands any smell to the Claude Code already on your machine. Free to use, and your source never leaves your computer.
- [DB-Kit Database Manager](https://blog.markkulab.net/en/tools/db-kit): DB-Kit is a lightweight, cross-platform database manager built with Tauri + Rust + React. Manage MySQL, MariaDB, PostgreSQL, SQL Server, Oracle, SQLite, MongoDB, Redis, Kafka, Elasticsearch and RabbitMQ from one consistent interface: passwords encrypted in the OS keychain, SSH tunnels, full CRUD, a visual query builder, stacked multi-statement result sets, cross-connection data transfer and compare/sync, Excel / CSV import & export, visualized execution plans, ER diagrams, scheduled backups, SQL stress testing with p50–p99 latency percentiles, a 15-rule SQL review engine, Kafka message browsing with monitoring & alerts, a bilingual UI (Traditional Chinese / English), a built-in AI assistant (natural-language SQL, AI review and tuning advice) and the dbk CLI. Free and open source (MIT), with installers for Windows, macOS and Linux.
- [VS Code Super Mermaid](https://blog.markkulab.net/en/tools/super-mermaid): Super Mermaid is a VS Code extension for beautiful Mermaid diagrams out of the box: auto-colored live preview, mouse pan & zoom, high-res PNG / SVG export, 21 templates and multiple themes. Free and open source (MIT).
- [React Super Mermaid](https://blog.markkulab.net/en/tools/react-super-mermaid): react-super-mermaid is an open-source React component library: render beautiful Mermaid diagrams with a single <MermaidViewer>, with built-in colorful / sketch themes, pan & zoom, in-diagram search, and high-res SVG / PNG export. Lightweight, SSR-safe, fully typed. Free and open source (MIT).
- [Jira / Confluence Super Mermaid](https://blog.markkulab.net/en/tools/jira-super-mermaid): An Atlassian Forge app: write Mermaid syntax directly inside a Jira issue or a Confluence page and get flowcharts, sequence diagrams, state machines and Gantt charts. 11 diagram types, SVG / PNG export, light and dark themes, full CJK support. Runs on Atlassian: your diagrams live in your own site and the app calls no third-party service. Free, coming soon to the Atlassian Marketplace.
- [Mermaid Live Preview](https://blog.markkulab.net/en/tools/mermaid-preview): Write Mermaid in your browser, see it render instantly, and share the whole diagram as a single link. No sign-up, nothing uploaded to a server, and mermaid.live share links work as-is.
- [React Intl Phone Number](https://blog.markkulab.net/en/tools/react-intl-phone-number): react-intl-phone-number is an open-source React component: framework-agnostic and antd-free, with E.164 in/out, a searchable flag / country-code dropdown, configurable validation levels (strict / mobile-strict / loose), themeable CSS, and i18n — phone logic powered by google-libphonenumber. Lightweight and fully typed. Free and open source (MIT).
- [Uptime Kuma Cluster](https://blog.markkulab.net/en/tools/uptime-kuma-cluster): Turn single-node Uptime Kuma into a highly available cluster: OpenResty + Lua smart load balancing, shared MariaDB state, health checks and automatic failover, plus cluster-management REST APIs. One Docker Compose command to start. Free and open source (MIT).
- [Special Education](https://blog.markkulab.net/en/education): Learning materials crafted for special education students

### Daily podcasts

- [Mark's Tech Insights — Daily AI News](https://blog.markkulab.net/en/category/tech-news): Daily curated AI and tech trends. Catch the latest developments via audio summaries — covering AI applications, software architecture, DevOps, and engineering practice. — RSS: https://blog.markkulab.net/feed.xml
- [AI股市蝦聊](https://blog.markkulab.net/en/category/ai-stock-chat): Every trading day, an AI-analyzed take on the Taiwan stock market, delivered as a two-host conversation covering the session and the next-day outlook. — RSS: https://blog.markkulab.net/ai-stock-chat/feed.xml
- [開源好物週報](https://blog.markkulab.net/en/category/open-source-weekly): A weekly two-host pick of free open-source tools surfaced from real Hacker News, GitHub, and Reddit buzz — what pain they solve and the fastest way to get started. — RSS: https://blog.markkulab.net/open-source-weekly/feed.xml

### Newsletter

[Subscribe to the newsletter](https://blog.markkulab.net/en/subscribe) — Be the first to know about new posts. No spam, unsubscribe anytime.
