### Install Common Ninja App Source: https://docs.commoninja.com/getting-started/quick-start Command to create a new NodeJS project using the Common Ninja CLI. This command bootstraps a new project with a default server template. ```bash npx @commonninja/create-nindo-app project-name ``` -------------------------------- ### Configure Environment Variables Source: https://docs.commoninja.com/getting-started/quick-start Example `.env` file for setting up Common Ninja application credentials and server port. These variables are essential for the application to connect to the Common Ninja platform. ```javascript # Env PORT=4000 # Common Ninja App COMMONNINJA_APP_ID= COMMONNINJA_APP_SECRET= ``` -------------------------------- ### Start Development Server Source: https://docs.commoninja.com/getting-started/quick-start Command to start the development server using Docker Compose. This command ensures the application environment is running correctly. ```bash ~ docker compose up ``` -------------------------------- ### 200 OK Response Example Source: https://docs.commoninja.com/apis/e-commerce/products/get-products-images Example of a successful response when fetching product images. ```javascript { "success": true, "message": "Product images retrieved successfully.", "data": { "limit": 10, "nextPage": 2, "page": 1, "pages": 5, "prevPage": null, "total": 45, "items": [ { "id": "img_123", "productId": "prod_abc", "url": "https://example.com/images/product1.jpg", "altText": "Product Image 1", "isDefault": true, "createdAt": "2023-01-01T10:00:00Z", "updatedAt": "2023-01-01T10:00:00Z" }, { "id": "img_456", "productId": "prod_abc", "url": "https://example.com/images/product2.png", "altText": "Product Image 2", "isDefault": false, "createdAt": "2023-01-01T10:05:00Z", "updatedAt": "2023-01-01T10:05:00Z" } ] } } ``` -------------------------------- ### Setup Local HTTPS for Webhook Testing Source: https://docs.commoninja.com/getting-started/quick-start Provides instructions for setting up a local HTTPS environment using Docker Compose to test webhook integrations. This is necessary because webhooks often require secure connections. ```Bash docker compose -f docker-compose.https.yml up ``` -------------------------------- ### 200 OK Response Example Source: https://docs.commoninja.com/apis/user/get-user-details Example JSON response for a successful retrieval of user details. ```javascript { success: true, message: "User details retrieved successfully", data: { platformUserId: "user123", platform: "commonninja", email: "user@example.com", name: "John Doe", subscriptionId: "sub456", plan: { id: "plan789", name: "Premium" } } } ``` -------------------------------- ### Example Proxy Request using cURL Source: https://docs.commoninja.com/apis/proxy Demonstrates how to use cURL to make a GET request to the Proxy API to retrieve Shopify gift cards. This example includes the necessary authorization headers and the specific path for the Shopify API. ```curl curl -X GET "https://api.commoninja.com/integrations/api/v1/proxy/admin/api/2022-04/gift_cards.json" \ -H "Authorization: {cn_token}" \ -H "X-CN-User-Access-Token: {access_token}" ``` -------------------------------- ### Install CommonNinja Node SDK Source: https://docs.commoninja.com/getting-started/sdk-libraries Installs the CommonNinja Node.js SDK using npm or yarn. This is the first step to integrate CommonNinja services into your application. ```bash npm i -S @commonninja/node-sdk yarn add @commonninja/node-sdk ``` -------------------------------- ### Successful Product Image Response Source: https://docs.commoninja.com/apis/e-commerce/products/get-product-image Example structure for a successful response when retrieving a product image. ```javascript { success: boolean; message: string; data: IProductImage; } ``` -------------------------------- ### Fetch Products using SDK Method Source: https://docs.commoninja.com/getting-started/quick-start Demonstrates fetching product data directly from the Common Ninja API using a specific SDK method. This approach allows for more targeted data retrieval compared to the general API proxy. ```TypeScript import { Request, Response, NextFunction } from 'express'; import { getCommonNinjaClient } from './commonNinjaClient'; // Assuming this is how you get the client router.get('/api/products', async (req, res, next) => { const client = getCommonNinjaClient(req); const data = await client.ecommerce.getProducts(); res.send(data); }); ``` -------------------------------- ### API Response Structure Source: https://docs.commoninja.com/apis/e-commerce/categories/get-categories Example TypeScript interface for a successful API response when fetching categories. ```typescript interface ICategory { // Properties of a category would be defined here, e.g.: // id: string; // name: string; // slug: string; } interface GetCategoriesResponse { success: boolean; message: string; data: { limit?: number; nextPage?: number | string | null; page?: number | string | null; pages?: number; prevPage?: number | string | null; total?: number; items: ICategory[]; } } ``` -------------------------------- ### Connect User to Platform via SDK Source: https://docs.commoninja.com/getting-started/quick-start Handles user redirection to platform authentication flows using the `getConnectUrl` SDK method. It initializes a Common Ninja client and redirects the user to the generated authentication URL, facilitating the integration process. ```TypeScript import { Request, Response } from 'express'; import { getCommonNinjaClient } from './commonNinjaClient'; // Assuming this is how you get the client // Authentication router.get('/connect', async (req: Request, res: Response) => { // Get a new Common Ninja instance const client = getCommonNinjaClient(req); // Get authentication url for platform const url = client.auth.getConnectUrl(); // Redirect to authentication url res.redirect(url); }); ``` -------------------------------- ### NodeJS Server Entry File (app.ts) Source: https://docs.commoninja.com/getting-started/quick-start The main entry file for a typical NodeJS server application using Express. It sets up middleware for parsing cookies and request bodies, and starts the server on a specified port. ```typescript import 'dotenv/config'; import express from 'express'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import router from './routes'; const port = parseInt(process.env.PORT || '3000'); const app = express(); // Parse cookies app.use(cookieParser()); // Parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // Parse application/json app.use( bodyParser.json({ limit: '50mb', }) ); app.use('/', router); // Start server app.listen(port, () => { console.log(`Running at http://localhost:${port}`); }); module.exports = app; ``` -------------------------------- ### 200 OK Response Structure Source: https://docs.commoninja.com/apis/e-commerce/orders/get-orders Example structure for a successful (200 OK) API response when retrieving shop orders. This JSON object includes a success status, a message, and a data object containing pagination details and an array of IOrder items. ```javascript { success: boolean; message: string; data: { limit?: number; nextPage?: number | string | null; page?: number | string | null; pages?: number; prevPage?: number | string | null; total?: number; items: IOrder[]; } } ``` -------------------------------- ### Common Ninja Pricing Plan Configuration Source: https://docs.commoninja.com/getting-started/payments Guide to creating and configuring pricing plans, including naming, descriptions, activation status, free plan options, prices, billing periods, and feature assignments. ```APIDOC Pricing Plan Configuration: Create New Plan: - Plan Name: string - Description: string - Active Status: boolean (toggle) - Free Plan: boolean Add Price to Plan: - Price Name: string - Price Amount: number - Billing Period: string (e.g., 'monthly', 'yearly') Connect Payment Providers: - Supported Providers: PayPal, Stripe, Shopify (requires prior integration) Edit Plan Features: - Assign or modify feature values specific to the plan. Plan Settings: - Redirect URL (Success): URL for successful checkout. - Redirect URL (Failure): URL for failed checkout. ``` -------------------------------- ### CommonNinja Node SDK Usage Examples Source: https://docs.commoninja.com/getting-started/sdk-libraries Demonstrates common operations using the CommonNinja Node.js SDK, including initializing the client, fetching shop data (products, orders, customers), generating authentication URLs, and validating webhooks. Requires environment variables for authentication. ```javascript const client = new CommonNinja({ appId: process.env.CN_APP_ID, appSecret: process.env.CN_APP_SECRET, accessToken: req.query.token, env: CommonNinja.envs.production, }); // Get shop products, filter by category const { data, success, message } = await client.ecommerce.getProducts({ category: '1', }); // Get shop orders const { data, success, message } = await client.ecommerce.getOrders(); // Get shop customers with pagination parameters const { data, success, message } = await client.ecommerce.getCustomers({ limit: 5, page: 1, }); // Get connect to platform screen url const connectUrl = client.auth.getConnectUrl(); // Validate an incoming webhook message from Common Ninja client.webhooks.validateWebhook(req); ``` -------------------------------- ### Common Ninja Client Initialization Source: https://docs.commoninja.com/getting-started/quick-start Function to initialize the Common Ninja client within a NodeJS application. It retrieves credentials from environment variables and configures the client with necessary parameters like `appId`, `appSecret`, and `accessToken`. ```typescript const { COMMONNINJA_APP_ID, COMMONNINJA_APP_SECRET } = process.env; function getCommonNinjaClient(req: Request) { if (!COMMONNINJA_APP_ID || !COMMONNINJA_APP_SECRET) { throw new Error('Missing Common Ninja app ID or secret key.'); } // Create a new Common Ninja instance return new CommonNinja({ appId: COMMONNINJA_APP_ID, appSecret: COMMONNINJA_APP_SECRET, accessToken: req.query.token as string, env: CommonNinja.envs.production, logs: true, }); } ``` -------------------------------- ### Handle and Validate Webhooks Source: https://docs.commoninja.com/getting-started/quick-start Accepts webhook messages from Common Ninja's supported platforms and validates their authenticity using the SDK. It logs the validated message and sends a success response, ensuring secure and reliable event handling. ```TypeScript import { Request, Response } from 'express'; import { getCommonNinjaClient } from './commonNinjaClient'; // Assuming this is how you get the client // Validate and handle Common Ninja's webhooks router.post('/webhooks', async (req: Request, res: Response) => { try { const client = getCommonNinjaClient(req); // Validate webhook message source const validated = client.webhooks.validateWebhook(req); if (!validated) { throw new Error('Cannot validate signature.'); } console.log('Webhook message', req.body); // Send a 200 OK response back to Common Ninja res.sendStatus(200); } catch (e) { console.error(`Cannot handle webhook message`, e); res.status(500).send((e as Error).message); } }); ``` -------------------------------- ### Common Ninja API: Get Coupons Endpoint Source: https://docs.commoninja.com/apis/e-commerce/coupons/get-coupons Documents the GET request to retrieve a list of coupons and discounts from the Common Ninja API. It details query parameters like 'limit' and 'page', required headers such as 'Authorization' and 'X-CN-User-Access-Token', and the structure of a successful response. ```APIDOC GET https://api.commoninja.com/integrations/api/v1/ecommerce/coupons Query Parameters: limit (Number): Number of items per request page (String): Headers: Authorization* (String): Common Ninja app authorization header X-CN-User-Access-Token* (String): User token ``` -------------------------------- ### Proxy Common Ninja API Requests Source: https://docs.commoninja.com/getting-started/quick-start Acts as a proxy for incoming requests to the Common Ninja API. It uses the `apiProxyMiddleware` SDK method to forward requests, handling authentication headers and request bodies automatically, simplifying API interaction. ```TypeScript import { Request, Response, NextFunction } from 'express'; import { getCommonNinjaClient } from './commonNinjaClient'; // Assuming this is how you get the client // API Proxy router.all('/api*', async (req: Request, res: Response, next: NextFunction) => { // Get a new Common Ninja instance const client = getCommonNinjaClient(req); // Proxy api requests to Common Ninja API // For example: // /api/ecommerce/products will be proxied to // https://api.commonninja.com/integrations/api/v1/ecommerce/products // The middleware will handle the authentication headers and request body return client.apiProxyMiddleware(req, res, next, '/api'); }); ``` -------------------------------- ### User Subscription Response Structure Source: https://docs.commoninja.com/apis/payments/subscriptions/get-user-subscriptions Defines the structure of the data returned for a successful request to get user subscriptions. ```javascript { success: boolean; message: string; data: IUserSubscription[]; } ``` -------------------------------- ### Get User Subscriptions API Source: https://docs.commoninja.com/apis/payments/subscriptions/get-user-subscriptions Fetches a list of the authenticated user's subscriptions. Requires authorization headers. ```APIDOC GET https://api.commoninja.com/integrations/api/v1/payments/subscriptions Query Parameters: status (String): Subscription status (see the "User Subscription" object). platform (String): The payment platform the subscription was created from. subscriptionId (String): Subscription ID. Headers: Authorization (String)*: Common Ninja app authorization header. X-CN-User-Access-Token (String)*: User token. Response (200 OK): success: boolean message: string data: IUserSubscription[] ``` -------------------------------- ### Cancel Subscription Response Example Source: https://docs.commoninja.com/apis/payments/subscriptions/cancel-user-subscription Example JSON response for a successful subscription cancellation request, indicating the operation's outcome. ```javascript { "success": true, "message": "Subscription cancelled successfully", "data": null } ``` -------------------------------- ### Get Product by ID Source: https://docs.commoninja.com/apis/e-commerce/products/get-product Retrieves a single product's details from the Common Ninja API using its unique identifier. Requires authentication headers. ```APIDOC GET /integrations/api/v1/ecommerce/products/:id Description: Retrieves a single product. Path Parameters: - id (String, required): The unique identifier of the product. Headers: - Authorization (String, required): Common Ninja app authorization header. - X-CN-User-Access-Token (String, required): User token for authentication. Responses: - 200 OK: Successful retrieval of product data. Content: success: boolean message: string data: IProduct (Object representing product details) ``` -------------------------------- ### Example Redirect URL with JWT Token Source: https://docs.commoninja.com/getting-started/authentication/setting-up-redirect-url This example shows the format of a redirect URL after a successful Common Ninja authentication. A JWT token is appended as a query parameter, which is used for making API requests on behalf of the merchant. ```text https://www.yourwebsite.com?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ``` -------------------------------- ### cURL API Request with Access Token Source: https://docs.commoninja.com/getting-started/authentication/using-the-access-token Demonstrates how to make an API request using cURL, including the Authorization and X-CN-User-Access-Token headers. ```bash curl 'https://api.commoninja.com/integrations/api/v1/products' \ -H 'Authorization: Basic ' \ -H 'X-CN-User-Access-Token: ' ``` -------------------------------- ### Get Store Categories API Source: https://docs.commoninja.com/apis/e-commerce/categories/get-categories Fetches a list of store categories or collections. Supports query parameters for pagination and requires specific authorization headers. ```APIDOC GET /integrations/api/v1/ecommerce/categories Description: Retrieves a list of store categories or collections. Query Parameters: - limit (Number): Number of items per request. Optional. - page (String): Specifies the page number for pagination. Optional. Headers: - Authorization (String, required): Common Ninja app authorization header. - X-CN-User-Access-Token (String, required): User token for authentication. Responses: 200 OK: Description: Successfully retrieved categories. Content: application/json: schema: type: object properties: success: { type: boolean } message: { type: string } data: type: object properties: limit: { type: number, nullable: true } nextPage: { type: [number, string, null], nullable: true } page: { type: [number, string, null], nullable: true } pages: { type: number, nullable: true } prevPage: { type: [number, string, null], nullable: true } total: { type: number, nullable: true } items: type: array items: { $ref: "#/definitions/ICategory" } required: [success, message, data] Definitions: ICategory: type: object description: Represents a single category item. properties: {} # Note: Specific properties for ICategory are not detailed in the provided text. ```