### Start Creem Next.js Development Server Source: https://docs.creem.io/code/sdks/templates Starts the Next.js development server, allowing you to see your application running locally. This command should be run after all setup steps are completed. ```bash yarn dev ``` -------------------------------- ### Create Your First Product Guide Source: https://context7_llms A step-by-step guide to creating and sharing your first product on Creem. ```APIDOC ## Create Your First Product Guide ### Description This guide walks you through the process of creating your initial product within the Creem platform. ### Method POST ### Endpoint /api/products ### Parameters #### Request Body - **name** (string) - Required - The name of the product. - **description** (string) - Optional - A detailed description of the product. - **price** (object) - Required - Pricing details for the product. - **currency** (string) - Required - The currency (e.g., 'usd'). - **unit_amount** (integer) - Required - The price in cents (e.g., 1000 for $10.00). ### Request Example ```json { "name": "Ebook: Advanced SEO", "description": "A comprehensive guide to mastering search engine optimization.", "price": { "currency": "usd", "unit_amount": 2999 } } ``` ### Response #### Success Response (200) - **productId** (string) - The unique identifier for the newly created product. - **productUrl** (string) - A URL to manage the product within the Creem dashboard. #### Response Example ```json { "productId": "prod_xyz789", "productUrl": "https://dashboard.creem.io/products/prod_xyz789" } ``` ``` -------------------------------- ### Integrate Creem IO with Better Auth Source: https://docs.creem.io/getting-started/quickstart Guides on integrating Creem IO with Better Auth, including package installation, API key setup, and configuration of Better Auth with the Creem plugin. It also covers client-side configuration and creating a checkout session. ```bash npm install @creem_io/better-auth better-auth ``` ```bash # .env CREEM_API_KEY=your_api_key_here ``` ```typescript // auth.ts import { betterAuth } from 'better-auth'; import { creem } from '@creem_io/better-auth'; export const auth = betterAuth({ database: { // your database config }, plugins: [ creem({ apiKey: process.env.CREEM_API_KEY!, testMode: true, }), ], }); ``` ```typescript // lib/auth-client.ts import { createAuthClient } from 'better-auth/react'; import { creemClient } from '@creem_io/better-auth/client'; export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_APP_URL, plugins: [creemClient()], }); ``` ```typescript import { authClient } from '@/lib/auth-client'; // Client-side integration const { data, error } = await authClient.creem.createCheckout({ productId, successUrl: '/success', }); ``` -------------------------------- ### Install Next.js Adapter for Creem IO Source: https://docs.creem.io/getting-started/quickstart Installs the Next.js adapter for Creem IO using various package managers (npm, yarn, pnpm, bun). It also shows how to set the API key as an environment variable and provides examples for creating a checkout API route and a checkout button component. ```bash npm install @creem_io/nextjs yarn add @creem_io/nextjs pnpm install @creem_io/nextjs bun install @creem_io/nextjs ``` ```bash # .env CREEM_API_KEY=your_api_key_here ``` ```typescript // app/api/checkout/route.ts import { Checkout } from '@creem_io/nextjs'; export const GET = Checkout({ apiKey: process.env.CREEM_API_KEY!, testMode: true, defaultSuccessUrl: '/success', }); ``` ```typescript // app/page.tsx import { CreemCheckout } from '@creem_io/nextjs'; export default function Page() { return ( ); } ``` -------------------------------- ### Basic Webhook Setup with Creem IO SDK Source: https://docs.creem.io/code/sdks/typescript Illustrates the basic setup for handling Creem webhook events in an Express.js application. It includes initializing the Creem SDK with API keys and webhook secrets, and setting up a POST endpoint to process incoming events. ```typescript import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET!, }); // In your webhook endpoint app.post('/webhook', async (req, res) => { try { await creem.webhooks.handleEvents( req.body, // raw body as string req.headers['creem-signature'], { onCheckoutCompleted: async (data) => { console.log('Checkout completed:', data.customer?.email); }, onGrantAccess: async (context) => { // Grant user access when subscription is active/trialing/paid const userId = context.metadata?.userId; await grantUserAccess(userId); }, onRevokeAccess: async (context) => { // Revoke access when subscription is paused/expired const userId = context.metadata?.userId; await revokeUserAccess(userId); }, } ); res.status(200).send('OK'); } catch (error) { console.error('Webhook error:', error); res.status(400).send('Invalid signature'); } }); ``` -------------------------------- ### Install and Use TypeScript SDK for Creem IO Source: https://docs.creem.io/getting-started/quickstart Installs the Creem IO TypeScript SDK using npm, yarn, pnpm, or bun. It details setting the API key and demonstrates creating a checkout session, logging the checkout URL for redirection. ```bash npm install creem_io yarn add creem_io pnpm install creem_io bun install creem_io ``` ```bash # .env CREEM_API_KEY=your_api_key_here ``` ```typescript import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, testMode: true, // Set to false for production }); const checkout = await creem.checkouts.create({ productId: 'prod_abc123', successUrl: 'https://yoursite.com/success', }); // Redirect to checkout.checkout_url console.log(checkout.checkout_url); ``` -------------------------------- ### Install Creem IO Better Auth Plugin Source: https://docs.creem.io/features/checkout/checkout-api Install the necessary packages for integrating Creem IO with Better Auth. This includes the `@creem_io/better-auth` plugin and the `better-auth` library itself. ```bash npm install @creem_io/better-auth better-auth ``` -------------------------------- ### Install Creem.io Next.js Adapter Source: https://docs.creem.io/code/sdks/nextjs Installs the @creem_io/nextjs package using various package managers (npm, yarn, pnpm, bun). Ensure you have Next.js 13+ and React 18+ installed. ```bash npm install @creem_io/nextjs ``` ```bash yarn add @creem_io/nextjs ``` ```bash pnpm install @creem_io/nextjs ``` ```bash bun install @creem_io/nextjs ``` -------------------------------- ### TypeScript SDK Source: https://docs.creem.io/getting-started/quickstart Utilize the TypeScript SDK for type-safe and flexible integration with Creem.io. This section covers installation, API key setup, and creating checkout sessions. ```APIDOC ## TypeScript SDK Installation ### Description Install the TypeScript SDK for full type-safety and flexibility. ### Method Package Manager Commands ### Parameters None ### Request Example ```bash # npm npm install creem_io # yarn yarn add creem_io # pnpm pnpm install creem_io # bun bun install creem_io ``` ## API Key Configuration ### Description Add your API Key as an environment variable. ### Method Environment Variable ### Parameters - **CREEM_API_KEY** (string) - Required - Your Creem.io API key. ### Request Example ```bash # .env CREEM_API_KEY=your_api_key_here ``` ## Create Checkout Session ### Description Create a checkout session using the Creem.io TypeScript SDK. ### Method POST ### Endpoint `creem.checkouts.create` ### Parameters #### Request Body - **apiKey** (string) - Required - Your Creem.io API key. - **testMode** (boolean) - Optional - Set to `true` for test mode, `false` for production. - **productId** (string) - Required - The ID of the product for the checkout. - **successUrl** (string) - Required - The URL to redirect to after a successful checkout. ### Request Example ```ts import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, testMode: true, // Set to false for production }); const checkout = await creem.checkouts.create({ productId: 'prod_abc123', successUrl: 'https://yoursite.com/success', }); // Redirect to checkout.checkout_url console.log(checkout.checkout_url); ``` ### Response #### Success Response (200) - **checkout_url** (string) - The URL for the checkout session. #### Response Example ```json { "checkout_url": "https://checkout.creem.io/session_id" } ``` ``` -------------------------------- ### Install Creem.io SDK with Package Managers Source: https://docs.creem.io/code/sdks/typescript Installs the Creem.io SDK using various package managers including npm, yarn, pnpm, and bun. Ensure you have one of these package managers installed. ```bash npm install creem_io ``` ```bash yarn add creem_io ``` ```bash pnpm add creem_io ``` ```bash bun add creem_io ``` -------------------------------- ### Activate License with Creem IO SDK, cURL, JavaScript, and Python Source: https://docs.creem.io/features/addons/licenses Examples demonstrate how to activate a software license using different methods. The TypeScript SDK offers type safety, while cURL, JavaScript, and Python provide alternative integration options. These examples require a valid license key and instance name. ```typescript import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, testMode: true, }); const license = await creem.licenses.activate({ key: 'ABC123-XYZ456-XYZ456-XYZ456', instanceName: 'johns-macbook-pro', }); ``` ```bash curl -X POST https://test-api.creem.io/v1/licenses/activate \ -H "accept: application/json" \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "key": "ABC123-XYZ456-XYZ456-XYZ456", "instance_name": "johns-macbook-pro" }' ``` ```javascript const activateLicense = async (licenseKey, instanceName) => { const response = await fetch( 'https://test-api.creem.io/v1/licenses/activate', { method: 'POST', headers: { accept: 'application/json', 'x-api-key': 'YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ key: licenseKey, instance_name: instanceName, }), } ); return await response.json(); }; ``` ```python import requests def activate_license(license_key, instance_name): url = "https://test-api.creem.io/v1/licenses/activate" headers = { "accept": "application/json", "x-api-key": "YOUR_API_KEY", "Content-Type": "application/json" } data = { "key": license_key, "instance_name": instance_name } response = requests.post(url, json=data, headers=headers) return response.json() ``` -------------------------------- ### Storefronts API Source: https://context7_llms Create a hosted storefront page that displays all your products in one place. Start selling immediately without building your own website. ```APIDOC ## Storefronts API ### Description Manages the creation and configuration of hosted storefront pages. ### Method POST ### Endpoint /api/storefronts ### Parameters #### Request Body - **name** (string) - Required - The name of the storefront. - **productIds** (array) - Optional - An array of product IDs to feature on the storefront. ### Request Example ```json { "name": "My Online Store", "productIds": ["prod_12345", "prod_67890"] } ``` ### Response #### Success Response (200) - **storefrontId** (string) - The unique identifier for the created storefront. - **url** (string) - The URL of the hosted storefront page. #### Response Example ```json { "storefrontId": "sf_abcde", "url": "https://store.creem.io/sf_abcde" } ``` ``` -------------------------------- ### Next.js Adapter Source: https://docs.creem.io/features/customer-portal Guides users on setting up the customer portal route and using the CreemPortal component in a Next.js application. ```APIDOC ## Next.js Customer Portal Integration ### Description This section details how to integrate the customer portal into your Next.js application using the `@creem_io/nextjs` adapter. ### Setup **Step 1: Create the Portal Route** Create a route file (e.g., `app/portal/route.ts`) to handle portal requests. ```typescript // app/portal/route.ts import { Portal } from '@creem_io/nextjs'; export const GET = Portal({ apiKey: process.env.CREEM_API_KEY!, testMode: process.env.NODE_ENV !== 'production', }); ``` **Step 2: Use the Component** Use the `CreemPortal` component to render a button that links to the customer portal. ```tsx // components/ManageSubscriptionButton.tsx 'use client'; import { CreemPortal } from '@creem_io/nextjs'; export function ManageSubscriptionButton({ customerId, }: { customerId: string }) { return ( ); } ``` ### Further Reading - [Next.js Adapter Documentation](/code/sdks/nextjs) ``` -------------------------------- ### Better Auth Integration Source: https://docs.creem.io/getting-started/quickstart Integrate Creem.io with Better Auth for seamless authentication and billing. This section details installation, API key configuration, and client-side setup. ```APIDOC ## Better Auth Installation ### Description Integrate Creem with Better Auth for seamless authentication and billing. ### Method Package Manager Commands ### Parameters None ### Request Example ```bash npm install @creem_io/better-auth better-auth ``` ## API Key Configuration ### Description Add your API Key as an environment variable. ### Method Environment Variable ### Parameters - **CREEM_API_KEY** (string) - Required - Your Creem.io API key. ### Request Example ```bash # .env CREEM_API_KEY=your_api_key_here ``` ## Configure Better Auth with Creem Plugin ### Description Configure Better Auth with the Creem plugin. ### Method Server-side Configuration ### Parameters #### Plugin Configuration - **apiKey** (string) - Required - Your Creem.io API key. - **testMode** (boolean) - Optional - Set to `true` for test mode, `false` for production. ### Request Example ```ts // auth.ts import { betterAuth } from 'better-auth'; import { creem } from '@creem_io/better-auth'; export const auth = betterAuth({ database: { // your database config }, plugins: [ creem({ apiKey: process.env.CREEM_API_KEY!, testMode: true, }), ], }); ``` ## Client Configuration for Better Auth ### Description Configure the Better Auth client for frontend integration. ### Method Client-side Setup ### Parameters #### Client Configuration - **baseURL** (string) - Required - The base URL of your application. ### Request Example ```ts // lib/auth-client.ts import { createAuthClient } from 'better-auth/react'; import { creemClient } from '@creem_io/better-auth/client'; export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_APP_URL, plugins: [creemClient()], }); ``` ## Create Checkout via Better Auth Client ### Description Create a checkout session using the Better Auth client-side integration. ### Method POST ### Endpoint `authClient.creem.createCheckout` ### Parameters #### Request Body - **productId** (string) - Required - The ID of the product to checkout. - **successUrl** (string) - Required - The URL to redirect to after a successful checkout. ### Request Example ```ts import { authClient } from '@/lib/auth-client'; // Client-side integration const { data, error } = await authClient.creem.createCheckout({ productId, successUrl: '/success', }); ``` ``` -------------------------------- ### Quick Start: Initialize Creem SDK and Basic Operations Source: https://docs.creem.io/code/sdks/typescript Initializes the Creem SDK with API keys and demonstrates basic operations such as retrieving a product and creating a checkout session. Requires Creem API key and optionally a webhook secret to be set as environment variables. ```typescript import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET, // optional, for webhooks testMode: false, // set to true for test mode }); // Retrieve a product const product = await creem.products.get({ productId: 'prod_7CIbZEZnRC5DWibmoOboOu', }); console.log(product); // Create a checkout session const checkout = await creem.checkouts.create({ productId: 'prod_xxxxx', successUrl: 'https://yourapp.com/success', metadata: { userId: 'user_123', }, }); console.log(checkout.checkoutUrl); // Redirect user to this URL ``` -------------------------------- ### Manage Products with Creem.io TypeScript SDK Source: https://docs.creem.io/code/sdks/typescript Provides examples for listing, retrieving, creating, and searching products using the Creem.io TypeScript SDK. Product creation requires details like name, description, price, currency, billing type, and billing period. ```typescript // List products const products = await creem.products.list({ page: 1, limit: 10, }); // Get a product const product = await creem.products.get({ productId: 'prod_7CIbb...', }); // Create a product creem.products.create({ name: 'Test Product', description: 'Test Product Description', price: 1000, // In cents currency: 'USD', billingType: 'recurring', billingPeriod: 'every-month', }); // Search products const products = await creem.products.list({ page: 1, limit: 10, }); ``` -------------------------------- ### Set Up Environment Variables for Creem Template Source: https://docs.creem.io/code/sdks/templates Copies the example environment file to `.env` and instructs the user to fill in the necessary variables. This step is crucial for configuring the application's connection to Creem and other services. ```bash cp .env.example .env # Edit .env and fill in the required variables ``` -------------------------------- ### Install Better Auth Creem Plugin (bun) Source: https://docs.creem.io/code/sdks/better-auth Installs the Better Auth Creem plugin using bun. Bun is a fast JavaScript runtime and package manager. Ensure bun is installed in your environment. ```bash bun install @creem_io/better-auth ``` -------------------------------- ### Install Project Dependencies for Creem Next.js Template Source: https://docs.creem.io/code/sdks/templates Installs project dependencies using various package managers (Yarn, npm, pnpm, Bun). Choose the command corresponding to your preferred package manager. ```bash yarn install ``` ```bash npm install ``` ```bash pnpm install ``` ```bash bun install ``` -------------------------------- ### REST API Source: https://docs.creem.io/features/customer-portal Provides instructions for using the REST API to generate customer portal links, including cURL and JavaScript examples. ```APIDOC ## REST API Customer Portal ### Description This section details how to generate a customer portal link using the Creem REST API. ### Endpoint `POST /v1/customers/billing` ### Parameters #### Request Body - **customer_id** (string) - Required - The ID of the customer for whom to create the portal link. ### Request Example (cURL) ```bash curl -X POST https://api.creem.io/v1/customers/billing \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ \ "customer_id": "cust_abc123" \ }' ``` ### Response #### Success Response (200) - **customer_portal_link** (string) - The URL for the customer portal. #### Response Example ```json { "customer_portal_link": "https://creem.io/my-orders/login/xxxxxxxxxx" } ``` ### JavaScript Example ```javascript const response = await fetch('https://api.creem.io/v1/customers/billing', { method: 'POST', headers: { 'x-api-key': 'YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ customer_id: 'cust_abc123', }), }); const data = await response.json(); console.log(data.customer_portal_link); ``` ### Important Note If you're in test mode, use `https://test-api.creem.io` instead of `https://api.creem.io`. ### Further Reading - [API Reference](/api-reference/endpoint/create-customer-billing) - [Test Mode](/getting-started/test-mode) ``` -------------------------------- ### GET /v1/products/search Source: https://docs.creem.io/api-reference/endpoint/search-products Retrieves a list of all products available in the Creem platform. This endpoint supports pagination and filtering. ```APIDOC ## GET /v1/products/search ### Description Lists all products available in the Creem platform. This endpoint supports pagination and filtering. ### Method GET ### Endpoint /v1/products/search ### Parameters #### Query Parameters - **page_number** (number) - Optional - The page number for pagination. - **page_size** (number) - Optional - The number of items to return per page. #### Header Parameters - **x-api-key** (string) - Required - Your Creem API key for authentication. ### Request Example ```json { "query": { "page_number": 1, "page_size": 10 }, "headers": { "x-api-key": "YOUR_API_KEY" } } ``` ### Response #### Success Response (200) - **items** (array) - A list of product objects. - **pagination** (object) - Pagination details for the product list. #### Response Example ```json { "items": [ { "id": "prod_12345", "mode": "test", "object": "product", "name": "Basic Plan", "description": "A basic subscription plan.", "image_url": "https://example.com/image.jpg", "features": [ { "name": "Feature A", "description": "Description for Feature A" } ], "price": 1000, "currency": "USD", "billing_type": "recurring", "billing_period": "every-month", "status": "active", "tax_mode": "inclusive", "tax_category": "saas", "product_url": "https://creem.io/product/prod_123123123123", "default_success_url": "https://example.com/?status=successful", "created_at": "2023-01-01T00:00:00Z", "updated_at": "2023-01-01T00:00:00Z" } ], "pagination": { "total_items": 100, "total_pages": 10, "current_page": 1, "current_page_size": 10 } } ``` ``` -------------------------------- ### Install Better Auth Creem Plugin (pnpm) Source: https://docs.creem.io/code/sdks/better-auth Installs the Better Auth Creem plugin using pnpm. This is an alternative package manager. Ensure pnpm is installed and configured in your project. ```bash pnpm add @creem_io/better-auth ``` -------------------------------- ### Install Better Auth Creem Plugin (npm) Source: https://docs.creem.io/code/sdks/better-auth Installs the Better Auth Creem plugin using npm. Ensure you have Node.js and npm installed. This command adds the necessary package to your project's dependencies. ```bash npm install @creem_io/better-auth ``` -------------------------------- ### Handle Creem IO Webhooks in Hono Source: https://docs.creem.io/code/sdks/typescript Provides an example of integrating Creem IO webhooks with the Hono framework. It shows how to correctly retrieve the request body and signature headers for secure event processing. ```typescript app.post("/webhook", async (c) => { try { const body = await c.req.text(); const signature = c.req.header("creem-signature"); await creem.webhooks.handleEvents(body, signature, { onCheckoutCompleted: async (data) => { // Handle checkout }, }); return c.text("OK"); } catch (error) { return c.text("Invalid signature", 400); } }); ``` -------------------------------- ### Creem IO SDK Error Handling Example Source: https://docs.creem.io/code/sdks/typescript Demonstrates robust error handling when interacting with the Creem IO SDK. It shows how to wrap API calls in try-catch blocks to gracefully manage potential failures during operations like retrieving product information. ```typescript try { const product = await creem.products.get({ productId: 'prod_xxxxx', }); } catch (error) { console.error('Failed to retrieve product:', error); // Handle error appropriately } ``` -------------------------------- ### Next.js Integration Source: https://docs.creem.io/getting-started/quickstart Integrate Creem.io with Next.js using the provided adapter for built-in routes and components. This includes installation, API key configuration, and setting up checkout routes and buttons. ```APIDOC ## Next.js Adapter Installation ### Description Install the Next.js adapter for the fastest integration with built-in routes and components. ### Method Package Manager Commands ### Parameters None ### Request Example ```bash # npm npm install @creem_io/nextjs # yarn yarn add @creem_io/nextjs # pnpm pnpm install @creem_io/nextjs # bun bun install @creem_io/nextjs ``` ## API Key Configuration ### Description Add your API Key as an environment variable. ### Method Environment Variable ### Parameters - **CREEM_API_KEY** (string) - Required - Your Creem.io API key. ### Request Example ```bash # .env CREEM_API_KEY=your_api_key_here ``` ## Create Checkout API Route ### Description Create a checkout API route in your Next.js application. ### Method GET ### Endpoint `/api/checkout/route.ts` ### Parameters #### Request Body - **apiKey** (string) - Required - Your Creem.io API key. - **testMode** (boolean) - Optional - Set to `true` for test mode, `false` for production. - **defaultSuccessUrl** (string) - Required - The URL to redirect to after a successful checkout. ### Request Example ```ts // app/api/checkout/route.ts import { Checkout } from '@creem_io/nextjs'; export const GET = Checkout({ apiKey: process.env.CREEM_API_KEY!, testMode: true, defaultSuccessUrl: '/success', }); ``` ## Checkout Button Component ### Description Add a checkout button to your page using the `CreemCheckout` component. ### Method React Component ### Endpoint `/app/page.tsx` ### Parameters #### Props - **productId** (string) - Required - The ID of the product to checkout. ### Request Example ```tsx // app/page.tsx import { CreemCheckout } from '@creem_io/nextjs'; export default function Page() { return ( ); } ``` ``` -------------------------------- ### Install Better Auth Creem Plugin (yarn) Source: https://docs.creem.io/code/sdks/better-auth Installs the Better Auth Creem plugin using yarn. This command adds the package to your project's dependencies if you are using yarn as your package manager. ```bash yarn add @creem_io/better-auth ``` -------------------------------- ### Create Checkout Session Handler (TypeScript) Source: https://docs.creem.io/code/sdks/nextjs Creates a GET route handler for issuing checkout sessions. Requires CREEM_API_KEY and a default success URL. Operates in test mode if the environment is not production. ```typescript // app/checkout/route.ts export const GET = Checkout({ apiKey: process.env.CREEM_API_KEY!, defaultSuccessUrl: '/success', testMode: process.env.NODE_ENV !== 'production', }); ``` -------------------------------- ### Clone Creem Next.js Template Repository Source: https://docs.creem.io/code/sdks/templates This command clones the Creem Next.js template repository from GitHub to your local machine. It's the first step to start using the template for your project. ```bash git clone https://github.com/armitage-labs/creem-template.git cd creem-template ``` -------------------------------- ### Generate Customer Portal Link via REST API Source: https://docs.creem.io/features/customer-portal This example demonstrates how to generate a customer portal link using the Creem REST API with cURL and JavaScript. It requires an API key and a customer ID, and returns a JSON object containing the customer portal link. Use the test API endpoint for test mode. ```bash curl -X POST https://api.creem.io/v1/customers/billing \ -H "x-api-key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "cust_abc123" }' ``` ```json { "customer_portal_link": "https://creem.io/my-orders/login/xxxxxxxxxx" } ``` ```javascript const response = await fetch('https://api.creem.io/v1/customers/billing', { method: 'POST', headers: { 'x-api-key': 'YOUR_API_KEY', 'Content-Type': 'application/json', }, body: JSON.stringify({ customer_id: 'cust_abc123', }), }); const data = await response.json(); console.log(data.customer_portal_link); ``` -------------------------------- ### Handle Transactions with Creem IO SDK Source: https://docs.creem.io/code/sdks/typescript Provides examples for retrieving a single transaction by its ID and listing multiple transactions, with an option to filter by customer ID. It shows how to interact with the transactions module. ```typescript const transaction = await creem.transactions.get({ transactionId: 'txn_xxxxx', }); const transactions = await creem.transactions.list({ customerId: 'cust_xxxxx', // Optional: filter by customer page: 1, limit: 50, }); ``` -------------------------------- ### Manage User Access via Creem.io TypeScript SDK Webhooks Source: https://docs.creem.io/features/subscriptions/introduction This TypeScript example shows how to integrate Creem.io webhooks into an Express.js application to manage user access. It utilizes the `creem_io` SDK to handle incoming webhook events, calling `onGrantAccess` for positive subscription statuses and `onRevokeAccess` for negative ones. Requires `CREEM_API_KEY` and `CREEM_WEBHOOK_SECRET` environment variables. ```typescript // app/api/webhook/route.ts import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET!, }); app.post('/webhook', async (req, res) => { try { await creem.webhooks.handleEvents( req.body, req.headers['creem-signature'], { onGrantAccess: async ({ reason, customer, product, metadata }) => { // Called for: subscription.active, subscription.trialing, subscription.paid const userId = metadata?.userId as string; await db.user.update({ where: { id: userId }, data: { subscriptionActive: true, subscriptionTier: product.name, }, }); console.log(`Granted ${reason} to ${customer.email}`); }, onRevokeAccess: async ({ reason, customer, metadata }) => { // Called for: subscription.paused, subscription.expired const userId = metadata?.userId as string; await db.user.update({ where: { id: userId }, data: { subscriptionActive: false }, }); console.log(`Revoked access (${reason}) from ${customer.email}`); }, } ); res.status(200).send('OK'); } catch (error) { res.status(400).send('Invalid signature'); } }); ``` -------------------------------- ### Next.js SDK Usage for One Time Payments Source: https://docs.creem.io/features/one-time-payment Example of how to use the Creem Next.js SDK to create a buy button for one-time payments. ```APIDOC ## CreemCheckout Component (Next.js) ### Description Use the `CreemCheckout` component to easily integrate a "Buy Now" button for one-time payments in your Next.js application. ### Method Client-side Component ### Endpoint N/A (Component-based) ### Parameters #### Props - **productId** (string) - Required - The ID of the one-time product. - **metadata** (object) - Optional - Additional key-value pairs to associate with the checkout session. - **customerId** (string) - Example metadata field. - **source** (string) - Example metadata field. ### Request Example ```tsx 'use client'; // Optional: Works with server components import { CreemCheckout } from '@creem_io/nextjs'; export function BuyButton() { return ( ); } ``` ### Response #### Success Response (200) N/A (Handled by the SDK) #### Response Example N/A ``` -------------------------------- ### Better Auth Integration for One Time Payments Source: https://docs.creem.io/features/one-time-payment Example of using a custom `authClient` to create a one-time payment checkout session. ```APIDOC ## `authClient.creem.createCheckout` (Better Auth) ### Description This example shows how to use a pre-configured `authClient` to initiate a one-time payment checkout. ### Method Client-side / SDK Function ### Endpoint N/A (SDK Function) ### Parameters #### `createCheckout` Options - **productId** (string) - Required - The ID of the one-time product. - **successUrl** (string) - Required - The URL to redirect to after a successful payment. - **metadata** (object) - Optional - Additional data to include with the checkout. - **source** (string) - Example metadata field. ### Request Example ```typescript "use client"; import { authClient } from "@/lib/auth-client"; export function BuyButton({ productId }: { productId: string }) { const handleCheckout = async () => { const { data, error } = await authClient.creem.createCheckout({ productId, successUrl: "/thank-you", metadata: { source: "web" }, }); if (data?.url) { window.location.href = data.url; } }; return ( ); } ``` ### Response #### Success Response - **data.url** (string) - The checkout URL if the request is successful. #### Response Example ```json { "data": { "url": "https://checkout.creem.io/ch_..." }, "error": null } ``` ``` -------------------------------- ### Creem API Authentication Header Source: https://docs.creem.io/api-reference/introduction Example of the required 'x-api-key' header for authenticating API requests. The value should be your unique API key. ```json { "headers": { "x-api-key": "creem_123456789" } } ``` -------------------------------- ### TypeScript SDK Usage for One Time Payments Source: https://docs.creem.io/features/one-time-payment Example of how to use the Creem TypeScript SDK to create a one-time payment checkout session. ```APIDOC ## TypeScript SDK - Create Checkout Session ### Description This example demonstrates how to initialize the Creem TypeScript SDK and create a checkout session for a one-time payment. ### Method Server-side / SDK Function ### Endpoint N/A (SDK Function) ### Parameters #### Initialization Options - **apiKey** (string) - Required - Your Creem API key. - **testMode** (boolean) - Required - Set to `true` for test mode, `false` for production. #### `creem.checkouts.create` Options - **productId** (string) - Required - The ID of the one-time product. - **successUrl** (string) - Required - The URL to redirect to after a successful payment. - **metadata** (object) - Optional - Additional data to include with the checkout. - **customerId** (string) - Example metadata field. - **source** (string) - Example metadata field. ### Request Example ```typescript import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, testMode: process.env.NODE_ENV !== 'production', }); // Create a one-time payment checkout session const checkout = await creem.checkouts.create({ productId: 'prod_YOUR_PRODUCT_ID', successUrl: 'https://yoursite.com/success', metadata: { customerId: 'cust_123', source: 'web', }, }); // Redirect to the checkout URL console.log(checkout.checkout_url); ``` ### Response #### Success Response (200) - **checkout_url** (string) - The URL for the customer to complete payment. #### Response Example ```json { "checkout_url": "https://checkout.creem.io/ch_..." } ``` ``` -------------------------------- ### GET /v1/discounts Source: https://docs.creem.io/api-reference/endpoint/get-discount-code Retrieves details for a specific discount code. You can query by either `discount_id` or `discount_code`. The response includes information such as the discount's status, type, amount, expiration date, and redemption limits. ```APIDOC ## GET /v1/discounts ### Description Retrieves discount code details by ID or code. Check usage limits, expiration, and discount amount. ### Method GET ### Endpoint /v1/discounts ### Parameters #### Query Parameters - **discount_id** (string) - Optional - The unique identifier of the discount (provide either discount_id OR discount_code). - **discount_code** (string) - Optional - The unique discount code (provide either discount_id OR discount_code). #### Header Parameters - **x-api-key** (string) - Required - Your API key for authentication. ### Request Example ``` GET /v1/discounts?discount_code=HOLIDAY2024 HTTP/1.1 Host: api.creem.io X-API-Key: YOUR_API_KEY ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the discount. - **mode** (string) - Environment mode (e.g., 'test', 'prod'). - **object** (string) - Type of the object, 'discount'. - **status** (string) - The status of the discount (e.g., 'active', 'expired'). - **name** (string) - The name of the discount. - **code** (string) - The discount code. - **type** (string) - The type of discount ('percentage' or 'fixed'). - **amount** (number) - The discount amount. - **currency** (string) - The currency (required if type is 'fixed'). - **percentage** (number) - The discount percentage (applicable if type is 'percentage'). - **expiry_date** (string) - The expiry date of the discount (ISO 8601 format). - **max_redemptions** (number) - Maximum number of redemptions allowed. - **duration** (string) - Duration type ('forever', 'once', 'repeating'). - **duration_in_months** (number) - Number of months for repeating duration. - **applies_to_products** (array[string]) - List of product IDs the discount applies to. - **redeem_count** (number) - Number of times the discount has been redeemed. #### Response Example ```json { "id": "disc_abc123", "mode": "prod", "object": "discount", "status": "active", "name": "Holiday Sale", "code": "HOLIDAY2024", "type": "percentage", "amount": 20, "currency": null, "percentage": 15, "expiry_date": "2024-12-31T23:59:59Z", "max_redemptions": 100, "duration": "repeating", "duration_in_months": 6, "applies_to_products": [ "prod_123", "prod_456" ], "redeem_count": 15 } ``` ``` -------------------------------- ### Generate and Migrate Database Schema for Better Auth Source: https://docs.creem.io/code/sdks/better-auth Generates the necessary database schema for subscription persistence and applies the migrations. Requires the Better Auth CLI to be installed. ```bash npx @better-auth/cli generate npx @better-auth/cli migrate ``` -------------------------------- ### Checkout Session Creation Response (JSON) Source: https://docs.creem.io/features/checkout/checkout-api This is an example of the JSON response received after successfully creating a checkout session via the Creem.io REST API. It includes the unique ID of the checkout session and the URL where the user can complete the payment. ```json { "id": "ch_1QyIQDw9cbFWdA1ry5Qc6I", "checkout_url": "https://checkout.creem.io/ch_1QyIQDw9cbFWdA1ry5Qc6I", "product_id": "prod_YOUR_PRODUCT_ID", "status": "pending" } ``` -------------------------------- ### Initialize TypeScript SDK with Test Mode Source: https://docs.creem.io/getting-started/test-mode Set up the Creem TypeScript SDK for Test Mode by passing `testMode: true` to the `createCreem` function. This isolates SDK interactions to the test environment. An example demonstrates creating a checkout within this test configuration. For dynamic environment handling, use `process.env.NODE_ENV`. ```typescript import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, testMode: true, // Enable test mode }); const checkout = await creem.checkouts.create({ productId: 'prod_abc123', successUrl: 'https://yoursite.com/success', }); ``` ```typescript const creem = createCreem({ apiKey: process.env.CREEM_API_KEY!, testMode: process.env.NODE_ENV !== 'production', }); ``` -------------------------------- ### Create Checkout Session: Seat-Based Billing (TypeScript) Source: https://docs.creem.io/guides/create-checkout-session This example demonstrates how to configure a checkout session for seat-based billing, allowing you to charge for multiple units or seats in a single transaction. This is suitable for subscription models or team-based access. It requires the Creem SDK and a valid `productId`. ```typescript const checkout = await creem.checkouts.create({ productId: 'prod_YOUR_PRODUCT_ID', units: 5, // Charge for 5 seats }); ``` -------------------------------- ### Create Checkout Session: Track Payments with Custom IDs (TypeScript) Source: https://docs.creem.io/guides/create-checkout-session This code example shows how to create a checkout session and associate it with custom tracking identifiers. This is useful for linking payments to your internal systems, such as order IDs or user IDs. It requires the Creem SDK and a valid `productId`. ```typescript const checkout = await creem.checkouts.create({ productId: 'prod_YOUR_PRODUCT_ID', requestId: 'order_12345', metadata: { userId: 'internal_user_id', source: 'marketing_campaign', }, }); ``` -------------------------------- ### Handle Subscription Webhooks in TypeScript Source: https://docs.creem.io/features/subscriptions/introduction Implement a webhook endpoint in TypeScript to receive and process events from Creem.io. This example demonstrates signature verification using crypto and logic for granting/revoking user access based on subscription status changes. It requires 'creem-webhook-secret' environment variable for signature verification. ```typescript import crypto from 'crypto'; async function verifySignature(payload: string, signature: string) { const computed = crypto .createHmac('sha256', process.env.CREEM_WEBHOOK_SECRET!) .update(payload) .digest('hex'); return computed === signature; } app.post('/webhook', async (req, res) => { const signature = req.headers['creem-signature']; const payload = JSON.stringify(req.body); if (!verifySignature(payload, signature)) { return res.status(401).send('Invalid signature'); } const { eventType, object } = req.body; // Grant access events if ( [ 'subscription.active', 'subscription.trialing', 'subscription.paid', ].includes(eventType) ) { const userId = object.metadata?.referenceId; const customer = object.customer; const product = object.product; await db.user.update({ where: { id: userId }, data: { subscriptionActive: true, subscriptionTier: product.name, }, }); console.log(`Granted access to ${customer.email}`); } // Revoke access events if (['subscription.paused', 'subscription.expired'].includes(eventType)) { const userId = object.metadata?.referenceId; const customer = object.customer; await db.user.update({ where: { id: userId }, data: { subscriptionActive: false }, }); console.log(`Revoked access from ${customer.email}`); } res.status(200).send('OK'); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.