Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-paypal

> 后端框架
Open source

PayPal REST API client for Laravel and standalone PHP.

1.1K stars0 likes2 views
WebsiteGitHub

About

PayPal REST API client for Laravel and standalone PHP.

Laravel PayPal

A PayPal REST API package for Laravel, also usable as a standalone PHP client without any framework.

Supports: PHP 8.2–8.5 · Laravel 12 / 13

Disclaimer: This package is an independent community project and is not affiliated with, endorsed by, or supported by PayPal, Inc. "PayPal" is a registered trademark of PayPal, Inc. Use this package at your own risk; no warranty is provided beyond what the MIT license covers.


  • Version Compatibility
  • Moving to Orders v2 (v1 Payments API sunset Jan 2027)
  • Installation
  • Standalone Usage (without Laravel)
  • Configuration
  • Usage
  • PayPal Fastlane
  • Pay Upon Invoice (Buy Now, Pay Later — DE/AT)
  • Subscription Helpers
  • Billing Plans
    • BillingPlanBuilder
  • Catalog Products
  • Orders
  • Payments
  • Payouts
  • Referenced Payouts
  • Reference Transactions (Billing Agreements)
  • Invoices
  • Invoice Search
  • Invoice Templates
  • Subscriptions
  • Disputes
  • Dispute Actions
  • Trackers
  • Webhooks
  • Payment Method Tokens
  • Reporting
  • Identity
  • Partner Referrals
  • Payment Experience

Version Compatibility

Version PayPal API PayPal Deprecation PHP Laravel Maintained
v1.0 Classic NVP/SOAP (Express Checkout, Adaptive Payments) Deprecated since 2017, no firm sunset date 5.6+ 5.1+ ❌
v2.0 REST v1 Payments + v2 Orders /v1/payments sunset Jan 2027 7.2+ 6+ ❌
v3.0 REST v2 Orders + v2 Subscriptions Current 7.4+ 6–12 ❌
v3.1 REST v2 Orders + v2 Subscriptions Current 8.2+ 12–13 ✅

What's new in v3.1

  • PHP 8.2+ and Laravel 12 / 13 required
  • Standalone usage — no Laravel dependency required, pass credentials directly
  • PSR-18 HTTP client — swap Guzzle for any compliant client via setClient()
  • Configurable timeouts and retries — timeout, connect_timeout, max_retries in config
  • Exception-based error handling — opt in with withExceptions() for PayPalApiException
  • Local webhook verification — verifyWebHookLocally() with in-memory cert caching, no API roundtrip
  • PayPal Fastlane — generateClientToken() for one-click guest checkout
  • Payment Method Tokens — full Vault v3 API (setup tokens, permanent tokens, Apple Pay, Google Pay)
  • getCaptureIdFromOrder() — extract capture/transaction ID from order responses
  • Bug fixes — float precision, URL encoding, null guards, invoice date normalization
  • 100% test coverage with Pest v3/v4 and PHPStan level 7

Moving to Orders v2 (v1 Payments API sunset Jan 2027)

PayPal is sunsetting the v1 Payments REST API (/v1/payments/payment) in January 2027. If your integration uses the old create-payment → redirect → execute-payment flow, or the classic Billing Agreements API (/v1/billing-agreements/), you need to migrate before then.

This package already uses Orders v2 and Subscriptions v2 throughout. The migration notes below are for callers who built custom flows against the legacy endpoints or who were previously using the Express Checkout helpers from older versions.

Checkout: redirect-based payment flow

Old (v1 Payments — being sunset) New (Orders v2)
POST /v1/payments/payment → redirect → POST /v1/payments/payment/{id}/execute createOrder() → redirect → capturePaymentOrder()
…

Recurring billing: Billing Agreements → Subscriptions

Old (v1 Billing Agreements — being sunset) New (Subscriptions v2)
createBillingAgreementToken() → createBillingAgreement() addProductById() → addBillingPlanById() → setupSubscription()
php
// New subscriptions flow
$response = $provider->addProductById('PROD-XYAB12ABSB7868434')
    ->addBillingPlanById('P-5ML4271244454362WXNWU5NQ')
    ->setReturnAndCancelUrl('https://example.com/success', 'https://example.com/cancel')
    ->setupSubscription('John Doe', '[email protected]');

// Redirect the buyer to: $response['links'][href where rel === 'approve']

See the Subscription Helpers section for creating plans programmatically.


Installation

bash
composer require srmklive/paypal

Publish the config file:

bash
php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"

Standalone Usage (without Laravel)

The package has no hard dependency on Laravel — you can use it in any PHP project:

bash
composer require srmklive/paypal

Instantiate the client and pass your credentials directly via setApiCredentials(). No service provider or .env file needed:

…

The facade and php artisan vendor:publish are Laravel-only conveniences; everything else works identically.


Configuration

Add to your .env:

env
PAYPAL_MODE=sandbox
PAYPAL_SANDBOX_CLIENT_ID=
PAYPAL_SANDBOX_CLIENT_SECRET=
PAYPAL_LIVE_CLIENT_ID=
PAYPAL_LIVE_CLIENT_SECRET=
PAYPAL_LIVE_APP_ID=

# Optional — shown with defaults
PAYPAL_TIMEOUT=30
PAYPAL_CONNECT_TIMEOUT=10
PAYPAL_MAX_RETRIES=2

The published config/paypal.php:

…

Usage

Initialization

php
use Srmklive\PayPal\Services\PayPal as PayPalClient;

$provider = new PayPalClient;

// Or via facade
$provider = \PayPal::setProvider();

Custom HTTP Client (PSR-18)

setClient() accepts any PSR-18 ClientInterface, so you can swap out Guzzle for Symfony HttpClient, Buzz, or any other compliant implementation:

