### Install SDK with Composer Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/README.md Install the 2Checkout PHP SDK using Composer. This is the recommended method for managing dependencies. ```bash composer require 2checkout/2checkout-php-sdk ``` -------------------------------- ### Example: Get and Process Subscriptions from an Order Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/Subscription.md Demonstrates how to retrieve all subscriptions for a given order reference number and then fetch details for the first subscription found. Includes error handling for potential API exceptions. ```php $subscription = $tco->subscription(); try { // Get all subscriptions from an order $subscriptionMap = $subscription->getSubscriptionsByOrderRefNo('ORDER-123'); foreach ($subscriptionMap as $lineItemRef => $subscriptionRefs) { echo "Line Item: $lineItemRef\n"; foreach ($subscriptionRefs as $subRef) { echo " - Subscription: $subRef\n"; } } // Retrieve details for first subscription if (!empty($subscriptionMap)) { $firstSubRef = reset($subscriptionMap)[0]; // Get first subscription ref $subDetails = $subscription->searchSubscriptions([ 'SubscriptionReference' => $firstSubRef ]); echo 'Subscription Status: ' . $subDetails['SubscriptionEnabled']; } } catch (TcoException $e) { echo 'Error: ' . $e->getMessage(); } ``` -------------------------------- ### generateSignature() - Basic Example Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/BuyLinkSignatureGenerator.md Demonstrates how to generate a buy link signature with essential parameters for a product purchase. ```APIDOC ## generateSignature() ### Description Generates a signature for a buy link using provided parameters. ### Method `getBuyLinkSignature(array $params)` ### Parameters - **buyLinkParams** (array) - An associative array containing parameters for the buy link. - `merchant` (string) - Your 2Checkout merchant ID. - `name` (string) - Customer's full name. - `email` (string) - Customer's email address. - `address` (string) - Customer's street address. - `city` (string) - Customer's city. - `state` (string) - Customer's state or province. - `country` (string) - Customer's country code (e.g., 'US'). - `zip` (string) - Customer's ZIP or postal code. - `prod` (string) - Product name or description. - `price` (float) - The price of the product. - `qty` (integer) - The quantity of the product. - `type` (string) - Type of product (e.g., 'PRODUCT'). - `tangible` (integer) - Indicates if the product is tangible (1) or digital (0). - `currency` (string) - The currency code (e.g., 'usd'). - `language` (string) - The language code for the checkout page (e.g., 'en'). - `test` (integer) - Set to 1 for test mode, 0 for live. - `dynamic` (integer) - Set to 1 for dynamic products, 0 for catalog products. - `src` (string) - Source identifier for the sale. - `return-url` (string) - URL to redirect the customer to after purchase. - `return-type` (string) - Type of return (e.g., 'redirect'). - `recurrence` (string) - For recurring billing (e.g., '1:MONTH'). - `duration` (string) - Duration for recurring billing (e.g., '12:MONTH'). - `renewal-price` (float) - The renewal price for recurring billing. - `expiration` (integer) - Unix timestamp for when the link expires. ### Request Example ```php try { $buyLinkParams = array( 'merchant' => '123456', 'name' => 'John Doe', 'email' => 'john@example.com', 'address' => '123 Main St', 'city' => 'New York', 'state' => 'NY', 'country' => 'US', 'zip' => '10001', 'prod' => 'Monthly Subscription', 'price' => 29.99, 'qty' => 1, 'type' => 'PRODUCT', 'tangible' => 0, 'currency' => 'usd', 'language' => 'en', 'test' => 1, 'dynamic' => 1, 'src' => 'myapp', 'return-url' => 'https://mysite.com/sub-success', 'return-type' => 'redirect', 'recurrence' => '1:MONTH', // Billed monthly 'duration' => '12:MONTH', // For 12 months 'renewal-price' => 29.99, // Renewal amount 'expiration' => time() + 3600 // Link expires in 1 hour ); $signature = $tco->getBuyLinkSignature($buyLinkParams); // ... use signature to build checkout URL ... } catch (TcoException $e) { echo 'Error: ' . $e->getMessage(); } ``` ### Response - **signature** (string) - The generated buy link signature. ``` -------------------------------- ### Example Usage of AuthFactory Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/Authentication.md This example demonstrates how to instantiate TcoConfig, create an AuthFactory, and then obtain both REST API and Buy Link authentication instances. ```php use Tco\Source\Api\Auth\AuthFactory; use Tco\TcoConfig; $config = new TcoConfig([ 'sellerId' => '123456', 'secretKey' => 'api-secret', 'buyLinkSecretWord' => 'buylink-secret' ]); $factory = new AuthFactory($config); // Get REST API authentication $authApi = $factory->getAuth('Api'); // Get Buy Link authentication $authBuyLink = $factory->getAuth('BuyLink'); ``` -------------------------------- ### Validate Configuration Settings Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/configuration.md Test different configuration arrays to validate their correctness using `TwocheckoutFacade`. This example demonstrates validating both minimal and full configuration setups. ```php use Tco\Exceptions\TcoException; $testConfigs = [ [ 'name' => 'Minimal Config', 'config' => [ 'sellerId' => '123456', 'secretKey' => 'secret-key' ] ], [ 'name' => 'Full Config', 'config' => [ 'sellerId' => '123456', 'secretKey' => 'secret-key', 'buyLinkSecretWord' => 'buylink-secret', 'jwtExpireTime' => 60, 'curlVerifySsl' => 1 ] ] ]; foreach ($testConfigs as $test) { try { $tco = new TwocheckoutFacade($test['config']); echo $test['name'] . ': ✓ Valid' . PHP_EOL; } catch (TcoException $e) { echo $test['name'] . ': ✗ Invalid - ' . $e->getMessage() . PHP_EOL; } } ``` -------------------------------- ### Complete Configuration Class Example Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/configuration.md This class handles the configuration for the 2Checkout SDK, reading settings from environment variables. It ensures all necessary credentials are set before proceeding. ```php config = [ 'sellerId' => $this->getSellerId(), 'secretKey' => $this->getSecretKey(), 'buyLinkSecretWord' => $this->getBuyLinkSecret(), 'jwtExpireTime' => $this->getJwtExpireTime(), 'curlVerifySsl' => $this->isProductionEnvironment() ? 1 : 0 ]; } private function getSellerId() { return $_ENV['TCO_SELLER_ID'] ?? die('Missing TCO_SELLER_ID environment variable'); } private function getSecretKey() { return $_ENV['TCO_SECRET_KEY'] ?? die('Missing TCO_SECRET_KEY environment variable'); } private function getBuyLinkSecret() { return $_ENV['TCO_BUYLINK_SECRET'] ?? ''; } private function getJwtExpireTime() { return (int) ($_ENV['TCO_JWT_EXPIRE'] ?? 30); } private function isProductionEnvironment() { return ($_ENV['APP_ENV'] ?? 'development') === 'production'; } public function getConfig() { return $this->config; } public function getFacade() { return new TwocheckoutFacade($this->config); } } ``` -------------------------------- ### Basic 2Checkout SDK Configuration Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TcoConfig.md Initialize the SDK with essential credentials (sellerId, secretKey) and SSL verification setting. This is a common starting point for most integrations. ```php require_once '/path/to/2checkout-php-sdk/autoloader.php'; use Tco\TwocheckoutFacade; $config = array( 'sellerId' => '123456', 'secretKey' => 'your-api-secret-key', 'curlVerifySsl' => 1 ); try { $tco = new TwocheckoutFacade($config); echo 'Configured with seller ID: ' . $tco->apiCore()->tcoConfig->getSellerId(); } catch (TcoException $e) { echo 'Configuration error: ' . $e->getMessage(); } ``` -------------------------------- ### Place and Retrieve Order Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TwocheckoutFacade.md Example of using the Order helper to place a new order and then retrieve order details by reference number. ```php $order = $tco->order(); $response = $order->place($orderParams); $orderData = $order->getOrder(['RefNo' => '12345']); ``` -------------------------------- ### Complete IPN Webhook Handler Example Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/IpnSignature.md A full example of a PHP script to handle incoming IPN (Instant Payment Notification) webhooks from 2Checkout. It validates the signature, extracts payment details, updates a database, and sends an acknowledgment. ```php $_ENV['TCO_SELLER_ID'], 'secretKey' => $_ENV['TCO_SECRET_KEY'] ); try { // Validate IPN signature $tco = new TwocheckoutFacade($config); $ipnData = $_POST; if (!$tco->validateIpnResponse($ipnData)) { error_log('IPN validation failed'); http_response_code(403); die('Signature validation failed'); } // Extract payment information $refNo = $ipnData['REFNO']; $status = $ipnData['STATUS']; $total = $ipnData['TOTAL']; $currency = $ipnData['CURRENCY']; $email = $ipnData['EMAIL'] ?? null; // Log IPN error_log("IPN received - RefNo: $refNo, Status: $status"); // Update database $db = getDatabase(); $db->query( 'UPDATE orders SET status = ?, ipn_received = NOW() WHERE refno = ?', [$status, $refNo] ); // Handle status-specific logic switch ($status) { case 'COMPLETE': case 'AUTHRECEIVED': // Payment confirmed $db->query( 'UPDATE orders SET paid = 1 WHERE refno = ?', [$refNo] ); sendConfirmationEmail($email, $refNo); break; case 'PENDING': // Payment pending (e.g., awaiting 3D Secure) $db->query( 'UPDATE orders SET status = ? WHERE refno = ?', ['pending_confirmation', $refNo] ); break; case 'CANCELED': // Payment cancelled/failed $db->query( 'UPDATE orders SET status = ? WHERE refno = ?', ['cancelled', $refNo] ); break; } // Send acknowledgment to 2Checkout echo $tco->generateIpnResponse($ipnData); } catch (TcoException $e) { error_log('IPN Error: ' . $e->getMessage()); http_response_code(500); echo '' . htmlspecialchars($e->getMessage()) . ''; } ?> ``` -------------------------------- ### generateSignature() - Advanced Example with All Customer Details Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/BuyLinkSignatureGenerator.md Shows how to generate a buy link signature including comprehensive billing, shipping, product, and tracking details. ```APIDOC ## generateSignature() - Advanced Example ### Description Generates a buy link signature with detailed customer, billing, shipping, and product information, suitable for complex transactions. ### Method `getBuyLinkSignature(array $params)` ### Parameters - **buyLinkParams** (array) - An associative array containing detailed parameters for the buy link. - `merchant` (string) - Your 2Checkout merchant ID. - `name` (string) - Billing customer's full name. - `email` (string) - Billing customer's email address. - `phone` (string) - Billing customer's phone number. - `company-name` (string) - Billing customer's company name. - `address` (string) - Billing customer's street address. - `city` (string) - Billing customer's city. - `state` (string) - Billing customer's state or province. - `country` (string) - Billing customer's country code. - `zip` (string) - Billing customer's ZIP or postal code. - `ship-name` (string) - Shipping customer's full name (if different). - `ship-email` (string) - Shipping customer's email address. - `ship-address` (string) - Shipping customer's street address. - `ship-city` (string) - Shipping customer's city. - `ship-state` (string) - Shipping customer's state or province. - `ship-country` (string) - Shipping customer's country code. - `ship-zip` (string) - Shipping customer's ZIP or postal code. - `prod` (string) - Product name. - `price` (float) - Product price. - `qty` (integer) - Product quantity. - `type` (string) - Product type (e.g., 'PRODUCT'). - `tangible` (integer) - 1 for physical, 0 for digital. - `currency` (string) - Currency code (e.g., 'usd'). - `language` (string) - Language code (e.g., 'en'). - `src` (string) - Source identifier. - `test` (integer) - 0 for live, 1 for test. - `dynamic` (integer) - 0 for catalog, 1 for dynamic. - `order-ext-ref` (string) - External reference for the order. - `item-ext-ref` (string) - External reference for the item. - `customer-ext-ref` (string) - External reference for the customer. - `return-url` (string) - URL for post-purchase redirection. - `return-type` (string) - Type of return (e.g., 'redirect'). - `expiration` (integer) - Unix timestamp for link expiration. ### Request Example ```php try { $buyLinkParams = array( 'merchant' => '123456', // Billing details 'name' => 'John Doe', 'email' => 'john@example.com', 'phone' => '+1-555-1234', 'company-name' => 'Acme Corp', 'address' => '123 Business Ave', 'city' => 'San Francisco', 'state' => 'CA', 'country' => 'US', 'zip' => '94107', // Shipping details (if different from billing) 'ship-name' => 'Jane Doe', 'ship-email' => 'jane@example.com', 'ship-address' => '456 Warehouse Blvd', 'ship-city' => 'Oakland', 'ship-state' => 'CA', 'ship-country' => 'US', 'ship-zip' => '94609', // Product details 'prod' => 'Premium Package', 'price' => 199.99, 'qty' => 1, 'type' => 'PRODUCT', 'tangible' => 1, // Physical product 'currency' => 'usd', 'language' => 'en', // Source and mode 'src' => 'sales_team', 'test' => 0, // Live transaction 'dynamic' => 0, // Catalog product // Tracking 'order-ext-ref' => 'ORD-2024-001', 'item-ext-ref' => 'ITEM-SKU-123', 'customer-ext-ref' => 'CUST-9999', // Callbacks 'return-url' => 'https://mysite.com/orders/confirm', 'return-type' => 'redirect', 'expiration' => time() + 86400 // Valid for 24 hours ); $signature = $tco->getBuyLinkSignature($buyLinkParams); $buyLinkParams['signature'] = $signature; $url = 'https://secure.2checkout.com/checkout/buy/?' . http_build_query($buyLinkParams); } catch (TcoException $e) { error_log('Buy Link signature error: ' . $e->getMessage()); } ``` ### Response - **signature** (string) - The generated buy link signature, which is then appended to the buy link URL. ``` -------------------------------- ### Generate IPN Response Example Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/IpnSignature.md This example demonstrates how to receive, validate, and generate an XML acknowledgment for an IPN using the TwocheckoutFacade. Ensure you have the SDK autoloader included and configure your seller ID and secret key. The code sets the content type to XML and handles potential TcoExceptions during processing. ```php require_once('/path/to/2checkout-php-sdk/autoloader.php'); use Tco\TwocheckoutFacade; use Tco\Exceptions\TcoException; // Receive and validate IPN $config = array( 'sellerId' => '123456', 'secretKey' => 'your-api-secret-key' ); $tco = new TwocheckoutFacade($config); $ipnData = $_POST; // Set headers to return XML header('Content-Type: application/xml'); try { // Validate IPN if (!$tco->validateIpnResponse($ipnData)) { throw new Exception('IPN validation failed'); } // Process payment $refNo = $ipnData['REFNO']; $status = $ipnData['STATUS']; $customerId = $ipnData['CUST_MSG'] ?? null; // Your custom business logic logPayment($refNo, $status); if ($status === 'COMPLETE') { activateService($customerId); } // Send acknowledgment $response = $tco->generateIpnResponse($ipnData); echo $response; exit; } catch (TcoException $e) { error_log('IPN processing error: ' . $e->getMessage()); echo 'IPN Processing Error'; exit; } ``` -------------------------------- ### Search Subscriptions Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TwocheckoutFacade.md Example of using the Subscription helper to retrieve subscriptions by order reference number and search for subscriptions by their reference. ```php $subscription = $tco->subscription(); $subscriptions = $subscription->getSubscriptionsByOrderRefNo('order-ref-no'); $details = $subscription->searchSubscriptions(['SubscriptionReference' => 'sub-ref']); ``` -------------------------------- ### Generate and Use Buy Link Signature (Simple Product) Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/BuyLinkSignatureGenerator.md This example demonstrates how to generate a Buy Link signature for a simple product, append it to the checkout URL, and redirect the customer. It includes error handling for signature generation. ```php require_once('/path/to/2checkout-php-sdk/autoloader.php'); use Tco\TwocheckoutFacade; $config = array( 'sellerId' => '123456', 'secretKey' => 'api-secret-key', 'buyLinkSecretWord' => 'buy-link-secret-word' ); $tco = new TwocheckoutFacade($config); // Simple product try { $buyLinkParams = array( 'merchant' => '123456', 'prod' => 'E-Book: Advanced PHP', 'price' => 19.99, 'qty' => 1, 'type' => 'PRODUCT', 'tangible' => 0, 'currency' => 'usd', 'language' => 'en', 'test' => 1, 'return-url' => 'https://mysite.com/checkout-complete', 'return-type' => 'redirect' ); $signature = $tco->getBuyLinkSignature($buyLinkParams); $buyLinkParams['signature'] = $signature; $checkoutUrl = 'https://secure.2checkout.com/checkout/buy/?' . http_build_query($buyLinkParams); // Redirect customer to checkout header('Location: ' . $checkoutUrl); exit; } catch (TcoException $e) { echo 'Error generating signature: ' . $e->getMessage(); } ``` -------------------------------- ### Auth API Example Usage Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/Interfaces-and-Utilities.md Demonstrates how to instantiate and use an AuthApi object, which implements the Auth interface, to retrieve HTTP headers for API requests. ```php use Tco\Interfaces\Auth; use Tco\Source\Api\Auth\AuthApi; $auth = new AuthApi('123456', 'secret-key'); // Implements Auth if ($auth instanceof Auth) { $headers = $auth->getHeaders(); foreach ($headers as $header) { // Use headers in HTTP request } } ``` -------------------------------- ### Initialize TwocheckoutFacade Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TwocheckoutFacade.md Instantiate the TwocheckoutFacade with your 2Checkout credentials. Ensure all required configuration keys are provided to avoid exceptions. This setup is necessary before performing any SDK operations. ```php require_once('/path/to/2checkout-php-sdk/autoloader.php'); use Tco\TwocheckoutFacade; $config = array( 'sellerId' => '123456', 'secretKey' => 'your-api-secret-key', 'buyLinkSecretWord' => 'your-buy-link-secret', 'jwtExpireTime' => 30, 'curlVerifySsl' => 1 ); try { $tco = new TwocheckoutFacade($config); } catch (TcoException $e) { echo 'Configuration error: ' . $e->getMessage(); } ``` -------------------------------- ### Dynamic Product Order Example Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/types.md Use this snippet to create an order for a dynamic product, such as a software license or a one-time service. It includes detailed item information and payment method specifics. ```php $orderParams = array( 'Country' => 'US', 'Currency' => 'USD', 'CustomerIP' => '192.168.1.1', 'ExternalReference' => 'ORD-' . time(), 'Language' => 'en', 'Source' => 'myapp', 'BillingDetails' => array( 'Address1' => '123 Main Street', 'City' => 'New York', 'State' => 'NY', 'CountryCode' => 'US', 'Email' => 'customer@example.com', 'FirstName' => 'John', 'LastName' => 'Doe', 'Zip' => '10001' ), 'Items' => array( array( 'Name' => 'Premium Software License', 'Description' => 'Annual subscription', 'Quantity' => 1, 'IsDynamic' => true, 'Tangible' => false, 'PurchaseType' => 'PRODUCT', 'Price' => array( 'Amount' => 99.99, 'Type' => 'CUSTOM' ) ) ), 'PaymentDetails' => array( 'Type' => 'EES_TOKEN_PAYMENT', 'Currency' => 'USD', 'CustomerIP' => '192.168.1.1', 'PaymentMethod' => array( 'EesToken' => 'eyJ0eXA...', 'RecurringEnabled' => false, 'HolderNameTime' => 1617117946, 'CardNumberTime' => 1617117946, 'Vendor3DSReturnURL' => 'https://mysite.com/3ds-success', 'Vendor3DSCancelURL' => 'https://mysite.com/3ds-cancel' ) ) ); ``` -------------------------------- ### Full 2Checkout SDK Configuration Options Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TcoConfig.md Configure the SDK with all available options, including seller ID, secret key, buy link secret word, JWT expiration time, and SSL verification. Use this for advanced setups requiring all features. ```php $config = array( 'sellerId' => '123456', 'secretKey' => 'api-secret-key-abc123xyz', 'buyLinkSecretWord' => 'buylink-secret-def456uvw', 'jwtExpireTime' => 60, // JWT tokens expire after 60 minutes 'curlVerifySsl' => 1 // Enable SSL verification in production ); $tco = new TwocheckoutFacade($config); ``` -------------------------------- ### Make Direct API Call Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TwocheckoutFacade.md Example of using the apiCore client to make a direct POST request to the /orders/ endpoint. ```php $apiCore = $tco->apiCore(); $response = $apiCore->call('/orders/', $orderData, 'POST'); ``` -------------------------------- ### Catalog Product Order Example Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/types.md Use this snippet to create an order for a product that exists in your 2Checkout catalog. It requires the product's code and quantity. ```php $orderParams = array( 'Country' => 'BR', 'Currency' => 'BRL', 'CustomerIP' => '91.220.121.21', 'ExternalReference' => 'CUSTORD100', 'BillingDetails' => array( 'Address1' => 'Test Address', 'City' => 'São Paulo', 'CountryCode' => 'BR', 'Email' => 'customer@example.com', 'FirstName' => 'Maria', 'FiscalCode' => '123.456.789-00', 'LastName' => 'Silva', 'Phone' => '1133335555', 'State' => 'SP', 'Zip' => '01001-100' ), 'Items' => array( array( 'Code' => 'PRODUCT-CODE-123', // From 2Checkout catalog 'Quantity' => 1 ) ), 'PaymentDetails' => array( 'Type' => 'TEST', 'Currency' => 'BRL', 'CustomerIP' => '91.220.121.21', 'PaymentMethod' => array( 'RecurringEnabled' => false, 'HolderNameTime' => 1617117946, 'CardNumberTime' => 1617117946 ) ) ); ``` -------------------------------- ### Get Subscription Helper Instance Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TwocheckoutFacade.md Returns an instance of the Subscription helper for managing subscriptions, including searching, updating, enabling, and disabling. ```php public function subscription(): Subscription ``` -------------------------------- ### Item with Recurring Subscription Options Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/README.md An example demonstrating how to include 'RecurringOptions' within an 'Items' array for a dynamic product, specifying subscription billing cycles and amounts. ```php 'Items' => array( 0 => array( 'Name' => 'Dynamic product', 'Description' => 'Product Description test', 'Quantity' => 3, //units 'IsDynamic' => true, 'Tangible' => false, 'PurchaseType' => 'PRODUCT', 'Price' => array( 'Amount' => 6, //amount in currency units 'Type' => 'CUSTOM', ), //Dynamic product subscription. 'RecurringOptions' => array( 'CycleLength' => 1, //The length of the recurring billing cycle. 'CycleUnit' => 'MONTH', //Unit of measuring billing cycles (years, months). 'CycleAmount' => 3, //The amount to be billed on each renewal. 'ContractLength' => 3, //The contact length for which the recurring option will apply. 'ContractUnit' => 'Year', //Unit of measuring contact length (years, months). ) ) ) ``` -------------------------------- ### Generate Advanced Buy Link Signature with All Customer Details Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/BuyLinkSignatureGenerator.md Generates a buy link signature including comprehensive billing, shipping, product, and tracking details. This example also constructs the full checkout URL. ```php try { $buyLinkParams = array( 'merchant' => '123456', // Billing details 'name' => 'John Doe', 'email' => 'john@example.com', 'phone' => '+1-555-1234', 'company-name' => 'Acme Corp', 'address' => '123 Business Ave', 'city' => 'San Francisco', 'state' => 'CA', 'country' => 'US', 'zip' => '94107', // Shipping details (if different from billing) 'ship-name' => 'Jane Doe', 'ship-email' => 'jane@example.com', 'ship-address' => '456 Warehouse Blvd', 'ship-city' => 'Oakland', 'ship-state' => 'CA', 'ship-country' => 'US', 'ship-zip' => '94609', // Product details 'prod' => 'Premium Package', 'price' => 199.99, 'qty' => 1, 'type' => 'PRODUCT', 'tangible' => 1, // Physical product 'currency' => 'usd', 'language' => 'en', // Source and mode 'src' => 'sales_team', 'test' => 0, // Live transaction 'dynamic' => 0, // Catalog product // Tracking 'order-ext-ref' => 'ORD-2024-001', 'item-ext-ref' => 'ITEM-SKU-123', 'customer-ext-ref' => 'CUST-9999', // Callbacks 'return-url' => 'https://mysite.com/orders/confirm', 'return-type' => 'redirect', 'expiration' => time() + 86400 // Valid for 24 hours ); $signature = $tco->getBuyLinkSignature($buyLinkParams); $buyLinkParams['signature'] = $signature; $url = 'https://secure.2checkout.com/checkout/buy/?' . http_build_query($buyLinkParams); } catch (TcoException $e) { error_log('Buy Link signature error: ' . $e->getMessage()); } ``` -------------------------------- ### Process and Acknowledge IPN Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/IpnSignature.md This example demonstrates how to receive IPN data, validate its signature using `validateIpnResponse`, process the payment status if valid, and generate an acknowledgment response using `generateIpnResponse`. It includes error handling for invalid signatures and exceptions during validation. ```php require_once('/path/to/2checkout-php-sdk/autoloader.php'); use Tco\TwocheckoutFacade; use Tco\Exceptions\TcoException; $config = array( 'sellerId' => '123456', 'secretKey' => 'your-api-secret-key' ); $tco = new TwocheckoutFacade($config); // Receive IPN from 2Checkout $ipnData = $_POST; try { if ($tco->validateIpnResponse($ipnData)) { // IPN is authentic - safe to process $refNo = $ipnData['REFNO']; $status = $ipnData['STATUS']; $total = $ipnData['TOTAL']; // Update your database with payment status updatePaymentStatus($refNo, $status); // Send acknowledgment back to 2Checkout $response = $tco->generateIpnResponse($ipnData); echo $response; } else { // IPN signature is invalid - possible attack error_log('Invalid IPN signature detected: ' . $ipnData['REFNO']); http_response_code(403); } } catch (TcoException $e) { error_log('IPN validation error: ' . $e->getMessage()); http_response_code(500); } ``` -------------------------------- ### Load 2Checkout SDK Configuration from Environment Variables Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TcoConfig.md Initialize the SDK by loading configuration values from environment variables. This is recommended for security and flexibility in different deployment environments. ```php $config = array( 'sellerId' => getenv('TCO_SELLER_ID'), 'secretKey' => getenv('TCO_SECRET_KEY'), 'buyLinkSecretWord' => getenv('TCO_BUYLINK_SECRET'), 'jwtExpireTime' => (int) getenv('TCO_JWT_EXPIRE') ?: 30, 'curlVerifySsl' => (int) getenv('TCO_VERIFY_SSL') ?: 0 ); $tco = new TwocheckoutFacade($config); ``` -------------------------------- ### Instantiate Facade with Configuration Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/configuration.md This snippet shows how to create an instance of the TwoCheckoutConfiguration class and then obtain the 2Checkout facade object using the configured settings. ```php $tcoConfig = new TwoCheckoutConfiguration(); $tco = $tcoConfig->getFacade(); ``` -------------------------------- ### Initialize 2Checkout PHP SDK Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/README.md Include the autoloader and initialize the TwocheckoutFacade with your merchant credentials. Ensure 'sellerId' and 'secretKey' are provided. ```php require_once('/path/to/2checkout-php-library/autoloader.php'); use Tco\TwocheckoutFacade; ``` ```php $config = array( 'sellerId' => YOUR_MERCHANT_CODE, // REQUIRED 'secretKey' => YOUR_SECRET_KEY, // REQUIRED 'buyLinkSecretWord' => YOUR_SECRET_WORD, 'jwtExpireTime' => 30, 'curlVerifySsl' => 1 ); $tco = new TwocheckoutFacade($config); ``` -------------------------------- ### Get Seller ID from AuthBuyLink Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/Authentication.md Retrieves the seller ID associated with the AuthBuyLink instance. ```php public function getSellerId(): string ``` -------------------------------- ### PSR-4 Autoloader Class Definition Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/Interfaces-and-Utilities.md Defines the structure for the PSR-4 autoloader class used in non-Composer installations. ```php class Psr4AutoloaderClass { public function register(); public function addNamespace(string $prefix, string $baseDir); protected function loadClass(string $class); } ``` -------------------------------- ### Load 2Checkout SDK Configuration from a File Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TcoConfig.md Configure the SDK by loading settings from an external PHP configuration file. This approach centralizes configuration and is useful for managing settings across different parts of an application. ```php // config/2checkout.php return array( 'sellerId' => '123456', 'secretKey' => 'api-secret-key', 'buyLinkSecretWord' => 'buylink-secret', 'jwtExpireTime' => 30, 'curlVerifySsl' => 1 ); // In application code $config = require 'config/2checkout.php'; $tco = new TwocheckoutFacade($config); ``` -------------------------------- ### Get Order Details Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/README.md This snippet demonstrates how to retrieve specific order details using the getOrder method. ```APIDOC ## Get Order Details ### Description Retrieves detailed information about a specific order using its reference number. ### Method ```php $orderData = $tco->order()->getOrder( array( 'RefNo' => $response['refNo'] ) ); ``` ### Parameters - **$tco**: An initialized TwocheckoutFacade instance. - **array( 'RefNo' => $response['refNo'] )**: An array containing the reference number of the order to retrieve. ``` -------------------------------- ### Loading Configuration with Fallbacks Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/errors.md Loads seller ID and secret key from environment variables, with a fallback to terminating if not set. Use this to configure the SDK. ```php $config = [ 'sellerId' => $_ENV['TCO_SELLER_ID'] ?? die('TCO_SELLER_ID not set'), 'secretKey' => $_ENV['TCO_SECRET_KEY'] ?? die('TCO_SECRET_KEY not set') ]; ``` -------------------------------- ### Get API Core Client Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TwocheckoutFacade.md Returns an instance of the low-level API client for making direct REST API calls. ```php public function apiCore(): ApiCore ``` -------------------------------- ### Secure Credential Loading and Initialization Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/configuration.md Loads 2Checkout credentials from environment variables and initializes the SDK. Ensures sensitive data is not hardcoded. ```php // Only load from environment if (!getenv('TCO_SELLER_ID') || !getenv('TCO_SECRET_KEY')) { die('Fatal: Missing 2Checkout configuration in environment variables'); } $config = array( 'sellerId' => getenv('TCO_SELLER_ID'), 'secretKey' => getenv('TCO_SECRET_KEY'), 'buyLinkSecretWord' => getenv('TCO_BUYLINK_SECRET'), 'curlVerifySsl' => 1 ); $tco = new TwocheckoutFacade($config); ``` -------------------------------- ### Recurring Subscription Order Example Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/types.md Use this snippet to create an order for a recurring subscription service. It includes specific 'RecurringOptions' for the subscription. ```php $orderParams = array( 'Country' => 'US', 'Currency' => 'USD', 'BillingDetails' => array( 'Address1' => '123 Main Street', 'City' => 'San Francisco', 'State' => 'CA', 'CountryCode' => 'US', 'Email' => 'customer@example.com', 'FirstName' => 'Alex', 'LastName' => 'Johnson', 'Zip' => '94107' ), 'Items' => array( array( 'Name' => 'Monthly Subscription', 'Description' => 'Recurring service', 'Quantity' => 1, 'IsDynamic' => true, 'Tangible' => false, 'PurchaseType' => 'PRODUCT', 'Price' => array( 'Amount' => 29.99, 'Type' => 'CUSTOM' ), 'RecurringOptions' => array( 'CycleLength' => 1, 'CycleUnit' => 'MONTH', 'CycleAmount' => 29.99, 'ContractLength' => 12, 'ContractUnit' => 'MONTH' ) ) ), 'PaymentDetails' => array( 'Type' => 'EES_TOKEN_PAYMENT', 'Currency' => 'USD', 'PaymentMethod' => array( 'EesToken' => 'token-string', 'RecurringEnabled' => true, 'Vendor3DSReturnURL' => 'https://mysite.com/success', 'Vendor3DSCancelURL' => 'https://mysite.com/cancel' ) ) ); ``` -------------------------------- ### Place an Order with 2Checkout Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/README.md Place a new order using the SDK, providing detailed billing and item information. Ensure all required parameters for order placement are included. ```php use Tco\TwocheckoutFacade; use Tco\Exceptions\TcoException; $config = ['sellerId' => '123456', 'secretKey' => 'key']; $tco = new TwocheckoutFacade($config); try { $orderParams = [ 'Country' => 'US', 'Currency' => 'USD', 'CustomerIP' => '192.168.1.1', 'BillingDetails' => [ 'FirstName' => 'John', 'LastName' => 'Doe', 'Email' => 'john@example.com', 'Address1' => '123 Main St', 'City' => 'New York', 'State' => 'NY', 'CountryCode' => 'US', 'Zip' => '10001' ], 'Items' => [ [ 'Name' => 'Product', 'Price' => ['Amount' => 99.99, 'Type' => 'CUSTOM'], 'Quantity' => 1, 'IsDynamic' => true, 'Tangible' => false, 'PurchaseType' => 'PRODUCT' ] ], 'PaymentDetails' => [ 'Type' => 'EES_TOKEN_PAYMENT', 'Currency' => 'USD', 'PaymentMethod' => ['EesToken' => 'token-from-2pay-js'] ] ]; $response = $tco->order()->place($orderParams); echo 'Order placed: ' . $response['RefNo']; } catch (TcoException $e) { echo 'Error: ' . $e->getMessage(); } ``` -------------------------------- ### Get Order by External Reference Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/Order.md Retrieves order details using your external reference number. Catches potential TcoException errors. ```php $order = $tco->order(); // Search by external reference try { $orderData = $order->getOrder(['ExternalRefNo' => 'CUST-001']); } catch (TcoException $e) { echo 'Error: ' . $e->getMessage(); } ``` -------------------------------- ### Get Secret Key Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TcoConfig.md Retrieves the configured REST API secret key. Ensure the secret key is set in the TcoConfig constructor. ```php public function getSecretKey(): string ``` -------------------------------- ### Get Order Helper Instance Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/_autodocs/api-reference/TwocheckoutFacade.md Returns an instance of the Order helper for managing orders, including placing, searching, and issuing refunds. ```php public function order(): Order ``` -------------------------------- ### Set Up Catalog Product Order Parameters in PHP Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/README.md Prepare an array of parameters for placing an order with a catalog product. Ensure all required fields like Country, Currency, BillingDetails, Items, and PaymentDetails are correctly populated. The item code should be retrieved from your 2Checkout control panel. ```php $orderCatalogProductParams = array( 'Country' => 'br', 'Currency' => 'brl', 'CustomerIP' => '91.220.121.21', 'ExternalReference' => 'CustOrderCatProd100', 'Language' => 'en', 'BillingDetails' => array( 'Address1' => 'Test Address', 'City' => 'LA', 'CountryCode' => 'BR', 'Email' => 'customer@2Checkout.com', 'FirstName' => 'Customer', 'FiscalCode' => '056.027.963-98', 'LastName' => '2Checkout', 'Phone' => '556133127400', 'State' => 'DF', 'Zip' => '70403-900', ), 'Items' => array( 0 => array( 'Code' => 'E377076E6A_COPY1', //Get the code from CPANEL at Setup->Products->Code column 'Quantity' => '1', ), ), 'PaymentDetails' => array( 'Type' => 'TEST', 'Currency' => 'USD', 'CustomerIP' => '91.220.121.21', 'PaymentMethod' => array( 'CCID' => '123', 'CardNumber' => '4111111111111111', 'CardNumberTime' => '12', 'CardType' => 'VISA', 'ExpirationMonth' => '12', 'ExpirationYear' => '2023', 'HolderName' => 'John Doe', 'HolderNameTime' => '12', 'RecurringEnabled' => true, 'Vendor3DSReturnURL' => 'www.test.com', 'Vendor3DSCancelURL' => 'www.test.com', ), ), ); ``` -------------------------------- ### Get and Validate Order Source: https://github.com/2checkout/2checkout-php-sdk/blob/main/README.md Retrieve an order using its reference number and validate its status. Successful payments will have a status of 'AUTHRECEIVED' or 'COMPLETE'. ```php $order = $tco->order(); ``` ```php $response = $order->place( $dynamicOrderParams ); ``` ```php $orderData = $tco->order()->getOrder( array( 'RefNo' => $response['refNo'] ) ); ```