### Initialize and Use Headless API with NodeJS Source: https://github.com/tebexio/tebex-sdk-nodejs/blob/master/README.md Demonstrates initializing the Tebex Headless API with a public key and performing common operations like listing categories and packages, getting a specific category, and creating baskets. It also shows how to handle user authentication and add packages to a basket. ```javascript Tebex.headless.setProject("your-public-key").then(project => { project.listCategories().then(categories => { // loops through all categories }); project.listPackages().then(packages => { // loop through all packages }); project.getCategory(12345).then(category => { //use specific category }); // Create baskets by providing a completion and cancellation url project.createBasket("https://tebex.io/completed", "https://tebex.io/cancelled").then(basket => { // If the project requires a user to auth, direct them to the auth url. On return the user's basket will // contain their authorized username. // NOTE: Most stores require the user to be authed before you are able to add packages. if (project.requiresUserAuth()) { let authUrl = project.getUserAuthUrl(basket, "https://tebex.io/auth-return"); console.log("User auth required at: " + authUrl + "."); } // Add packages after auth project.getPackage(67890).then(pack => { // Various helper functions are provided for special actions such as gifting or gift card deliverables. basket.addPackage(pack); basket.addGiftedPackage(pack, "Username"); basket.addGiftCardPackage(pack, "tebex-integrations@overwolf.com"); // You may also provide custom variable data as needed basket.addPackage(pack, { "server_id":"127244", }); }); // Each function returns the remote basket after completion, but you can always refresh your current // basket instance from the API. basket.refreshBasket().then(b => { //use new basket }); // Query the basket variable for any information console.log("Price $: " + basket.getBasket().basePrice); // Go to checkout let checkoutLink = basket.getLinks().checkout; console.log("Checkout at: " + checkoutLink); }) }); ``` -------------------------------- ### Tebex Checkout API: Create and Request Checkout using Node.js Source: https://github.com/tebexio/tebex-sdk-nodejs/blob/master/README.md This snippet demonstrates initializing the Tebex Checkout API with project and private keys, building a basket with customer information and URLs, defining one-time and subscription packages, and making a checkout request. It also shows how to add packages to an existing basket. Dependencies include the Tebex SDK. It outputs a checkout link. ```javascript let checkout = Tebex.checkout.setApiKeys("project-id", "private-key"); // Use a BasketBuilder to create your basket let basketBuilder = checkout.newBasketBuilder() .email("tebex-integrations@overwolf.com") .firstname("Tebex") .lastname("Integrations") .returnUrl("https://tebex.io/") .completeUrl("https://tebex.io/"); // Use a Package builder to define packages let package1 = checkout.newPackageBuilder() .name("100 Gold") .qty(1) .price(1.27) .oneTime() let package2 = checkout.newPackageBuilder() .name("1 Month Sub") .qty(1) .price(2.44) .subscription() .monthly() // Recommended: Create a single checkout request containing basket info, all packages, and any sales. let checkoutItems = [ package1.buildCheckoutItem(), package2.buildCheckoutItem() ]; checkout.checkoutRequest(basketBuilder, checkoutItems, undefined).then( (checkoutBasket) => { console.log("Checkout at: " + checkoutBasket.links!.checkout); } ).catch(console.error); // Alternatively, you can add, remove, or change packages as needed after building the basket. basketBuilder.build().then((basket) => { Tebex.checkout.addPackage(basket, package1.build()).then((currentBasket) => { // The basket object contains all property getters let checkoutLink = currentBasket.links?.checkout; console.log("Checkout at: " + checkoutLink); }) }).catch(console.error); ``` -------------------------------- ### Initialize Headless API Project with Tebex SDK Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Initializes connection to a Tebex store using a public token. This allows access to pre-defined packages and categories. It requires the 'tebex-sdk-nodejs' package. Outputs store platform name and authentication requirement. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); // Initialize the project with your public key Tebex.headless.setProject("your-public-key-here").then(project => { console.log("Connected to store:", project.getPlatformName()); console.log("Requires user auth:", project.requiresUserAuth()); }).catch(error => { console.error("Failed to initialize project:", error.message); }); ``` -------------------------------- ### Initialize Tebex Checkout API with Node.js Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Sets up the Tebex Checkout API using project credentials. This is necessary for creating ad-hoc payments for products not pre-defined in your Tebex store. It requires a project ID and private key for initialization and logs success or failure to the console. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); // Initialize Checkout API with project ID and private key const checkout = Tebex.checkout.setApiKeys("your-project-id", "your-private-key"); if (checkout.areApiKeysSet()) { console.log("Checkout API initialized successfully"); } else { console.error("Failed to initialize Checkout API"); } ``` -------------------------------- ### Headless API - Initialize Project Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Initializes the Headless API with your Tebex store's public token. This allows you to access store data and initiate transactions. ```APIDOC ## Initialize Headless API Project ### Description Connect to a Tebex store using a public token to access pre-defined packages, categories, and create baskets for checkout. ### Method N/A (SDK Initialization) ### Endpoint N/A (SDK Initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { Tebex } = require('tebex-sdk-nodejs'); // Initialize the project with your public key Tebex.headless.setProject("your-public-key-here").then(project => { console.log("Connected to store:", project.getPlatformName()); console.log("Requires user auth:", project.requiresUserAuth()); }).catch(error => { console.error("Failed to initialize project:", error.message); }); ``` ### Response #### Success Response (200) - **project** (object) - An initialized project object providing access to store functionalities. - **getPlatformName** (function) - Returns the name of the Tebex platform. - **requiresUserAuth** (function) - Returns a boolean indicating if user authentication is required. #### Response Example ```javascript // On successful initialization console.log("Connected to store: Minecraft"); console.log("Requires user auth: true"); ``` ``` -------------------------------- ### List Tebex Packages and Categories using Node.js Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Retrieves all available packages and categories from a Tebex store using the headless API. This is useful for building custom storefronts or displaying product catalogs. It requires a public key for initialization and outputs category and package details to the console. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); Tebex.headless.setProject("your-public-key").then(async project => { try { // List all categories const categories = await project.listCategories(); categories.forEach(category => { console.log(`Category: ${category.name} (ID: ${category.id})`); console.log(` Description: ${category.description}`); console.log(` Order: ${category.order}`); }); // List all packages const packages = await project.listPackages(); packages.forEach(pkg => { console.log(`Package: ${pkg.name} (ID: ${pkg.id})`); console.log(` Price: $${pkg.basePrice}`); console.log(` Category: ${pkg.category?.name}`); }); // Get specific category with packages const category = await project.getCategory(123); console.log(`Category "${category.name}" has ${category.packages?.length || 0} packages`); // Get specific package details const specificPackage = await project.getPackage(456); console.log(`Package: ${specificPackage.name}`); console.log(` Price: $${specificPackage.basePrice}`); console.log(` Type: ${specificPackage.type}`); } catch (error) { console.error("Failed to fetch store data:", error.message); } }); ``` -------------------------------- ### Create Tebex Checkout Request with Ad-hoc Packages using Node.js Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Builds and submits a complete checkout request with dynamically defined packages, customer information, and optional sales promotions. This allows for flexible payment scenarios beyond pre-defined store products. It requires API keys, basket details, and checkout items, outputting the basket ID, total price, and checkout URL upon success. ```javascript const { Tebex, Package } = require('tebex-sdk-nodejs'); const checkout = Tebex.checkout.setApiKeys("project-id", "private-key"); try { // Build basket with customer information const basketBuilder = checkout.newBasketBuilder() .email("customer@example.com") .firstname("John") .lastname("Doe") .returnUrl("https://yoursite.com/cancelled") .completeUrl("https://yoursite.com/completed") .ip("192.168.1.100") // Customer IP for fraud protection .creatorCode("CREATOR123") // Optional creator code .custom({ order_id: "ORD-12345" }); // Custom tracking data // Define one-time purchase package const goldPackage = checkout.newPackageBuilder() .name("100 Gold Coins") .qty(1) .price(4.99) .oneTime() .custom({ item_type: "currency" }) .buildCheckoutItem(); // Define monthly subscription package const vipSubscription = checkout.newPackageBuilder() .name("VIP Membership") .qty(1) .price(9.99) .subscription() .monthly() .buildCheckoutItem(); // Define quarterly subscription const premiumQuarterly = checkout.newPackageBuilder() .name("Premium Quarterly Plan") .qty(1) .price(24.99) .subscription() .expiryPeriod(Package.ExpiryPeriodEnum.Month) .expiryLength(3) .buildCheckoutItem(); // Create checkout with all items const checkoutItems = [goldPackage, vipSubscription, premiumQuarterly]; checkout.checkoutRequest(basketBuilder, checkoutItems, undefined).then(basket => { console.log("Checkout created successfully"); console.log("Basket ID:", basket.ident); console.log("Total price:", basket.basePrice); console.log("Checkout URL:", basket.links.checkout); }).catch(error => { console.error("Checkout request failed:", error.message); }); } catch (error) { console.error("Failed to build checkout:", error.message); } ``` -------------------------------- ### Headless API - Create Basket Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Creates a new shopping basket for a customer. This is the first step in the checkout process, allowing you to add items. ```APIDOC ## Create Basket with Headless API ### Description Create a shopping basket for a customer with completion and cancellation URLs, optionally including user authentication for platform-specific stores. ### Method N/A (SDK Method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { Tebex } = require('tebex-sdk-nodejs'); Tebex.headless.setProject("your-public-key").then(async project => { try { // For stores requiring authentication (e.g., Minecraft, Steam) const basket = await project.createBasket( "https://yoursite.com/payment-complete", "https://yoursite.com/payment-cancelled", "PlayerUsername123" // Required for auth-enabled stores ); console.log("Basket created:", basket.getIdent()); console.log("Is user authenticated:", basket.isAuthed()); // If authentication required but not yet completed if (project.requiresUserAuth() && !basket.isAuthed()) { const authUrl = await project.getUserAuthUrl(basket, "https://yoursite.com/auth-complete"); console.log("Direct user to authenticate:", authUrl); } console.log("Basket price:", basket.getBasePrice()); } catch (error) { console.error("Basket creation failed:", error.message); } }); ``` ### Response #### Success Response (200) - **basket** (object) - A basket object representing the newly created shopping cart. - **getIdent** (function) - Returns the unique identifier for the basket. - **isAuthed** (function) - Returns a boolean indicating if the user is authenticated for this basket. - **getBasePrice** (function) - Returns the current base price of the basket. - **getLinks** (function) - Returns an object containing URLs related to the basket (e.g., checkout URL). #### Response Example ```javascript // On successful basket creation console.log("Basket created: abcdef123456"); console.log("Is user authenticated: false"); console.log("Basket price: 19.99"); // If authentication is required and not completed: // console.log("Direct user to authenticate: https://auth.tebex.io/oauth/authorize?..."); ``` ``` -------------------------------- ### Manage Basket with Tebex Checkout API (Node.js) Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Programmatically create baskets, add or remove packages, apply discounts, and retrieve basket details using the Tebex Checkout API. This function demonstrates building a basket, adding items, applying a percentage-based sale, and retrieving/modifying the basket. Requires 'tebex-sdk-nodejs' and specific API keys. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); const checkout = Tebex.checkout.setApiKeys("project-id", "private-key"); async function manageBasket() { try { // Create basket const basketBuilder = checkout.newBasketBuilder() .email("customer@example.com") .firstname("Jane") .lastname("Smith") .returnUrl("https://yoursite.com/cancel") .completeUrl("https://yoursite.com/success"); const basket = await basketBuilder.build(); console.log("Basket created:", basket.ident); // Add a package const package1 = checkout.newPackageBuilder() .name("Starter Pack") .qty(1) .price(9.99) .oneTime() .build(); const updatedBasket = await checkout.addPackage(basket, package1); console.log("Package added. New total:", updatedBasket.basePrice); // Add a sale/discount const { Sale } = require('tebex-sdk-nodejs/Checkout/lib/model/sale'); const saleBasket = await checkout.addSaleToBasket( updatedBasket, "Spring Sale", Sale.DiscountTypeEnum.Percentage, 15 // 15% off ); console.log("Sale applied. Final total:", saleBasket.basePrice); // Get basket by ID later const retrievedBasket = await checkout.getBasket(basket.ident); console.log("Retrieved basket:", retrievedBasket.ident); // Remove a specific row from basket const rowId = retrievedBasket.rows[0].id; await checkout.removeBasketRow(retrievedBasket, rowId); console.log("Basket row removed"); console.log("Final checkout URL:", saleBasket.links.checkout); } catch (error) { console.error("Basket management failed:", error.message); } } manageBasket(); ``` -------------------------------- ### Apply Coupons, Gift Cards, and Creator Codes with Tebex SDK Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Demonstrates applying and removing coupon codes, gift cards, and creator codes to a basket using the Tebex Headless API. Requires the 'tebex-sdk-nodejs' package. It takes a public key, basket details, package information, coupon codes, gift card codes, and creator codes as input, and outputs the updated basket price and checkout link. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); Tebex.headless.setProject("your-public-key").then(async project => { try { const basket = await project.createBasket( "https://yoursite.com/complete", "https://yoursite.com/cancel", "PlayerUsername" ); // Add some packages to the basket const package = await project.getPackage(12345); const basketFacade = await basket.addPackage(package, null, 1); console.log("Original price:", basketFacade.getBasePrice()); // Apply a coupon code const coupon = { code: "SUMMER2024" }; const couponBasket = await Tebex.headless.applyCoupon(basketFacade, coupon); console.log("Price after coupon:", couponBasket.basePrice); // Remove coupon if needed await Tebex.headless.removeCoupon(basketFacade); console.log("Coupon removed"); // Apply creator code for revenue share const creatorBasket = await Tebex.headless.addCreatorCode(basketFacade, "CREATOR123"); console.log("Creator code applied"); // Remove creator code const removedCreatorBasket = await Tebex.headless.removeCreatorCode(basketFacade); console.log("Creator code removed"); // Apply gift card const giftCardBasket = await Tebex.headless.addGiftCard(basketFacade, "GIFT-1234-5678-9012"); console.log("Gift card applied:", giftCardBasket.basePrice); // Remove gift card if needed const removedGiftCardBasket = await Tebex.headless.removeGiftCard( basketFacade, "GIFT-1234-5678-9012" ); console.log("Gift card removed"); console.log("Checkout at:", basketFacade.getLinks().checkout); } catch (error) { console.error("Promotion application failed:", error.message); } }); ``` -------------------------------- ### Create Basket with Headless API in Tebex SDK Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Creates a shopping basket for a customer using the Tebex Headless API. Requires completion and cancellation URLs. Optionally includes user authentication for platform-specific stores (e.g., Minecraft, Steam). Outputs basket identifier and authentication status. May provide an authentication URL if required. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); Tebex.headless.setProject("your-public-key").then(async project => { try { // For stores requiring authentication (e.g., Minecraft, Steam) const basket = await project.createBasket( "https://yoursite.com/payment-complete", "https://yoursite.com/payment-cancelled", "PlayerUsername123" // Required for auth-enabled stores ); console.log("Basket created:", basket.getIdent()); console.log("Is user authenticated:", basket.isAuthed()); // If authentication required but not yet completed if (project.requiresUserAuth() && !basket.isAuthed()) { const authUrl = await project.getUserAuthUrl(basket, "https://yoursite.com/auth-complete"); console.log("Direct user to authenticate:", authUrl); } console.log("Basket price:", basket.getBasePrice()); } catch (error) { console.error("Basket creation failed:", error.message); } }); ``` -------------------------------- ### Manage Recurring Payments with Tebex SDK for Node.js Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Demonstrates how to interact with the Tebex SDK for Node.js to manage recurring payments. This includes fetching subscription details, pausing, reactivating, updating products, and canceling subscriptions. It requires Tebex API keys and a valid subscription reference. The output includes subscription status, amounts, dates, and confirmation messages for each action. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); const checkout = Tebex.checkout.setApiKeys("project-id", "private-key"); async function manageSubscription() { try { const subscriptionRef = "sub_abc123xyz"; // Get recurring payment details const subscription = await checkout.getRecurringPayment(subscriptionRef); console.log("Subscription Reference:", subscription.reference); console.log("Status:", subscription.status.description); console.log("Amount:", subscription.amount.amount, subscription.amount.currency); console.log("Interval:", subscription.interval); console.log("Next payment:", subscription.nextPaymentDate); console.log("Created:", subscription.createdAt); // Pause subscription const pausedSubscription = await checkout.pauseRecurringPayment(subscriptionRef); console.log("Subscription paused:", pausedSubscription.status.description); // Reactivate subscription const activeSubscription = await checkout.reactivateRecurringPayment(subscriptionRef); console.log("Subscription reactivated:", activeSubscription.status.description); // Update subscription products const newPackage = checkout.newPackageBuilder() .name("Upgraded VIP Membership") .qty(1) .price(19.99) .subscription() .monthly() .build(); const updatedSubscription = await checkout.updateSubscriptionProduct( subscriptionRef, [newPackage] ); console.log("Subscription updated to new package"); console.log("New amount:", updatedSubscription.amount.amount); // Cancel subscription const cancelledSubscription = await checkout.cancelRecurringPayment(subscriptionRef); console.log("Subscription cancelled:", cancelledSubscription.status.description); console.log("Cancellation date:", cancelledSubscription.cancelledAt); } catch (error) { console.error("Subscription management failed:", error.message); } } manageSubscription(); ``` -------------------------------- ### Headless API - Add Package to Basket Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Adds pre-defined packages from your Tebex store to a customer's basket. Supports gifting, gift cards, and custom delivery variables. ```APIDOC ## Add Package to Basket ### Description Add pre-defined packages from your Tebex store to a customer's basket with support for gifting, gift cards, and custom variable data. ### Method N/A (SDK Method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { Tebex } = require('tebex-sdk-nodejs'); Tebex.headless.setProject("your-public-key").then(async project => { try { const basket = await project.createBasket( "https://yoursite.com/complete", "https://yoursite.com/cancel", "PlayerUsername" ); // Get a package by ID const package = await project.getPackage(12345); // Standard package addition with quantity await basket.addPackage(package, null, 2); // Add package with custom variable data await basket.addPackage(package, { "server_id": "127244", "player_rank": "VIP" }, 1); // Gift a package to another player await basket.addGiftedPackage(package, "RecipientUsername"); // Add gift card package with email delivery await basket.addGiftCardPackage(package, "recipient@example.com"); // Add package for Discord delivery await basket.addPackageWithDiscordDeliverable(package, "123456789012345678"); // Refresh basket to get updated totals const updatedBasket = await basket.refreshBasket(); console.log("Updated basket price:", updatedBasket.getBasePrice()); console.log("Checkout at:", updatedBasket.getLinks().checkout); } catch (error) { console.error("Failed to add package:", error.message); } }); ``` ### Response #### Success Response (200) - **updatedBasket** (object) - The basket object after the package has been added and potentially refreshed. - **getBasePrice** (function) - Returns the updated base price of the basket. - **getLinks** (function) - Returns an object containing URLs related to the basket, including the checkout URL. #### Response Example ```javascript // On successful package addition and basket refresh console.log("Updated basket price: 49.99"); console.log("Checkout at: https://checkout.tebex.io/..."); ``` ``` -------------------------------- ### Add Package to Basket using Tebex Headless API Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Adds pre-defined packages from a Tebex store to a customer's basket. Supports standard additions, gifting, gift cards, custom variables, and Discord deliverables. Requires package ID and basket object. Outputs updated basket price and checkout link. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); Tebex.headless.setProject("your-public-key").then(async project => { try { const basket = await project.createBasket( "https://yoursite.com/complete", "https://yoursite.com/cancel", "PlayerUsername" ); // Get a package by ID const package = await project.getPackage(12345); // Standard package addition with quantity await basket.addPackage(package, null, 2); // Add package with custom variable data await basket.addPackage(package, { "server_id": "127244", "player_rank": "VIP" }, 1); // Gift a package to another player await basket.addGiftedPackage(package, "RecipientUsername"); // Add gift card package with email delivery await basket.addGiftCardPackage(package, "recipient@example.com"); // Add package for Discord delivery await basket.addPackageWithDiscordDeliverable(package, "123456789012345678"); // Refresh basket to get updated totals const updatedBasket = await basket.refreshBasket(); console.log("Updated basket price:", updatedBasket.getBasePrice()); console.log("Checkout at:", updatedBasket.getLinks().checkout); } catch (error) { console.error("Failed to add package:", error.message); } }); ``` -------------------------------- ### Parse and Handle Tebex Webhooks with NodeJS Source: https://github.com/tebexio/tebex-sdk-nodejs/blob/master/README.md Shows how to set the webhook secret key, parse incoming webhook JSON data, and check for specific webhook types like validation, payment, dispute, or recurring payments. It also demonstrates how to access subject data for different webhook types. ```javascript Tebex.webhooks.setSecretKey("your-webhook-secret-key"); let webhook = Webhook.parse("your-received-webhook-json", { "HTTP-X-SIGNATURE": "your-received-signature", "REMOTE_ADDR": "webhook-originating-ip" }); // You can check for specific webhook types if (webhook.isType(WebhookType.VALIDATION_WEBHOOK)) { // respond to validation webhooks by returning their id let response = {"id": webhook.getId()} } // You can quickly check for types of webhooks with helper functions else if (webhook.isTypeOfPayment() || webhook.isTypeOfDispute()) { // subject contains data about the webhook action let subject = webhook.getSubject() as PaymentSubject; } else if (webhook.isTypeOfRecurringPayment()) { let subject = webhook.getSubject() as RecurringPaymentSubject; // etc... } ``` -------------------------------- ### Manage Tiered Categories with Tebex SDK Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Shows how to retrieve and manage tiered categories and user tiers using the Tebex Headless API. This requires the 'tebex-sdk-nodejs' package. It fetches all tiered categories, specific user tiers, and allows updating a user's tier, taking category and package IDs as input, and outputs status and messages related to tier management. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); Tebex.headless.setProject("your-public-key").then(async project => { try { // Get all tiered categories const tieredCategories = await Tebex.headless.getTieredCategories(); tieredCategories.forEach(category => { console.log(`Tiered Category: ${category.name}`); console.log(` ID: ${category.id}`); console.log(` Tiered: ${category.tiered}`); category.packages?.forEach(pkg => { console.log(` - Tier: ${pkg.name} ($${pkg.basePrice})`); }); }); // Get tiered categories for specific user (by Steam64 ID) const userTiers = await Tebex.headless.getTieredCategoriesForUser(76561198012345678); userTiers.forEach(category => { console.log(`User's tier in ${category.name}:`); if (category.activeTier) { console.log(` Active tier: ${category.activeTier.name}`); console.log(` Purchased on: ${category.activeTier.purchasedAt}`); } else { console.log(` No active tier`); } }); // Update user's tier to a new package const currentTierId = 12345; const newTierPackageId = 67890; const updateResponse = await Tebex.headless.updateTier(currentTierId, newTierPackageId); console.log("Tier update status:", updateResponse.status); console.log("Message:", updateResponse.message); } catch (error) { console.error("Tier management failed:", error.message); } }); ``` -------------------------------- ### Process Tebex Webhooks with Node.js Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt This snippet shows how to process incoming Tebex webhooks. It requires the 'tebex-sdk-nodejs' and 'express' packages. The code parses the webhook, validates its signature and source IP, and then handles different webhook types such as payment, dispute, and recurring payment events. It logs relevant information and sends a success response to Tebex. ```javascript const { Tebex, Webhook, WebhookType } = require('tebex-sdk-nodejs'); const express = require('express'); // Set your webhook secret from Tebex creator panel Tebex.webhooks.setSecretKey("your-webhook-secret-key"); const app = express(); app.use(express.json()); app.post('/webhooks/tebex', (req, res) => { try { // Parse webhook with validation const webhook = Webhook.parse(JSON.stringify(req.body), { "HTTP_X_SIGNATURE": req.headers['x-signature'], "REMOTE_ADDR": req.ip }); console.log("Webhook received:", webhook.getId()); console.log("Type:", webhook.getType()); console.log("Date:", webhook.getDate()); // Respond to validation webhook if (webhook.isType(WebhookType.VALIDATION_WEBHOOK)) { return res.json({ id: webhook.getId() }); } // Handle payment webhooks if (webhook.isTypeOfPayment()) { const subject = webhook.getSubject(); console.log("Payment received:"); console.log(" Transaction ID:", subject.transactionId); console.log(" Amount:", subject.price.amount, subject.price.currency); console.log(" Customer:", subject.customer.email); console.log(" Status:", subject.status.description); // Check if payment is complete if (webhook.isStatusComplete()) { console.log("Payment completed successfully"); // Deliver purchased items to player subject.products.forEach(product => { console.log(` Deliver: ${product.name} x${product.quantity}`); }); } } // Handle dispute webhooks if (webhook.isTypeOfDispute()) { const subject = webhook.getSubject(); console.log("Dispute received:"); console.log(" Transaction ID:", subject.transactionId); console.log(" Reason:", webhook.getType()); // Handle dispute logic } // Handle recurring payment webhooks if (webhook.isTypeOfRecurringPayment()) { const subject = webhook.getSubject(); console.log("Recurring payment event:"); console.log(" Reference:", subject.reference); console.log(" Status:", subject.status.description); console.log(" Next payment:", subject.nextPaymentDate); // Handle subscription renewal or cancellation } res.status(200).json({ success: true }); } catch (error) { console.error("Webhook processing failed:", error.message); res.status(400).json({ error: error.message }); } }); app.listen(3000, () => { console.log("Webhook server listening on port 3000"); }); ``` -------------------------------- ### Handle Payments and Refunds with Tebex Checkout API (Node.js) Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt Retrieve payment details and process refunds for completed transactions using the Tebex Checkout API. This function shows how to fetch payment information by transaction ID, check its status, list purchased products, and initiate a refund. It requires the 'tebex-sdk-nodejs' library and valid API keys. ```javascript const { Tebex } = require('tebex-sdk-nodejs'); const checkout = Tebex.checkout.setApiKeys("project-id", "private-key"); async function handlePayments() { try { // Get payment by transaction ID const payment = await checkout.getPayment("txn_abc123xyz"); console.log("Payment ID:", payment.id); console.log("Status:", payment.status.description); console.log("Amount:", payment.price.amount); console.log("Currency:", payment.price.currency); console.log("Customer:", payment.customer.email); console.log("Payment Method:", payment.paymentMethod.name); // Check payment status if (payment.status.id === 1) { // Complete console.log("Payment completed successfully"); // List purchased products payment.products.forEach(product => { console.log(` - ${product.name}: $${product.paidPrice.amount}`); }); } // Process refund if needed if (payment.status.id === 1) { const refundedPayment = await checkout.refundPayment(payment.transactionId); console.log("Refund processed"); console.log("Refund status:", refundedPayment.status.description); } } catch (error) { console.error("Payment handling failed:", error.message); } } handlePayments(); ``` -------------------------------- ### Manage Recurring Payments API Source: https://context7.com/tebexio/tebex-sdk-nodejs/llms.txt This API endpoint group provides methods to retrieve, update, pause, reactivate, and cancel subscription payments. ```APIDOC ## Manage Recurring Payments Retrieve, update, pause, reactivate, or cancel subscription payments with full lifecycle management. ### Methods - **Get Recurring Payment**: Retrieves details of a specific recurring payment. - **Pause Recurring Payment**: Pauses a recurring payment. - **Reactivate Recurring Payment**: Reactivates a paused recurring payment. - **Update Subscription Product**: Updates the products associated with a subscription. - **Cancel Recurring Payment**: Cancels a recurring payment. ### Parameters #### Path Parameters - **subscriptionRef** (string) - Required - The unique reference ID of the subscription. #### Request Body for Update Subscription Product - **products** (array) - Required - An array of `Package` objects representing the new products for the subscription. - Each `Package` object should have: - **name** (string) - Required - The name of the package. - **qty** (integer) - Required - The quantity of the package. - **price** (number) - Required - The price of the package. - **isSubscription** (boolean) - Required - Indicates if the package is a subscription. - **subscriptionInterval** (string) - Optional - The subscription interval (e.g., 'monthly', 'yearly'). ### Request Example (Get, Pause, Reactivate, Cancel) ```javascript const { Tebex } = require('tebex-sdk-nodejs'); const checkout = Tebex.checkout.setApiKeys("project-id", "private-key"); const subscriptionRef = "sub_abc123xyz"; // Get subscription const subscription = await checkout.getRecurringPayment(subscriptionRef); // Pause subscription const pausedSubscription = await checkout.pauseRecurringPayment(subscriptionRef); // Reactivate subscription const activeSubscription = await checkout.reactivateRecurringPayment(subscriptionRef); // Cancel subscription const cancelledSubscription = await checkout.cancelRecurringPayment(subscriptionRef); ``` ### Request Example (Update Subscription Product) ```javascript const { Tebex } = require('tebex-sdk-nodejs'); const checkout = Tebex.checkout.setApiKeys("project-id", "private-key"); const subscriptionRef = "sub_abc123xyz"; const newPackage = checkout.newPackageBuilder() .name("Upgraded VIP Membership") .qty(1) .price(19.99) .subscription() .monthly() .build(); const updatedSubscription = await checkout.updateSubscriptionProduct( subscriptionRef, [newPackage] ); ``` ### Response (Success) - **reference** (string) - The unique reference ID of the subscription. - **status** (object) - The current status of the subscription. - **id** (integer) - The status ID. - **description** (string) - A description of the status (e.g., 'active', 'paused', 'cancelled'). - **amount** (object) - The amount and currency of the payment. - **amount** (number) - The payment amount. - **currency** (string) - The currency code (e.g., 'USD'). - **interval** (string) - The payment interval (e.g., 'monthly'). - **nextPaymentDate** (string) - The date of the next payment (ISO 8601 format). - **createdAt** (string) - The date the subscription was created (ISO 8601 format). - **cancelledAt** (string) - The date the subscription was cancelled (ISO 8601 format), if applicable. ### Response Example (Get Subscription) ```json { "reference": "sub_abc123xyz", "status": { "id": 1, "description": "active" }, "amount": { "amount": 9.99, "currency": "USD" }, "interval": "monthly", "nextPaymentDate": "2023-12-01T00:00:00+00:00", "createdAt": "2023-11-01T10:00:00+00:00", "cancelledAt": null } ``` ### Response Example (Update Subscription) ```json { "reference": "sub_abc123xyz", "status": { "id": 1, "description": "active" }, "amount": { "amount": 19.99, "currency": "USD" }, "interval": "monthly", "nextPaymentDate": "2023-12-01T00:00:00+00:00", "createdAt": "2023-11-01T10:00:00+00:00", "cancelledAt": null } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.