php
use Symfony\Component\HttpClient\Psr18Client;

$provider->setClient(new Psr18Client());

Pass null (or call with no argument) to restore the default Guzzle client with the configured timeout and retry middleware.

Note: The built-in retry middleware runs only on the default Guzzle client. When you inject a custom client, handle retries in that client's own middleware stack.

Retry Behaviour

The default Guzzle client automatically retries failed requests up to max_retries times (default: 2) for:

  • 5xx server errors — PayPal-side failures (500, 502, 503, …)
  • 429 Too Many Requests — rate-limit responses; the Retry-After header is read and honoured when present
  • Network/connection errors — DNS failures, connection refused, etc.

The delay between attempts uses exponential backoff (500 ms → 1 s → 2 s → 4 s, capped at 8 s) unless a Retry-After header overrides it. Set max_retries to 0 to disable retries entirely.


Override Configuration at Runtime

php
$provider->setApiCredentials([
    'mode' => 'live',
    'live' => [
        'client_id'     => 'PAYPAL_LIVE_CLIENT_ID',
        'client_secret' => 'PAYPAL_LIVE_CLIENT_SECRET',
        'app_id'        => 'PAYPAL_LIVE_APP_ID',
    ],
    'payment_action' => 'Sale',
    'currency'       => 'USD',
    'notify_url'     => 'https://your-site.com/paypal/notify',
    'locale'         => 'en_US',
    'validate_ssl'   => true,
]);

Get Access Token

Call this before any API method:

php
$provider->getAccessToken();

Set Currency

php
$provider->setCurrency('EUR');

Partner Attribution ID (BN code)

PayPal uses the PayPal-Partner-Attribution-Id header to attribute transactions to a partner or platform. Set it once after initialisation — it persists for the lifetime of the provider instance:

php
$provider->setPartnerAttributionId('YourPlatform_SP');

All subsequent API calls will include the header automatically.

Error Handling

By default, API errors are returned as an array with an error key:

php
$response = $provider->showOrderDetails('bad-id');

if (isset($response['error'])) {
    // $response['error'] is the decoded PayPal error object or a plain string
}

Opt in to exceptions with withExceptions(). All API errors will then throw PayPalApiException instead:

php
use Srmklive\PayPal\Exceptions\PayPalApiException;

$provider->withExceptions();

try {
    $order = $provider->showOrderDetails('bad-id');
} catch (PayPalApiException $e) {
    $e->getHttpStatus();    // HTTP status code: 400, 401, 404, 422, 500, etc. (0 for network errors)
    $e->getMessage();       // JSON-encoded error string
    $e->getPayPalError();   // decoded array (e.g. ['name' => 'RESOURCE_NOT_FOUND', ...])
                            // or a plain string for non-JSON errors
}

Call withoutExceptions() to revert to silent mode. Both methods are fluent.


PayPal Fastlane

PayPal Fastlane is a one-click guest checkout experience that pre-fills shipping and payment details for returning PayPal customers, typically delivering ~50% higher conversion on guest checkout flows.

Server role: generate a client token and handle Orders v2 create/capture. The Fastlane UI is rendered entirely by the PayPal JS SDK on the client.

1. Generate a client token (server-side)

php
$provider->getAccessToken();

$result = $provider->generateClientToken();
// $result['client_token'] — pass this to your frontend

2. Initialise Fastlane (client-side)

xml

3. Create & capture the order (server-side)

php
// Create
$order = $provider->createOrder([
    'intent' => 'CAPTURE',
    'purchase_units' => [
        ['amount' => ['currency_code' => 'USD', 'value' => '49.99']],
    ],
    'payment_source' => [
        'card' => [
            'single_use_token' => $singleUseToken, // from Fastlane.FastlaneCardComponent
        ],
    ],
]);

// Capture
$capture = $provider->capturePaymentOrder($order['id']);

// Extract the transaction/capture ID
$captureId = $provider->getCaptureIdFromOrder($capture);

Pay Upon Invoice (Buy Now, Pay Later — DE/AT)

Pay Upon Invoice (Rechnungskauf) lets buyers in Germany and Austria pay after receiving goods. PayPal collects the payment and the merchant is paid upfront.

Requirements: DE/AT merchant account, buyer name, email, date of birth, phone number, and billing address.

…

Subscription Helpers

A fluent helper API for creating subscriptions without manually building plan/product payloads.

addPlanTrialPricing() and setReturnAndCancelUrl() are optional. Return/cancel URLs require real domains (not localhost).

Daily Subscription

php
$response = $provider->addProduct('Demo Product', 'Demo Product', 'SERVICE', 'SOFTWARE')
    ->addPlanTrialPricing('DAY', 7)
    ->addDailyPlan('Demo Plan', 'Demo Plan', 1.50)
    ->setReturnAndCancelUrl('https://example.com/paypal-success', 'https://example.com/paypal-cancel')
    ->setupSubscription('John Doe', '[email protected]', '2025-01-01');

Weekly / Monthly / Annual Subscription

…

Custom Interval

php
$response = $provider->addProduct('Demo Product', 'Demo Product', 'SERVICE', 'SOFTWARE')
    ->addCustomPlan('Demo Plan', 'Demo Plan', 150, 'MONTH', 3)
    ->setReturnAndCancelUrl('https://example.com/paypal-success', 'https://example.com/paypal-cancel')
    ->setupSubscription('John Doe', '[email protected]', '2025-01-01');

Use Existing Product & Billing Plan

php
$response = $provider->addProductById('PROD-XYAB12ABSB7868434')
    ->addBillingPlanById('P-5ML4271244454362WXNWU5NQ')
    ->setReturnAndCancelUrl('https://e

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPipnlaravel-paypallaravel-pluginpaypal

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架