Mark Ku's Blog

Context

According to statistics, 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 insurance service to mitigate the operational risks of online e-commerce fraud. Riskified fraud prevention process with approval, decline, and chargeback guaran

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

API Endpoint

Sandbox. https://api-m.sandbox.paypal.com
Live. https://api-m.paypal.com

Getting API Keys

Link Get API key

The new version is quite convenient, allowing debugging via Event Logs

debug-tools
debug-tools

Frontend errors can also be debugged through the browser

console-debug.png
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
Integration diagram

Starting the Integration

First, you can refer to the examples in the official Integration builder. They are actually quite well-written, and you can basically complete the integration by following them. Integration-builder-1Integration-builder-2Integration-builder-3

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
PayPal credit card

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

Author

Mark Ku

擁有 10+ 年經驗的資深軟體工程師,現為 AI 應用 Builder,專注於大型平台架構與簡化複雜系統設計,從電商系統到訂閱與收費平台,結合 AI Agent、AI 整合與自動化開發,打造高效率且可持續演進的產品技術基礎。Read More

Found this useful?

The author's free tools, daily podcasts and newsletter are all here.

Mark Ku · This article is licensed under CC BY 4.0. Credit the author and link back to the original when reusing it.

Comments

Subscribe to Newsletter

Subscribe to get new posts delivered instantly — never miss a tech share.

By submitting, you agree to receive emails. You can anytime.

Popular Posts

View all
Mark Ku
··602

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution
Mark Ku
··490

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.
Mark Ku
··333

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki
Mark Ku
··264

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning
Mark Ku
··221

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1
Mark Ku
··215

Setting Up Samba on Ubuntu to Share Folders with Windows 11

Setting Up Samba on Ubuntu to Share Folders with Windows 11