Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Plug&Pay SDK
https://github.com/plug-and-pay/sdk-php
Admin
A PHP SDK designed to simplify and facilitate communication with the Plug&Pay API.
Tokens:
32,625
Snippets:
141
Trust Score:
4.9
Update:
3 weeks ago
Context
Skills
Chat
Benchmark
74.3
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Plug&Pay PHP SDK The Plug&Pay PHP SDK provides a streamlined interface for integrating with the Plug&Pay payment and e-commerce platform. It enables PHP applications to manage products, orders, subscriptions, checkouts, affiliate sellers, rules, memberships, tax rates, and payments through a clean, object-oriented API. The SDK requires PHP 8.1+ and uses Guzzle for HTTP communication with the Plug&Pay API v2. The SDK follows a service-oriented architecture where each resource type (products, orders, subscriptions, etc.) has a dedicated service class. Services support CRUD operations, filtering, pagination, and eager loading of related data through an `include()` method. All responses are mapped to entity objects with type-safe getters and setters, and the SDK provides comprehensive exception handling for validation errors, authentication failures, and not-found scenarios. ## Client Authentication Initialize the SDK client with your API access token to authenticate all requests to the Plug&Pay API. ```php use PlugAndPay\Sdk\Service\Client; // Basic client initialization $client = new Client('your_access_token'); // Client with custom API URL (for testing/staging) $client = new Client( 'your_access_token', 'https://api.staging.plugandpay.com', 'https://admin.staging.plugandpay.com' ); ``` ## OAuth Authorization Flow Generate authorization URLs and exchange authorization codes for access tokens using the PKCE flow. ```php use PlugAndPay\Sdk\Service\Client; $client = new Client(); // Generate code verifier and state $codeVerifier = Client::getRandomString(128); $state = Client::getRandomString(40); // Generate authorization URL $authUrl = $client->generateAuthorizationUrl( clientId: 12345, state: $state, codeVerifier: $codeVerifier, redirectUrl: 'https://your-app.com/callback' ); // After user authorization, exchange code for tokens $response = $client->getCredentials( code: $_GET['code'], codeVerifier: $codeVerifier, redirectUrl: 'https://your-app.com/callback', clientId: 12345, tenantId: 67890, clientSecret: 'your_client_secret' ); $accessToken = $response->body()['access_token']; $refreshToken = $response->body()['refresh_token']; // Refresh tokens when needed $refreshResponse = $client->refreshTokensIfNeeded( refreshToken: $refreshToken, clientId: 12345, tenantId: 67890, clientSecret: 'your_client_secret' ); if ($refreshResponse->body()['refreshed']) { $newAccessToken = $refreshResponse->body()['access_token']; } // Revoke tokens when logging out $client->revokeTokens(); ``` ## Exception Handling Handle SDK exceptions properly to manage validation errors, authentication failures, and not-found scenarios. ```php use PlugAndPay\Sdk\Exception\NotFoundException; use PlugAndPay\Sdk\Exception\RelationNotLoadedException; use PlugAndPay\Sdk\Exception\ValidationException; use PlugAndPay\Sdk\Exception\UnauthenticatedException; use PlugAndPay\Sdk\Exception\DecodeResponseException; try { // Your SDK operations here $order = $orderService->find($orderId); } catch (ValidationException $exception) { // HTTP 422 - Invalid data submitted $message = $exception->getMessage(); $field = $exception->errors()[0]->field(); $errorMessage = $exception->errors()[0]->message(); } catch (UnauthenticatedException $exception) { // HTTP 401 - Invalid or expired token } catch (NotFoundException $exception) { // HTTP 404 - Resource not found } catch (RelationNotLoadedException $exception) { // Tried to access relation not loaded via include() } catch (BadFunctionCallException $exception) { // Invalid function usage } catch (DecodeResponseException $exception) { // Failed to decode API response } ``` ## ProductService - List Products Retrieve all products with optional filtering, sorting, and eager loading of related data. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\ProductService; use PlugAndPay\Sdk\Filters\ProductFilter; use PlugAndPay\Sdk\Enum\ProductIncludes; use PlugAndPay\Sdk\Enum\Direction; use PlugAndPay\Sdk\Enum\ProductSortType; use PlugAndPay\Sdk\Enum\ContractType; $client = new Client('your_access_token'); $service = new ProductService($client); // Get all products with pricing and tax rates $products = $service->include( ProductIncludes::PRICING, ProductIncludes::TAX_RATES, )->get(); // Get products with filters $filter = (new ProductFilter()) ->direction(Direction::ASC) ->hasLimitedStock(true) ->isDeleted(false) ->limit(10) ->page(1) ->query('Lorem') ->sort(ProductSortType::ACTIVE_SUBSCRIPTIONS) ->tag(['first']) ->type(ContractType::INSTALLMENTS); $filteredProducts = $service->get($filter); foreach ($products as $product) { echo $product->id() . ': ' . $product->title(); } ``` ## ProductService - Find Product Retrieve a single product by ID with optional related data. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\ProductService; use PlugAndPay\Sdk\Enum\ProductIncludes; $client = new Client('your_access_token'); $service = new ProductService($client); $productId = 1; $product = $service->include( ProductIncludes::PRICING, ProductIncludes::TAX_RATES, )->find($productId); $id = $product->id(); $title = $product->title(); $description = $product->description(); $sku = $product->sku(); $slug = $product->slug(); $physical = $product->physical(); $pricing = $product->pricing(); $stock = $product->stock(); ``` ## ProductService - Create Product Create a new product with pricing tiers, stock settings, and tax configuration. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\ProductService; use PlugAndPay\Sdk\Entity\Product; use PlugAndPay\Sdk\Entity\ProductPricing; use PlugAndPay\Sdk\Entity\Price; use PlugAndPay\Sdk\Entity\PriceRegular; use PlugAndPay\Sdk\Entity\PriceFirst; use PlugAndPay\Sdk\Entity\PriceTier; use PlugAndPay\Sdk\Entity\PricingTax; use PlugAndPay\Sdk\Entity\TaxRate; use PlugAndPay\Sdk\Entity\Stock; use PlugAndPay\Sdk\Entity\Shipping; use PlugAndPay\Sdk\Enum\ProductIncludes; use PlugAndPay\Sdk\Enum\Interval; use PlugAndPay\Sdk\Enum\ContractType; $client = new Client('your_access_token'); $service = new ProductService($client); $stock = (new Stock()) ->setEnabled(true) ->setHidden(false) ->setValue(100); $taxRate = (new TaxRate())->setId(1); $pricingTax = (new PricingTax())->setRate($taxRate); $shipping = (new Shipping())->setAmount(5.00); $tierOne = (new PriceTier())->setAmount(100.00)->setQuantity(10); $tierTwo = (new PriceTier())->setAmount(90.00)->setQuantity(100); $priceRegular = (new PriceRegular())->setAmount(120.00); $priceFirst = (new PriceFirst())->setAmount(99.00); $monthlyPrice = (new Price()) ->setFirst($priceFirst) ->setRegular($priceRegular) ->setInterval(Interval::MONTHLY) ->setSuggested(true) ->setTiers([$tierOne, $tierTwo]); $productPricing = (new ProductPricing()) ->setTaxIncluded(true) ->setPrices([$monthlyPrice]) ->setShipping($shipping) ->setTax($pricingTax); $product = (new Product()) ->setTitle('Premium Membership') ->setPublicTitle('Premium Membership Plan') ->setDescription('Access to all premium features') ->setLedger(99998) ->setPhysical(false) ->setPricing($productPricing) ->setSku('PREM-001') ->setSlug('premium-membership') ->setStock($stock) ->setType(ContractType::SUBSCRIPTION); $createdProduct = $service->include( ProductIncludes::PRICING, ProductIncludes::TAX_RATES, )->create($product); echo 'Created product ID: ' . $createdProduct->id(); ``` ## ProductService - Update Product Update an existing product using a callback function. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\ProductService; use PlugAndPay\Sdk\Entity\Product; use PlugAndPay\Sdk\Entity\Stock; $client = new Client('your_access_token'); $service = new ProductService($client); $productId = 12; $service->update( $productId, fn(Product $product) => $product ->setTitle('Updated Product Title') ->setStock((new Stock()) ->setHidden(false) ->setEnabled(true) ->setValue(200) ) ); ``` ## ProductService - Delete Product Delete a product by ID. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\ProductService; $client = new Client('your_access_token'); $service = new ProductService($client); $productId = 12; $service->delete($productId); ``` ## OrderService - List Orders Retrieve all orders with comprehensive filtering options. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\OrderService; use PlugAndPay\Sdk\Filters\OrderFilter; use PlugAndPay\Sdk\Enum\OrderIncludes; use PlugAndPay\Sdk\Enum\ContractType; use PlugAndPay\Sdk\Enum\CountryCode; use PlugAndPay\Sdk\Enum\Direction; use PlugAndPay\Sdk\Enum\InvoiceStatus; use PlugAndPay\Sdk\Enum\Mode; use PlugAndPay\Sdk\Enum\PaymentStatus; use PlugAndPay\Sdk\Enum\OrderSortType; use PlugAndPay\Sdk\Enum\Source; $client = new Client('your_access_token'); $service = new OrderService($client); // Get all orders with related data $orders = $service->include( OrderIncludes::BILLING, OrderIncludes::COMMENTS, OrderIncludes::DISCOUNTS, OrderIncludes::ITEMS, OrderIncludes::PAYMENT, OrderIncludes::TAGS, OrderIncludes::TAXES, )->get(); // Get orders with filters $filter = (new OrderFilter()) ->affiliateId(1234) ->contractType(ContractType::SUBSCRIPTION) ->country(CountryCode::NL) ->direction(Direction::DESC) ->email('customer@example.com') ->invoiceStatus(InvoiceStatus::FINAL) ->limit(25) ->mode(Mode::LIVE) ->page(1) ->paymentStatus(PaymentStatus::PAID) ->productId(1234) ->sort(OrderSortType::PAID_AT) ->source(Source::API) ->sincePaidAt(new DateTimeImmutable('2024-01-01')) ->untilPaidAt(new DateTimeImmutable('2024-12-31')); $filteredOrders = $service->get($filter); ``` ## OrderService - Find Order Retrieve a single order by ID with all related data. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\OrderService; use PlugAndPay\Sdk\Enum\OrderIncludes; $client = new Client('your_access_token'); $service = new OrderService($client); $orderId = 1; $order = $service->include( OrderIncludes::BILLING, OrderIncludes::COMMENTS, OrderIncludes::DISCOUNTS, OrderIncludes::ITEMS, OrderIncludes::PAYMENT, OrderIncludes::TAGS, OrderIncludes::TAXES, )->find($orderId); $amount = $order->amount(); $amountWithTax = $order->amountWithTax(); $invoiceNumber = $order->invoiceNumber(); $invoiceStatus = $order->invoiceStatus()->value; $mode = $order->mode()->value; $source = $order->source()->value; $createdAt = $order->createdAt(); // Access billing information $billing = $order->billing(); $email = $billing->email(); $firstName = $billing->firstName(); $address = $billing->address(); $city = $address->city(); $country = $address->country()->value; // Access order items foreach ($order->items() as $item) { $itemId = $item->id(); $label = $item->label(); $productId = $item->productId(); $quantity = $item->quantity(); $itemAmount = $item->amount(); } // Access payment information $payment = $order->payment(); $paymentStatus = $payment->status()->value; $paymentMethod = $payment->method()->value; $paidAt = $payment->paidAt(); ``` ## OrderService - Create Order Create a new order with billing information, items, payment, and discounts. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\OrderService; use PlugAndPay\Sdk\Entity\Order; use PlugAndPay\Sdk\Entity\OrderBilling; use PlugAndPay\Sdk\Entity\Contact; use PlugAndPay\Sdk\Entity\Address; use PlugAndPay\Sdk\Entity\Item; use PlugAndPay\Sdk\Entity\Payment; use PlugAndPay\Sdk\Entity\Tax; use PlugAndPay\Sdk\Entity\Discount; use PlugAndPay\Sdk\Entity\Comment; use PlugAndPay\Sdk\Enum\OrderIncludes; use PlugAndPay\Sdk\Enum\CountryCode; use PlugAndPay\Sdk\Enum\PaymentType; use PlugAndPay\Sdk\Enum\PaymentStatus; use PlugAndPay\Sdk\Enum\PaymentProvider; use PlugAndPay\Sdk\Enum\PaymentMethod; use PlugAndPay\Sdk\Enum\TaxExempt; use PlugAndPay\Sdk\Enum\DiscountType; use PlugAndPay\Sdk\Enum\Mode; use PlugAndPay\Sdk\Enum\Source; $client = new Client('your_access_token'); $service = new OrderService($client); $contact = (new Contact()) ->setCompany('Acme Corp') ->setEmail('customer@example.com') ->setFirstName('John') ->setLastName('Doe') ->setTaxExempt(TaxExempt::REVERSE) ->setTelephone('+31612345678') ->setWebsite('https://example.com'); $address = (new Address()) ->setCity('Amsterdam') ->setCountry(CountryCode::NL) ->setStreet('Main Street') ->setHouseNumber('123') ->setZipcode('1234AB'); $billing = (new OrderBilling()) ->setAddress($address) ->setContact($contact); $itemOne = (new Item())->setProductId(1); $itemTwo = (new Item())->setProductId(2); $tax = (new Tax())->setRateId(1); $discount = (new Discount()) ->setAmount(10) ->setCode('SAVE10') ->setType(DiscountType::PROMOTION); $payment = (new Payment()) ->setMethod(PaymentMethod::IDEAL) ->setPaidAt(new DateTimeImmutable()) ->setProvider(PaymentProvider::MOLLIE) ->setStatus(PaymentStatus::PAID) ->setType(PaymentType::MANUAL); $comment = (new Comment())->setValue('Rush order - priority shipping'); $order = (new Order()) ->setAmount(100) ->setTotal(121) ->setBilling($billing) ->setComments([$comment]) ->setTotalDiscounts([$discount]) ->setHidden(false) ->setItems([$itemOne, $itemTwo]) ->setMode(Mode::LIVE) ->setPayment($payment) ->setReference('ORD-2024-001') ->setSource(Source::API) ->setTags(['vip', 'priority']) ->setTaxes([$tax]); $createdOrder = $service->include( OrderIncludes::BILLING, OrderIncludes::ITEMS, OrderIncludes::PAYMENT, )->create($order); echo 'Created order ID: ' . $createdOrder->id(); ``` ## OrderService - Update Order Update an existing order using a callback function. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\OrderService; use PlugAndPay\Sdk\Entity\Order; use PlugAndPay\Sdk\Enum\OrderIncludes; use PlugAndPay\Sdk\Enum\Mode; use PlugAndPay\Sdk\Enum\CountryCode; $client = new Client('your_access_token'); $service = new OrderService($client); $orderId = 14; $order = $service->include( OrderIncludes::BILLING, OrderIncludes::PAYMENT, )->update($orderId, function (Order $order) { $order->setAmount(1000.00); $order->setTotal(1210.00); $order->setHidden(true); $order->setMode(Mode::LIVE); $order->setReference('ORD-2024-001-UPDATED'); // Update billing address $order->billing()->address() ->setCity('Rotterdam') ->setCountry(CountryCode::NL) ->setStreet('New Street') ->setHouseNumber('456') ->setZipcode('3000AB'); // Update billing contact $order->billing()->contact() ->setCompany('New Company') ->setEmail('new@example.com') ->setFirstName('Jane') ->setLastName('Smith'); }); ``` ## OrderService - Delete Order Delete an order by ID. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\OrderService; $client = new Client('your_access_token'); $service = new OrderService($client); $orderId = 12; $service->delete($orderId); ``` ## SubscriptionService - List Subscriptions Retrieve all subscriptions with filtering and related data. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\SubscriptionService; use PlugAndPay\Sdk\Filters\SubscriptionFilter; use PlugAndPay\Sdk\Enum\SubscriptionIncludes; use PlugAndPay\Sdk\Enum\Interval; use PlugAndPay\Sdk\Enum\CountryCode; use PlugAndPay\Sdk\Enum\Mode; use PlugAndPay\Sdk\Enum\SubscriptionStatus; use PlugAndPay\Sdk\Enum\ContractType; $client = new Client('your_access_token'); $service = new SubscriptionService($client); $subscriptions = $service->include( SubscriptionIncludes::BILLING, SubscriptionIncludes::PRICING, SubscriptionIncludes::PRODUCT, SubscriptionIncludes::TAGS, SubscriptionIncludes::TRIAL, )->get(); // With filters $filter = (new SubscriptionFilter()) ->affiliateId(1234) ->billingScheduleInterval(Interval::MONTHLY) ->country(CountryCode::NL) ->hasOrders(true) ->isTrial(false) ->limit(10) ->mode(Mode::LIVE) ->page(1) ->productId(1) ->status(SubscriptionStatus::ACTIVE) ->tag(['premium']) ->type(ContractType::SUBSCRIPTION) ->sinceCreatedAt(new DateTimeImmutable('2024-01-01')); $filteredSubscriptions = $service->get($filter); ``` ## SubscriptionService - Find Subscription Retrieve a single subscription by ID with all related data. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\SubscriptionService; use PlugAndPay\Sdk\Enum\SubscriptionIncludes; $client = new Client('your_access_token'); $service = new SubscriptionService($client); $subscriptionId = 40; $subscription = $service->include( SubscriptionIncludes::BILLING, SubscriptionIncludes::META, SubscriptionIncludes::PRICING, SubscriptionIncludes::PRODUCT, SubscriptionIncludes::TAGS, SubscriptionIncludes::TRIAL, )->find($subscriptionId); $id = $subscription->id(); $status = $subscription->status(); $mode = $subscription->mode()->value; $source = $subscription->source(); $cancelledAt = $subscription->cancelledAt(); $createdAt = $subscription->createdAt(); // Pricing information $pricing = $subscription->pricing(); $amount = $pricing->amount(); $amountWithTax = $pricing->amountWithTax(); $quantity = $pricing->quantity(); // Billing schedule $schedule = $subscription->billing()->schedule(); $interval = $schedule->interval()->value; $nextAt = $schedule->nextAt(); $remaining = $schedule->remaining(); // Product information $product = $subscription->product(); $productTitle = $product->title(); // Trial information $trial = $subscription->trial(); $isTrialActive = $trial->isActive(); ``` ## SubscriptionService - Create Subscription Create a new subscription with billing, pricing, and payment configuration. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\SubscriptionService; use PlugAndPay\Sdk\Entity\Subscription; use PlugAndPay\Sdk\Entity\SubscriptionBilling; use PlugAndPay\Sdk\Entity\SubscriptionBillingSchedule; use PlugAndPay\Sdk\Entity\SubscriptionPaymentOptions; use PlugAndPay\Sdk\Entity\SubscriptionPricing; use PlugAndPay\Sdk\Entity\SubscriptionTrial; use PlugAndPay\Sdk\Entity\Contact; use PlugAndPay\Sdk\Entity\Address; use PlugAndPay\Sdk\Entity\Tax; use PlugAndPay\Sdk\Enum\SubscriptionIncludes; use PlugAndPay\Sdk\Enum\Interval; use PlugAndPay\Sdk\Enum\CountryCode; use PlugAndPay\Sdk\Enum\PaymentType; use PlugAndPay\Sdk\Enum\PaymentProvider; use PlugAndPay\Sdk\Enum\Mode; use PlugAndPay\Sdk\Enum\SubscriptionStatus; use PlugAndPay\Sdk\Enum\Source; $client = new Client('your_access_token'); $service = new SubscriptionService($client); $trial = (new SubscriptionTrial()) ->setStartDate(new DateTimeImmutable()) ->setEndDate(new DateTimeImmutable('+14 days')) ->setIsActive(true); $paymentOptions = (new SubscriptionPaymentOptions()) ->setCustomerId('cust_123456') ->setProvider(PaymentProvider::MOLLIE) ->setType(PaymentType::MANDATE) ->setIban('NL12ABNA0746352736') ->setName('John Doe'); $schedule = (new SubscriptionBillingSchedule()) ->setInterval(Interval::MONTHLY) ->setNextAt(new DateTimeImmutable('+1 month')); $contact = (new Contact()) ->setEmail('subscriber@example.com') ->setFirstName('John') ->setLastName('Doe') ->setTelephone('+31612345678'); $address = (new Address()) ->setCity('Amsterdam') ->setCountry(CountryCode::NL) ->setStreet('Main Street') ->setHouseNumber('123') ->setZipcode('1234AB'); $billing = (new SubscriptionBilling()) ->setAddress($address) ->setContact($contact) ->setPaymentOptions($paymentOptions) ->setSchedule($schedule); $tax = (new Tax())->setAmount(21.00); $pricing = (new SubscriptionPricing()) ->setAmount(99.00) ->setQuantity(1) ->setTax($tax) ->setIsTaxIncluded(false); $subscription = (new Subscription()) ->setMode(Mode::LIVE) ->setPricing($pricing) ->setProductId(7) ->setStatus(SubscriptionStatus::ACTIVE) ->setSource(Source::API) ->setBilling($billing) ->setTags(['premium', 'annual']) ->setTrial($trial); $createdSubscription = $service->include( SubscriptionIncludes::BILLING, SubscriptionIncludes::PRICING, SubscriptionIncludes::PRODUCT, )->create($subscription); echo 'Created subscription ID: ' . $createdSubscription->id(); ``` ## SubscriptionService - Update Subscription Update an existing subscription using a callback function. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\SubscriptionService; use PlugAndPay\Sdk\Entity\Subscription; use PlugAndPay\Sdk\Enum\Mode; use PlugAndPay\Sdk\Enum\SubscriptionStatus; use PlugAndPay\Sdk\Enum\Source; use PlugAndPay\Sdk\Enum\Interval; use PlugAndPay\Sdk\Enum\CountryCode; use PlugAndPay\Sdk\Enum\PaymentProvider; use PlugAndPay\Sdk\Enum\PaymentType; $client = new Client('your_access_token'); $service = new SubscriptionService($client); $subscriptionId = 1; $subscription = $service->update($subscriptionId, function (Subscription $subscription) { $subscription->setMode(Mode::LIVE); $subscription->setTags(['premium', 'upgraded']); $subscription->setStatus(SubscriptionStatus::ACTIVE); $subscription->setSource(Source::API); // Update pricing $subscription->pricing() ->setAmount(149.00) ->setQuantity(1) ->tax()->setAmount(31.29); // Update product $subscription->product()->setId(8); // Update billing address $subscription->billing()->address() ->setCity('Rotterdam') ->setCountry(CountryCode::NL) ->setStreet('New Street') ->setHouseNumber('456') ->setZipcode('3000AB'); // Update billing schedule $subscription->billing()->schedule() ->setInterval(Interval::YEARLY) ->setNextAt(new DateTimeImmutable('+1 year')); // Update payment options $subscription->billing()->paymentOptions() ->setProvider(PaymentProvider::MOLLIE) ->setType(PaymentType::MANDATE); }); ``` ## SubscriptionService - Delete Subscription Delete a subscription by ID. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\SubscriptionService; $client = new Client('your_access_token'); $service = new SubscriptionService($client); $subscriptionId = 2; $service->delete($subscriptionId); ``` ## CheckoutService - CRUD Operations Manage checkout pages for products with full CRUD operations. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\CheckoutService; use PlugAndPay\Sdk\Entity\Checkout; $client = new Client('your_access_token'); $service = new CheckoutService($client); // List all checkouts $checkouts = $service->get(); // Find single checkout $checkout = $service->find($checkoutId); // Create new checkout $newCheckout = (new Checkout()) ->setIsActive(true) ->setIsExpired(false) ->setName('Premium Plan Checkout') ->setPreviewUrl('https://preview.example.com') ->setPrimaryColor('#3498db') ->setProductId(1) ->setReturnUrl('https://example.com/thank-you') ->setSecondaryColor('#ffffff') ->setSlug('premium-checkout') ->setUrl('https://checkout.example.com'); $createdCheckout = $service->create($newCheckout); // Update checkout $checkout = $service->find($checkoutId); $checkout->setName('Updated Checkout Name'); $service->update($checkout); // Delete checkout $service->delete($checkoutId); ``` ## RuleService - CRUD Operations Manage automation rules for webhooks and triggers. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\RuleService; use PlugAndPay\Sdk\Entity\Rule; $client = new Client('your_access_token'); $service = new RuleService($client); // List all rules $rules = $service->get(); // Find single rule $rule = $service->find($ruleId); // Create new rule $newRule = (new Rule()) ->setName('Order Paid Webhook') ->setDriver('webhook') ->setTriggerType('order_paid') ->setActionType('call_webhook') ->setActionData(['url' => 'https://example.com/webhook']) ->setConditionData(['product_id' => [1, 2, 3]]); $createdRule = $service->create($newRule); // Update rule $rule = $service->find($ruleId); $rule->setName('Updated Rule Name'); $service->update($rule); // Delete rule $service->delete($ruleId); ``` ## MembershipsSettingService - CRUD Operations Manage membership integration settings. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\MembershipsSettingService; use PlugAndPay\Sdk\Entity\MembershipsSetting; $client = new Client('your_access_token'); $service = new MembershipsSettingService($client); // List all membership settings $settings = $service->get(); // Find single setting $setting = $service->find($settingId); // Create new membership setting $newSetting = (new MembershipsSetting()) ->setDriver('huddle') ->setIsActive(true) ->setTenantId(1) ->setApiToken('your_membership_api_token'); $createdSetting = $service->create($newSetting); // Update setting $setting = $service->find($settingId); $setting->setDriver('kajabi'); $service->update($setting); // Delete setting $service->delete($settingId); ``` ## AffiliateSellerService - List and Find Sellers Retrieve affiliate sellers with filtering and related data. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\AffiliateSellerService; use PlugAndPay\Sdk\Filters\AffiliateSellerFilter; use PlugAndPay\Sdk\Enum\AffiliateSellerIncludes; use PlugAndPay\Sdk\Enum\Direction; use PlugAndPay\Sdk\Enum\SellerSortType; use PlugAndPay\Sdk\Enum\SellerStatus; $client = new Client('your_access_token'); $service = new AffiliateSellerService($client); // List sellers with includes $sellers = $service->include( AffiliateSellerIncludes::ADDRESS, AffiliateSellerIncludes::CONTACT, AffiliateSellerIncludes::PROFILE, AffiliateSellerIncludes::STATISTICS, AffiliateSellerIncludes::PAYOUT_OPTIONS, AffiliateSellerIncludes::PAYOUT_METHODS, )->get(); // Filter sellers $filter = (new AffiliateSellerFilter()) ->direction(Direction::DESC) ->eligibleForPayout(true) ->limit(10) ->query('john') ->since(new DateTimeImmutable('2024-01-01')) ->sort(SellerSortType::COMMISSION) ->status(SellerStatus::ACCEPTED) ->until(new DateTimeImmutable('2024-12-31')); $filteredSellers = $service->get($filter); // Find single seller $sellerId = 1; $seller = $service->include( AffiliateSellerIncludes::CONTACT, AffiliateSellerIncludes::STATISTICS, AffiliateSellerIncludes::PAYOUT_METHODS, )->find($sellerId); $id = $seller->id(); $name = $seller->name(); $email = $seller->email(); $status = $seller->status()->value; // Access payout methods foreach ($seller->payoutMethods() as $method) { $methodId = $method->id(); $methodType = $method->method(); $settings = $method->settings(); } ``` ## TaxRateService - List Tax Rates Retrieve tax rates filtered by country. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\TaxRateService; use PlugAndPay\Sdk\Filters\TaxRateFilter; use PlugAndPay\Sdk\Enum\CountryCode; $client = new Client('your_access_token'); $service = new TaxRateService($client); $filter = (new TaxRateFilter())->country(CountryCode::NL); $taxRates = $service->get($filter); foreach ($taxRates as $taxRate) { $id = $taxRate->id(); $percentage = $taxRate->percentage(); } ``` ## OrderPaymentService - Find and Update Payments Manage order payment status and details. ```php use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\OrderPaymentService; use PlugAndPay\Sdk\Entity\Payment; use PlugAndPay\Sdk\Enum\PaymentStatus; $client = new Client('your_access_token'); $service = new OrderPaymentService($client); // Find payment $paymentId = 14; $payment = $service->find($paymentId); // Update payment status $service->update($paymentId, function (Payment $payment) { $payment->setStatus(PaymentStatus::PAID); }); ``` ## Mocking for Testing Mock the SDK client for unit testing without making real API calls. ```php // Option 1: Guzzle Client Mock use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Psr7\Response; use PlugAndPay\Sdk\Service\Client; use PlugAndPay\Sdk\Service\OrderService; $guzzleClient = new GuzzleClient([ 'handler' => function (Request $request) { $path = $request->getUri()->getPath(); $method = $request->getMethod(); if ($method === 'DELETE' && $path === '/v2/orders/1') { return new Response(204); } if ($method === 'GET' && $path === '/v2/orders/1') { return new Response(200, [], json_encode([ 'data' => ['id' => 1, 'amount' => 100] ])); } throw new Exception("No mock for $method $path"); }, ]); $client = new Client('test_token', null, null, $guzzleClient); $service = new OrderService($client); $service->delete(1); // Option 2: Predefined Mock Clients use PlugAndPay\Sdk\Tests\Feature\Order\Mock\OrderShowMockClient; use PlugAndPay\Sdk\Tests\Feature\Order\Mock\OrderDestroyMockClient; use PlugAndPay\Sdk\Service\OrderService; use Symfony\Component\HttpFoundation\Response; // Delete mock $client = new OrderDestroyMockClient(Response::HTTP_NO_CONTENT, []); (new OrderService($client))->delete(1); // Show mock with billing included $client = (new OrderShowMockClient(['id' => 1]))->billing(); $order = (new OrderService($client))->find(1); $billing = $order->billing(); ``` ## Summary The Plug&Pay PHP SDK is designed for e-commerce platforms, SaaS applications, and subscription businesses that need to integrate with the Plug&Pay payment platform. Common use cases include building custom checkout flows, managing recurring subscriptions, automating order processing through webhooks, syncing product catalogs, tracking affiliate sales, and generating financial reports. The SDK's service-oriented architecture makes it easy to perform complex operations while the entity system ensures type safety and IDE autocompletion. Integration patterns typically involve initializing a single Client instance with authentication, then creating service instances as needed for specific operations. The `include()` method should be used judiciously to load only required relations, improving performance. All operations should be wrapped in try-catch blocks to handle the various exception types appropriately. For testing, the SDK provides mock clients that can be used to simulate API responses without making actual HTTP requests, making it easy to write comprehensive unit tests for your integration code.