### Install Dodo Payments PHP Library Source: https://github.com/dodopayments/dodopayments-php/blob/main/README.md Use Composer to install the Dodo Payments PHP client library. Ensure you are using PHP 8.1.0 or higher. ```bash composer require "dodopayments/client 6.7.2" ``` -------------------------------- ### Retrieve Customer by ID Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Retrieves a customer's details using their unique `customer_id`. The email address is printed as an example. ```php // Retrieve by ID $customer = $client->customers->retrieve('cus_abc123'); echo $customer->email; ``` -------------------------------- ### List Supported Countries Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Utility endpoint to get all supported country codes. Useful for validation or dropdown population. ```php misc->listSupportedCountries(); foreach ($countries as $code) { echo $code . PHP_EOL; // "US", "GB", "DE", "IN", … } ``` -------------------------------- ### Retrieve Line Items for a Payment Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Get the line items associated with a specific payment. This provides details about the products and quantities included in the payment. ```php // Get line items for a payment $lineItems = $client->payments->retrieveLineItems('pay_abc123'); foreach ($lineItems->items as $item) { echo $item->product_id . ' × ' . $item->quantity . PHP_EOL; } ``` -------------------------------- ### Create Subscription with Trial Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Creates a new subscription with a specified trial period. Ensure `productID` and `customer` are valid. ```php subscriptions->create( billing: BillingAddress::with(country: 'US', state: 'NY', city: 'NYC', street: '1 Broad St', zipcode: '10004'), customer: AttachExistingCustomer::with(customerId: 'cus_abc123'), productID: 'prod_monthly_plan', quantity: 1, trialPeriodDays: 14, metadata: ['plan' => 'pro'], ); echo $sub->subscription_id; ``` -------------------------------- ### Create and Manage Addons Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Manage optional add-on products that can be attached to subscriptions. Includes creation, retrieval, update, and listing. ```php addons->create( currency: 'USD', name: 'Extra Storage (50 GB)', price: 499, // $4.99 in cents taxCategory: 'digital_products', description: 'Add 50 GB of cloud storage to your subscription.', ); echo $addon->addon_id; // Retrieve and update an addon $addon = $client->addons->retrieve('addon_abc123'); $client->addons->update('addon_abc123', price: 599, name: 'Extra Storage (100 GB)'); // List addons $page = $client->addons->list(pageSize: 50); foreach ($page->pagingEachItem() as $a) { echo $a->addon_id . ' — ' . $a->name . ' — ' . $a->price . PHP_EOL; } // Get an image upload URL for an addon $imageInfo = $client->addons->updateImages('addon_abc123'); echo $imageInfo->upload_url; ``` -------------------------------- ### Initialize Dodo Payments Client Source: https://github.com/dodopayments/dodopayments-php/blob/main/README.md Instantiate the Dodo Payments client using your API key and specify the environment. Named parameters are used for optional arguments. ```php checkoutSessions->create( productCart: [['productID' => 'product_id', 'quantity' => 0]] ); var_dump($checkoutSessionResponse->session_id); ``` -------------------------------- ### Create Full Checkout Session with Options Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Create a comprehensive checkout session including billing address, discounts, custom fields, and return URLs. Set `shortLink` to true for a shorter URL. ```php checkoutSessions->create( productCart: [['productID' => 'prod_abc123', 'quantity' => 1]], billingAddress: CheckoutSessionBillingAddress::with( country: 'US', state: 'CA', city: 'San Francisco', street: '123 Main St', zipcode: '94105', ), customer: ['email' => 'alice@example.com', 'name' => 'Alice'], discountCodes: ['SAVE20'], returnURL: 'https://myapp.com/success', cancelURL: 'https://myapp.com/cancel', metadata: ['order_ref' => 'ORD-9981'], shortLink: true, requestOptions: ['maxRetries' => 1], ); echo $session->url; ``` -------------------------------- ### Access Raw PSR-7 Response and Call Undocumented Endpoint Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use the `raw` sub-service to get the raw PSR-7 response for any API call. You can also make requests to undocumented endpoints using the `request` method, specifying method, path, query, headers, and body. ```php payments->raw->retrieve('pay_abc123'); echo $rawResponse->getStatusCode(); // 200 echo $rawResponse->getBody(); // raw JSON string $parsed = $rawResponse->parse(); // typed Payment object // Call an undocumented endpoint $response = $client->request( method: 'post', path: '/undocumented/endpoint', query: ['filter' => 'active'], headers: ['X-Custom-Header' => 'value'], body: ['key' => 'value'], ); ``` -------------------------------- ### Initialize Dodo Payments Client Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Instantiate the `Client` class with your Bearer token. For sandbox or test environments, specify the 'test_mode' environment and optionally provide a webhook key. You can also configure retry attempts. ```php 3], ); ``` -------------------------------- ### Create and Manage Products with DodoPayments PHP SDK Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this to create one-time, recurring, or usage-based products. It also covers retrieving, updating, archiving, and listing products, as well as generating image upload URLs and short links. ```php products->create( name: 'Premium Template Pack', price: OneTimePrice::with( currency: 'USD', price: 2999, // $29.99 ), taxCategory: 'digital_products', description: 'A collection of 50 premium design templates.', ); echo $product->product_id; // Recurring (subscription) product $product = $client->products->create( name: 'Pro Plan — Monthly', price: RecurringPrice::with( currency: 'USD', price: 1999, paymentFrequencyInterval: 'month', paymentFrequencyCount: 1, subscriptionPeriodInterval: 'month', subscriptionPeriodCount: 1, trialPeriodDays: 14, ), taxCategory: 'saas', ); // Usage-based product $product = $client->products->create( name: 'API Requests — Pay Per Use', price: UsageBasedPrice::with( currency: 'USD', unitAmount: 10, // $0.10 per unit in cents meterID: 'mtr_api_requests', ), taxCategory: 'saas', ); // Retrieve, update, and archive $product = $client->products->retrieve('prod_abc123'); $client->products->update('prod_abc123', name: 'Pro Plan — Monthly (New)', description: 'Updated plan.'); $client->products->archive('prod_abc123'); $client->products->unarchive('prod_abc123'); // List products with pagination $page = $client->products->list(recurring: true, pageSize: 20); foreach ($page->pagingEachItem() as $p) { echo $p->product_id . ' — ' . $p->name . PHP_EOL; } // Get a product image upload URL $imageInfo = $client->products->images->upload('prod_abc123'); echo $imageInfo->upload_url; // PUT your image bytes here // Generate a short link for a product $shortLink = $client->products->shortLinks->create('prod_abc123'); echo $shortLink->url; ``` -------------------------------- ### Create Customer Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Creates a new customer with basic contact information and optional metadata. The `customer_id` is returned upon successful creation. ```php customers->create( email: 'carol@example.com', name: 'Carol', phoneNumber: '+15550001234', metadata: ['tier' => 'vip'], ); echo $customer->customer_id; ``` -------------------------------- ### Create and Manage Discounts with PHP Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this to create, update, retrieve, and delete promotional discount codes. Supports percentage, flat, and flat-per-unit types. Ensure correct currency units (basis points for percentage, cents for flat). ```php discounts->create( amount: 2000, type: DiscountType::Percentage, code: 'SAVE20', usageLimit: 500, expiresAt: new DateTimeImmutable('2025-12-31T23:59:59Z'), subscriptionCycles: 3, // apply for first 3 billing cycles only preserveOnPlanChange: true, ); echo $discount->discount_id; echo $discount->code; // "SAVE20" // $10 flat discount (amount in USD cents: 1000 = $10.00) $discount = $client->discounts->create( amount: 1000, type: DiscountType::Flat, restrictedTo: ['prod_abc123'], // only for this product ); // Update a discount $client->discounts->update('disc_abc123', usageLimit: 1000, code: 'SAVE20NEW'); // Retrieve by human-readable code (useful for checkout validation) $discount = $client->discounts->retrieveByCode('SAVE20'); var_dump($discount->amount); // int(2000) // List and delete $page = $client->discounts->list(active: true, pageSize: 50); $client->discounts->delete('disc_abc123'); ``` -------------------------------- ### Manage License Keys with DodoPayments PHP SDK Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this to retrieve, update, and list license keys. You can update the activation limit or expiry date, and filter listings by customer or product ID. ```php licenseKeys->retrieve('lk_abc123'); echo $lk->status; // "active" | "expired" | "disabled" echo $lk->activations_limit; // Update activation limit or expiry $client->licenseKeys->update('lk_abc123', activationsLimit: 5); // List all license keys with filters $page = $client->licenseKeys->list( customerID: 'cus_abc123', productID: 'prod_abc123', pageSize: 50, ); foreach ($page->pagingEachItem() as $key) { echo $key->license_key . ' — ' . $key->status . PHP_EOL; } ``` -------------------------------- ### Activate and Validate Licenses with DodoPayments PHP SDK Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this to activate a license key on a device, validate its status, and deactivate it. Ensure you store the licenseKeyInstanceID for device-scoped checks. ```php licenses->activate( licenseKey: 'XXXX-YYYY-ZZZZ-WWWW', name: "Alice's MacBook Pro", ); echo $activation->license_key_instance_id; // store per-device // Validate a license key (with optional instance ID for device-scoped check) $validation = $client->licenses->validate( licenseKey: 'XXXX-YYYY-ZZZZ-WWWW', licenseKeyInstanceID: $activation->license_key_instance_id, ); var_dump($validation->valid); // bool echo $validation->status; // "active" | "expired" | "disabled" // Deactivate (e.g. when user uninstalls the app) $client->licenses->deactivate( licenseKey: 'XXXX-YYYY-ZZZZ-WWWW', licenseKeyInstanceID: $activation->license_key_instance_id, ); ``` -------------------------------- ### Pagination Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Information on how pagination works for list methods in the SDK, including manual page-by-page access, auto-pagination, and cursor-based pagination. ```APIDOC ## Pagination ### Description All `list()` methods return a page object supporting both single-page access and full auto-pagination. ### Usage **Manual page-by-page access:** ```php $page = $client->payments->list(pageSize: 10); foreach ($page->getItems() as $item) { echo $item->payment_id . PHP_EOL; } ``` **Auto-paginate through all results:** (Makes additional HTTP requests automatically) ```php foreach ($page->pagingEachItem() as $item) { echo $item->payment_id . PHP_EOL; } ``` **Cursor-based pagination:** (Webhooks use CursorPagePagination) ```php $page = $client->webhooks->list(limit: 20); $nextPage = $page->getNextPage(); // returns null when exhausted ``` ``` -------------------------------- ### Products Management Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Create, retrieve, update, archive, and list products with various pricing models (one-time, recurring, usage-based). Includes functionality for managing product images and generating short links. ```APIDOC ## Products — `$client->products` Create and manage the product catalog with one-time, recurring, or usage-based pricing. ### Create Product **Description**: Creates a new product with specified pricing and details. **Usage**: `$client->products->create(...);` **Parameters**: - `name` (string): The name of the product. - `price` (OneTimePrice|RecurringPrice|UsageBasedPrice): The pricing details for the product. - `taxCategory` (string): The tax category for the product. - `description` (string, optional): A description of the product. ### Retrieve Product **Description**: Retrieves a specific product by its ID. **Usage**: `$client->products->retrieve(string $productID);` **Parameters**: - `productID` (string): The ID of the product to retrieve. ### Update Product **Description**: Updates an existing product's details. **Usage**: `$client->products->update(string $productID, ...);` **Parameters**: - `productID` (string): The ID of the product to update. - `name` (string, optional): The new name for the product. - `description` (string, optional): The new description for the product. ### Archive Product **Description**: Archives a product, making it inactive. **Usage**: `$client->products->archive(string $productID);` **Parameters**: - `productID` (string): The ID of the product to archive. ### Unarchive Product **Description**: Unarchives a product, making it active again. **Usage**: `$client->products->unarchive(string $productID);` **Parameters**: - `productID` (string): The ID of the product to unarchive. ### List Products **Description**: Lists products, with options for filtering and pagination. **Usage**: `$client->products->list(bool $recurring = null, int $pageSize = null);` **Parameters**: - `recurring` (bool, optional): Filter for recurring products. - `pageSize` (int, optional): The number of items per page. ### Product Images Upload URL **Description**: Gets a URL to upload an image for a product. **Usage**: `$client->products->images->upload(string $productID);` **Parameters**: - `productID` (string): The ID of the product. ### Generate Product Short Link **Description**: Generates a short link for a product. **Usage**: `$client->products->shortLinks->create(string $productID);` **Parameters**: - `productID` (string): The ID of the product. ``` -------------------------------- ### Create Direct Payment (Legacy) Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this legacy API to create direct one-time payment intents. It supports customer and billing address details, and returns a payment link for redirection. ```php payments->create( billing: BillingAddress::with( country: 'US', state: 'TX', city: 'Austin', street: '456 Oak Ave', zipcode: '78701', ), customer: NewCustomer::with( email: 'bob@example.com', name: 'Bob', createNewCustomer: true, ), productCart: [['productID' => 'prod_xyz', 'quantity' => 1]], returnURL: 'https://myapp.com/thank-you', paymentLink: true, ); echo $payment->payment_link; // redirect customer ``` -------------------------------- ### Handle API Response Pagination Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Demonstrates manual page-by-page access and full auto-pagination for API list methods. Also shows cursor-based pagination for webhooks. ```php payments->list(pageSize: 10); foreach ($page->getItems() as $item) { echo $item->payment_id . PHP_EOL; } // Auto-paginate through all results (makes additional HTTP requests automatically) foreach ($page->pagingEachItem() as $item) { echo $item->payment_id . PHP_EOL; } // Cursor-based pagination (webhooks use CursorPagePagination) $page = $client->webhooks->list(limit: 20); $nextPage = $page->getNextPage(); // returns null when exhausted ``` -------------------------------- ### Change Subscription Plan with Proration Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Changes a subscription to a new product plan, applying immediate proration. Ensure `productID` is valid. ```php // Change plan (with immediate proration) $client->subscriptions->changePlan( subscriptionID: 'sub_abc123', productID: 'prod_annual_plan', prorationBillingMode: ProrationBillingMode::ProratedImmediately, quantity: 1, effectiveAt: EffectiveAt::Immediately, ); ``` -------------------------------- ### Addons Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Manage optional add-on products that can be attached to subscriptions. This includes creating, retrieving, updating, listing, and managing images for addons. ```APIDOC ## Addons — `$client->addons` ### Description Manage optional add-on products that can be attached to subscriptions. ### Methods - `create`: Creates a new addon. - `retrieve`: Retrieves a specific addon by its ID. - `update`: Updates an existing addon. - `list`: Lists all addons with optional pagination. - `updateImages`: Gets an image upload URL for an addon. ### Example Usage ```php // Create an addon $addon = $client->addons->create( currency: 'USD', name: 'Extra Storage (50 GB)', price: 499, // $4.99 in cents taxCategory: 'digital_products', description: 'Add 50 GB of cloud storage to your subscription.', ); // Retrieve and update an addon $addon = $client->addons->retrieve('addon_abc123'); $client->addons->update('addon_abc123', price: 599, name: 'Extra Storage (100 GB)'); // List addons $page = $client->addons->list(pageSize: 50); foreach ($page->pagingEachItem() as $a) { echo $a->addon_id . ' — ' . $a->name . ' — ' . $a->price . PHP_EOL; } // Get an image upload URL for an addon $imageInfo = $client->addons->updateImages('addon_abc123'); echo $imageInfo->upload_url; ``` ``` -------------------------------- ### Discounts Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Create, retrieve, update, list, and delete promotional discount codes. ```APIDOC ## Discounts — `$client->discounts` Create and manage promotional discount codes (percentage, flat, or flat-per-unit). ### Create Discount Creates a new discount code. **Parameters** - **amount** (int) - Required - The discount amount. For `Percentage` type, this is in basis points (e.g., 2000 for 20%). For `Flat` or `FlatPerUnit` types, this is in the smallest currency unit (e.g., cents). - **type** (DiscountType) - Required - The type of discount (`Percentage`, `Flat`, `FlatPerUnit`). - **code** (string) - Optional - The human-readable discount code. - **usageLimit** (int) - Optional - The maximum number of times the discount can be used. - **expiresAt** (DateTimeImmutable) - Optional - The date and time when the discount expires. - **subscriptionCycles** (int) - Optional - The number of subscription billing cycles the discount applies to. - **preserveOnPlanChange** (bool) - Optional - Whether to preserve the discount when the subscription plan changes. - **restrictedTo** (array) - Optional - A list of product IDs to which the discount is restricted. ### Update Discount Updates an existing discount. **Parameters** - **discountId** (string) - Required - The ID of the discount to update. - **usageLimit** (int) - Optional - The new usage limit. - **code** (string) - Optional - The new discount code. ### Retrieve Discount by Code Retrieves a discount by its human-readable code. **Parameters** - **code** (string) - Required - The discount code to retrieve. ### List Discounts Lists discounts with optional filtering. **Parameters** - **active** (bool) - Optional - Filter by active status. - **pageSize** (int) - Optional - The number of discounts to return per page. ### Delete Discount Deletes a discount. **Parameters** - **discountId** (string) - Required - The ID of the discount to delete. ``` -------------------------------- ### List Customers with Filtering and Pagination Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Lists customers, allowing filtering by email and creation date, and controlling the number of results per page. Iterates through results using `pagingEachItem()`. ```php // List customers with filtering and pagination $page = $client->customers->list( email: 'carol', createdAtGte: new DateTimeImmutable('2024-01-01'), pageSize: 50, ); foreach ($page->pagingEachItem() as $c) { echo $c->customer_id . ' — ' . $c->email . PHP_EOL; } ``` -------------------------------- ### Checkout Sessions Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Creates a hosted checkout page for one-time or subscription purchases. Returns a URL the customer is redirected to. ```APIDOC ## Checkout Sessions — `$client->checkoutSessions` Creates a hosted checkout page for one-time or subscription purchases. Returns a URL the customer is redirected to. ### Method ```php $client->checkoutSessions->create( productCart: [['productID' => 'prod_abc123', 'quantity' => 2]], billingAddress?: CheckoutSessionBillingAddress, customer?: array, discountCodes?: array, returnURL?: string, cancelURL?: string, metadata?: array, shortLink?: bool, requestOptions?: array ); ``` ### Method ```php $client->checkoutSessions->retrieve(string $session_id); ``` ### Method ```php $client->checkoutSessions->preview( productCart: array, discountCodes?: array, billingCurrency?: string ); ``` ### Example Usage ```php checkoutSessions->create( productCart: [['productID' => 'prod_abc123', 'quantity' => 2]] ); echo $session->url; echo $session->session_id; // Full checkout session with billing address, discount, custom fields, and return URLs $session = $client->checkoutSessions->create( productCart: [['productID' => 'prod_abc123', 'quantity' => 1]], billingAddress: CheckoutSessionBillingAddress::with( country: 'US', state: 'CA', city: 'San Francisco', street: '123 Main St', zipcode: '94105' ), customer: ['email' => 'alice@example.com', 'name' => 'Alice'], discountCodes: ['SAVE20'], returnURL: 'https://myapp.com/success', cancelURL: 'https://myapp.com/cancel', metadata: ['order_ref' => 'ORD-9981'], shortLink: true, requestOptions: ['maxRetries' => 1] ); echo $session->url; // Retrieve session status $status = $client->checkoutSessions->retrieve($session->session_id); echo $status->status; // Preview pricing before creating the session $preview = $client->checkoutSessions->preview( productCart: [['productID' => 'prod_abc123', 'quantity' => 3]], discountCodes: ['SAVE20'], billingCurrency: 'EUR' ); echo $preview->recurring_breakup->amount; ``` ``` -------------------------------- ### Preview Checkout Session Pricing Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Preview the pricing breakdown for a potential checkout session without creating it. Specify currency for accurate previews. ```php // Preview pricing before creating the session $preview = $client->checkoutSessions->preview( productCart: [['productID' => 'prod_abc123', 'quantity' => 3]], discountCodes: ['SAVE20'], billingCurrency: 'EUR', ); echo $preview->recurring_breakup->amount; ``` -------------------------------- ### Create and Manage Billing Meters Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this to define billing meters that aggregate usage events into chargeable quantities. Supports count and sum aggregations with optional filtering. ```php meters->create( aggregation: MeterAggregation::with(type: 'count'), eventName: 'api_request', measurementUnit: 'requests', name: 'API Request Meter', description: 'Counts all inbound API requests for billing.', ); echo $meter->meter_id; // e.g. "mtr_abc123" — use in product UsageBasedPrice // Create a meter that sums a metadata field (e.g. tokens_used) $tokenMeter = $client->meters->create( aggregation: MeterAggregation::with(type: 'sum', fieldName: 'tokens_used'), eventName: 'api_request', measurementUnit: 'tokens', name: 'Token Usage Meter', filter: MeterFilter::with( conditions: [['field' => 'model', 'operator' => 'eq', 'value' => 'gpt-4']] ), ); // Retrieve and list meters $meter = $client->meters->retrieve('mtr_abc123'); $page = $client->meters->list(archived: false, pageSize: 20); // Archive / unarchive $client->meters->archive('mtr_abc123'); $client->meters->unarchive('mtr_abc123'); ``` -------------------------------- ### List Customer Credit Entitlements Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Lists all credit entitlements for a customer, including their current balances. Iterates through the `items` property. ```php // List all credit entitlements with current balances $entitlements = $client->customers->listCreditEntitlements('cus_abc123'); foreach ($entitlements->items as $e) { echo $e->entitlement_id . ': ' . $e->balance . PHP_EOL; } ``` -------------------------------- ### On-Demand Subscription Charge Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Initiates an immediate charge against a subscription for a specific product price and description. Useful for add-ons or one-time purchases. ```php // On-demand charge against a subscription $charge = $client->subscriptions->charge( subscriptionID: 'sub_abc123', productPrice: 4999, // $49.99 in cents productDescription: 'Pro add-on block', metadata: ['invoice_ref' => 'INV-101'], ); echo $charge->payment_id; ``` -------------------------------- ### Create Minimal Checkout Session Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this to create a basic checkout session for one-time or subscription purchases. The returned URL is where the customer is redirected. ```php checkoutSessions->create( productCart: [['productID' => 'prod_abc123', 'quantity' => 2]] ); echo $session->url; // redirect customer here echo $session->session_id; // store for status polling ``` -------------------------------- ### Ingest Usage Events for Billing with PHP Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Ingest metered usage events in batches for usage-based billing. Events must be within a specific time window (1 hour old to 5 minutes in the future) and are limited to 1000 per request. Supports retrieving and listing events with filtering. ```php usageEvents->ingest( events: [ EventInput::with( eventId: 'evt_' . uniqid(), customerId: 'cus_abc123', eventName: 'api_request', timestamp: new DateTimeImmutable(), metadata: [ 'endpoint' => '/api/v1/completions', 'tokens_used' => '1500', 'model' => 'gpt-4', ], ), EventInput::with( eventId: 'evt_' . uniqid(), customerId: 'cus_abc123', eventName: 'api_request', timestamp: new DateTimeImmutable(), metadata: ['endpoint' => '/api/v1/embeddings', 'tokens_used' => '200'], ), ], ); echo $result->ingested_count; // number accepted // Retrieve a single event by its ID $event = $client->usageEvents->retrieve('evt_api_call_12345'); echo $event->event_name; echo $event->customer_id; // List events with filtering $page = $client->usageEvents->list( customerID: 'cus_abc123', eventName: 'api_request', meterID: 'mtr_api_requests', start: new DateTimeImmutable('2024-01-14T00:00:00Z'), end: new DateTimeImmutable('2024-01-15T00:00:00Z'), pageSize: 50, ); foreach ($page->pagingEachItem() as $e) { echo $e->event_id . ' at ' . $e->timestamp . PHP_EOL; } ``` -------------------------------- ### Create Customer Portal URL Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Generates a URL for the customer portal, allowing customers to manage their subscriptions and billing self-service. Requires a `customer_id`. ```php // Customer portal URL (manage subscriptions / billing self-service) $portal = $client->customers->customerPortal->create('cus_abc123'); echo $portal->url; ``` -------------------------------- ### List Customer Entitlements Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Retrieves a list of entitlement grants for a customer. This is a general entitlement listing. ```php // List entitlement grants $grants = $client->customers->listEntitlements('cus_abc123'); ``` -------------------------------- ### License Key Management Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Manage license key objects, including retrieval, updates to activation limits or expiry, and listing. ```APIDOC ## License Keys — `$client->licenseKeys` Manage the license key objects themselves (bulk list, retrieve, update expiry or activation limit). ### Retrieve License Key **Description**: Retrieves a specific license key record. **Usage**: `$client->licenseKeys->retrieve(string $licenseKeyID);` **Parameters**: - `licenseKeyID` (string): The ID of the license key to retrieve. ### Update License Key **Description**: Updates the activation limit or expiry of a license key. **Usage**: `$client->licenseKeys->update(string $licenseKeyID, int $activationsLimit = null);` **Parameters**: - `licenseKeyID` (string): The ID of the license key to update. - `activationsLimit` (int, optional): The new activation limit for the license key. ### List License Keys **Description**: Lists all license keys with optional filters. **Usage**: `$client->licenseKeys->list(string $customerID = null, string $productID = null, int $pageSize = null);` **Parameters**: - `customerID` (string, optional): Filter by customer ID. - `productID` (string, optional): Filter by product ID. - `pageSize` (int, optional): The number of items per page. ``` -------------------------------- ### Misc Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Utility endpoints such as listing supported countries. ```APIDOC ## Misc — `$client->misc` ### Description Utility endpoints such as listing supported countries. ### Methods - `listSupportedCountries`: Retrieves a list of all supported country codes. ### Example Usage ```php // Get all supported country codes $countries = $client->misc->listSupportedCountries(); foreach ($countries as $code) { echo $code . PHP_EOL; } ``` ``` -------------------------------- ### Customers Management Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Manage the full customer lifecycle, including creation, updates, listing, retrieving payment methods, and accessing entitlements. ```APIDOC ## Customers — `$client->customers` Full customer lifecycle: create, update, list, retrieve saved payment methods, and access entitlements. ### Create Customer Creates a new customer record. ```php // Create a customer $customer = $client->customers->create( email: 'carol@example.com', name: 'Carol', phoneNumber: '+15550001234', metadata: ['tier' => 'vip'], ); echo $customer->customer_id; ``` ### Retrieve Customer Retrieves a customer by their ID. ```php // Retrieve by ID $customer = $client->customers->retrieve('cus_abc123'); echo $customer->email; ``` ### Update Customer Updates an existing customer's information. ```php // Update email and metadata $client->customers->update( 'cus_abc123', email: 'carol-new@example.com', metadata: ['tier' => 'enterprise'], ); ``` ### List Customers Lists customers with support for filtering and pagination. ```php // List customers with filtering and pagination $page = $client->customers->list( email: 'carol', createdAtGte: new DateTimeImmutable('2024-01-01'), pageSize: 50, ); foreach ($page->pagingEachItem() as $c) { echo $c->customer_id . ' — ' . $c->email . PHP_EOL; } ``` ### Retrieve Payment Methods Retrieves all saved payment methods for a customer. ```php // Retrieve saved payment methods $methods = $client->customers->retrievePaymentMethods('cus_abc123'); foreach ($methods->payment_methods as $pm) { echo $pm->type . ' …' . $pm->last4 . PHP_EOL; } ``` ### Delete Payment Method Deletes a saved payment method for a customer. ```php // Delete a saved payment method $client->customers->deletePaymentMethod( paymentMethodID: 'pm_abc123', customerID: 'cus_abc123', ); ``` ### List Credit Entitlements Lists all credit entitlements for a customer, including current balances. ```php // List all credit entitlements with current balances $entitlements = $client->customers->listCreditEntitlements('cus_abc123'); foreach ($entitlements->items as $e) { echo $e->entitlement_id . ': ' . $e->balance . PHP_EOL; } ``` ### List Entitlements Lists entitlement grants for a customer. ```php // List entitlement grants $grants = $client->customers->listEntitlements('cus_abc123'); ``` ### Create Customer Portal URL Generates a URL for the customer portal, enabling self-service for managing subscriptions and billing. ```php // Customer portal URL (manage subscriptions / billing self-service) $portal = $client->customers->customerPortal->create('cus_abc123'); echo $portal->url; ``` ``` -------------------------------- ### Register and Verify Webhooks with PHP Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Register webhook endpoints to receive real-time event notifications. Use the provided secret to verify incoming webhook signatures for security. Supports filtering events by type. ```php webhooks->create( url: 'https://myapp.com/webhooks/dodo', filterTypes: [ WebhookEventType::PaymentSucceeded, WebhookEventType::SubscriptionActive, WebhookEventType::RefundSucceeded, WebhookEventType::DisputeOpened, ], metadata: ['env' => 'production'], ); echo $webhook->webhook_id; // Retrieve the webhook signing secret $secret = $client->webhooks->retrieveSecret($webhook->webhook_id); echo $secret->secret; // store as DODO_PAYMENTS_WEBHOOK_KEY // Parse and verify an incoming webhook (in your HTTP handler) $body = file_get_contents('php://input'); $headers = getallheaders(); try { $event = $client->webhooks->unwrap( body: $body, headers: $headers, // secret is read from $client->webhookKey automatically if set ); if ($event instanceof PaymentSucceededWebhookEvent) { $data = $event->data; echo "Payment succeeded: " . $data->payment_id; echo " — amount: " . $data->total_amount; } elseif ($event instanceof SubscriptionActiveWebhookEvent) { echo "Subscription activated: " . $event->data->subscription_id; } } catch (WebhookException $e) { http_response_code(400); echo "Invalid webhook: " . $e->getMessage(); } // Parse without signature verification (development only) $event = $client->webhooks->unsafeUnwrap($body); // List, update, and delete webhooks $page = $client->webhooks->list(limit: 20); $client->webhooks->update($webhook->webhook_id, disabled: true); $client->webhooks->delete($webhook->webhook_id); ``` -------------------------------- ### List Payments with Filters Source: https://context7.com/dodopayments/dodopayments-php/llms.txt List payments with support for filtering by customer ID, status, and creation date. It also supports pagination for large result sets. ```php // List payments with filters and auto-pagination $page = $client->payments->list( customerID: 'cus_abc123', status: 'succeeded', createdAtGte: new DateTimeImmutable('2024-01-01'), pageSize: 25, ); foreach ($page->pagingEachItem() as $item) { echo $item->payment_id . ' — ' . $item->total_amount . PHP_EOL; } ``` -------------------------------- ### License Activation and Validation Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Activate, validate, and deactivate license keys for customers' devices. ```APIDOC ## Licenses — `$client->licenses` Activate, deactivate, and validate license keys issued to customers after purchase. ### Activate License **Description**: Activates a license key on a specific device. **Usage**: `$client->licenses->activate(string $licenseKey, string $name);` **Parameters**: - `licenseKey` (string): The license key to activate. - `name` (string): The name of the device or user. ### Validate License **Description**: Validates a license key, optionally checking against a specific instance ID. **Usage**: `$client->licenses->validate(string $licenseKey, string $licenseKeyInstanceID = null);` **Parameters**: - `licenseKey` (string): The license key to validate. - `licenseKeyInstanceID` (string, optional): The instance ID for device-scoped validation. ### Deactivate License **Description**: Deactivates a license key on a device. **Usage**: `$client->licenses->deactivate(string $licenseKey, string $licenseKeyInstanceID);` **Parameters**: - `licenseKey` (string): The license key to deactivate. - `licenseKeyInstanceID` (string): The instance ID of the license key to deactivate. ``` -------------------------------- ### Issue Refunds with DodoPayments PHP SDK Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Use this to issue full or partial refunds on completed payments. You can specify a reason, metadata, or target specific line items for partial refunds. ```php refunds->create( paymentID: 'pay_abc123', reason: 'Customer requested cancellation within 30 days.', metadata: ['ticket' => 'SUPPORT-4421'], ); echo $refund->refund_id; echo $refund->status; // "pending" | "succeeded" | "failed" // Partial refund targeting specific line items $refund = $client->refunds->create( paymentID: 'pay_abc123', items: [ ['item_id' => 'li_001', 'amount' => 500], // $5.00 partial ], ); // Retrieve a refund $refund = $client->refunds->retrieve('ref_abc123'); // List refunds $page = $client->refunds->list( customerID: 'cus_abc123', status: 'succeeded', pageSize: 20, ); foreach ($page->pagingEachItem() as $r) { echo $r->refund_id . ': ' . $r->amount . PHP_EOL; } ``` -------------------------------- ### Inject Extra Parameters into Documented Calls Source: https://context7.com/dodopayments/dodopayments-php/llms.txt When making documented calls, you can inject extra parameters through the `requestOptions` array. This allows for advanced configurations like setting `maxRetries`, adding `extraBodyParams`, `extraQueryParams`, or `extraHeaders`. ```php $result = $client->checkoutSessions->create( productCart: [['productID' => 'prod_abc123', 'quantity' => 1]], requestOptions: [ 'maxRetries' => 5, 'extraBodyParams' => ['undocumented_field' => 'value'], 'extraQueryParams' => ['debug' => 'true'], 'extraHeaders' => ['X-Trace-ID' => 'trace-abc123'], ], ); ``` -------------------------------- ### Retrieve Subscription Credit Usage Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Fetches the current credit usage for a subscription. This is relevant for subscriptions that operate on a credit-based model. ```php // Retrieve credit usage (for credit-based subscriptions) $creditUsage = $client->subscriptions->retrieveCreditUsage('sub_abc123'); ``` -------------------------------- ### Retrieve Customer Payment Methods Source: https://context7.com/dodopayments/dodopayments-php/llms.txt Fetches all saved payment methods for a given customer. Displays the type and last four digits of each method. ```php // Retrieve saved payment methods $methods = $client->customers->retrievePaymentMethods('cus_abc123'); foreach ($methods->payment_methods as $pm) { echo $pm->type . ' …' . $pm->last4 . PHP_EOL; } ```