### Run Local Development Server Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-set-up-an-app-with-the-cli Start a local development server to view your app in real-time. This command runs the app on a development site chosen during setup. ```bash yarn dev ``` -------------------------------- ### Complete Callback Handler Example Source: https://dev.wix.com/docs/build-apps/launch-your-app/app-distribution/install-your-app/set-up-the-external-install-flow A full example of the callback handler, including route definition, query parameter extraction, installation success verification, and placeholder for business logic. Ensure your callback endpoint uses HTTPS. ```javascript app.get('/wix/connect', async (req, res) => { const { appId, tenantId, instanceId, state } = req.query if (!instanceId) { // Log the failure server-side if needed return res.redirect('/install-cancelled') } const parsedState = JSON.parse(state) // Implement business logic to use the query parameters }) ``` -------------------------------- ### Get App Instance with wix-application-backend (Deprecated Backend) Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-blocks/publish-blocks-apps-to-the-app-market/adjust-a-blocks-app-to-different-pricing-plans This example demonstrates how to retrieve the decoded app instance using the deprecated `wix-application-backend` module in a backend file. ```javascript import * as wixApplicationBackend from 'wix-application-backend'; export async function getInstance() { return wixApplicationBackend.getDecodedAppInstance(); } ``` -------------------------------- ### Start Wix Development Server Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-create-a-site-plugin-for-the-wix-stores-product-page-with-the-cli Use this command to start the local development server for testing your Wix application. ```bash wix dev ``` -------------------------------- ### Start the local app server Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-set-up-an-app-with-the-app-dashboard Execute this command to start your local development server. It will output important URLs needed for OAuth and webhook configuration. ```bash npm run start ``` -------------------------------- ### Install client dependencies Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-set-up-an-app-with-the-app-dashboard Install all necessary Node.js dependencies for the client-side application. ```bash npm install ``` -------------------------------- ### Install Wix Blog SDK Module Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-create-a-top-blog-posts-dashboard-page-with-the-cli Install the Wix Blog module using npm to access its functionalities in your app. ```bash npm install @wix/blog ``` -------------------------------- ### Install Business Tools Package Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/get-started/quick-start Install the @wix/business-tools package to enable interaction with Wix Business APIs like Locations. ```bash npm install @wix/business-tools ``` -------------------------------- ### Install Wix SDK and Data Packages Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-build-an-e-commerce-business-solution/step-5-implement-a-self-hosted-catalog-service-plugin Install the necessary Wix SDK and Wix Data npm packages for your server-side code. ```bash npm install @wix/sdk npm install @wix/data ``` -------------------------------- ### Install Site Location Package Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-create-a-product-widget-with-blocks-cli Run this command in your terminal to install the necessary package for site navigation. Warnings can typically be ignored. ```bash npm install '@wix/site-location' ``` -------------------------------- ### Install Wix SDK Source: https://dev.wix.com/docs/build-apps/develop-your-app/access/authentication/authenticate-on-behalf-of-a-wix-user Install the Wix SDK using npm. This module is used for communicating with the Wix platform from JavaScript code. ```bash npm install @wix/sdk ``` -------------------------------- ### Base Installation URL Source: https://dev.wix.com/docs/build-apps/launch-your-app/app-distribution/install-your-app/about-the-external-install-flow This is the base URL to which query parameters are appended to initiate the external install flow. Ensure the `postInstallationUrl` is an encoded URI component. ```url https://www.wix.com/app-installer ``` -------------------------------- ### Install Wix Stores Package Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-create-a-product-widget-with-blocks-cli After generating the app and its extensions, install the '@wix/stores' package to enable access to Wix Stores functionalities. ```bash npm install '@wix/stores' ``` -------------------------------- ### Full Service Plugin Implementation Example Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/supported-extensions/backend-extensions/add-self-hosted-service-plugin-extensions-with-the-sdk A complete example demonstrating how to set up the Wix client, define handler functions for shipping rates, and expose an endpoint using Express. ```javascript // Import the Wix client and service plugin modules import { createClient } from '@wix/sdk'; import { shippingRates } from '@wix/ecom/service-plugins' const wixClient = createClient({ auth: { appId: , publicKey: }, modules: { shippingRates } }); // Define handler functions with your custom logic wixClient.shippingRates.provideHandlers({ getShippingRates: async (payload: GetShippingRatesEnvelope) => { const { request, metadata } = payload; // Add your logic here } }); // Implement a router to process all requests and trigger calls to your handler functions express.post('/plugins-and-webhooks/*', (req, res) => { wixClient.process(req); }); ``` -------------------------------- ### Check for Installed Wix Apps using Get App Instance API Source: https://dev.wix.com/docs/build-apps/launch-your-app/app-submission/app-checks-and-testing-guide Use the Get App Instance API to verify if a user has required Wix apps, such as Wix Stores, installed on their site. If not, inform the user. ```javascript const WixApps = await getAppInstance("APP_ID"); const WixStoresInstalled = WixApps.installedWixApps.includes("WIX_STORES_APP_ID"); if (!WixStoresInstalled) { // Inform user they need Wix Stores } ``` -------------------------------- ### Initialize a New Wix App with npm Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-build-a-locations-app-with-the-cli Use this command to start a new Wix app project. Follow the prompts to configure your app's name and project structure. ```bash npm create @wix/new app ``` -------------------------------- ### Check for Installed Wix Apps using Get App Instance API Source: https://dev.wix.com/docs/build-apps/launch-your-app/app-distribution/test-your-app/app-checks-and-testing-guide Use the Get App Instance API to verify if a user has required Wix apps, such as Wix Stores, installed on their site. The `installedWixApps` field contains this information. ```javascript const WixApps = require("@wix/wix-apps"); async function checkWixStores(instanceId) { const appInstance = await WixApps.getAppInstance(instanceId); if (appInstance.installedWixApps && appInstance.installedWixApps.includes("wix-stores")) { console.log("Wix Stores is installed."); } else { console.log("Wix Stores is not installed. Please install it to use this app."); } } ``` -------------------------------- ### Deprecated: Get Widget Properties in Panel (Velo) Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-blocks/code-in-blocks/blocks-code-snippets This is a deprecated Velo example using 'wix-widget' to get all widget properties and load panel elements with them. ```typescript import wixWidget from 'wix-widget'; //... const props = await wixWidget.getProps(); //load panel elements with current props $w('#').value = props.propName; ``` -------------------------------- ### Run the Development Server Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-set-up-an-app-with-the-cli Start the local development server to preview your app. This command watches for file changes and rebuilds the app automatically. ```bash wix app dev ``` -------------------------------- ### Deprecated: Get Decoded App Instance Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-blocks/code-in-blocks/about-custom-elements-in-blocks Example of using the deprecated `wix-application` module to get the decoded app instance ID and set it as a custom element attribute. ```js import wixApplication from 'wix-application'; $w.onReady(function () { const instance = await wixApplication.getDecodedAppInstance(); $w('#myCustomElement').setAttribute('instanceIdAttribute', instance.instanceId); }); ``` -------------------------------- ### Build Your App Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/supported-extensions/backend-extensions/web-methods/add-web-method-extensions-with-the-cli Execute this command to build your application for production. This prepares your app for deployment. ```bash npm run build ``` -------------------------------- ### Define GET Route and Read Query Parameters Source: https://dev.wix.com/docs/build-apps/launch-your-app/app-distribution/install-your-app/set-up-the-external-install-flow Register a GET route for your callback path and extract query parameters from the incoming request. This is the initial setup for your callback handler. ```javascript app.get('/wix/connect', async (req, res) => { const { appId, tenantId, instanceId, state } = req.query }) ``` -------------------------------- ### Initialize a New Wix App with Wix CLI Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-set-up-an-app-with-the-cli Use this command to create a new Wix app. It sets up the project structure, package.json, and a local git repository. Follow the prompts to name your app and select default configurations. ```bash yarn create @wix/new app ``` -------------------------------- ### Get App Instance with wix-application (Deprecated Frontend) Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-blocks/publish-blocks-apps-to-the-app-market/adjust-a-blocks-app-to-different-pricing-plans This example shows how to get the decoded app instance and its vendor product ID using the deprecated `wix-application` module in frontend code. ```javascript import wixApplication from 'wix-application'; $w.onReady(async function () { instance = await wixApplication.getDecodedAppInstance(); plan = instance.vendorProductId; //You configured vendorProductId in the app dashboard. //If there is no plan, the value is null. // Now, add your logic for the different plans }); $widget.onPropsChanged((oldProps, newProps) => { }); ``` -------------------------------- ### Example Product Page Slot Configuration Source: https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/site-plugins/supported-wix-app-pages/wix-stores/wix-stores-product-page An example JSON object demonstrating how to configure a plugin placement for the new Wix Stores product page, including specific app, widget, and slot IDs. ```json { "appDefinitionId": "a0c68605-c2e7-4c8d-9ea1-767f9770e087", "widgetId": "6a25b678-53ec-4b37-a190-65fcd1ca1a63", "slotId": "product-page-details-2" } ``` -------------------------------- ### Get App Instance Data with Wix SDK (Node.js) Source: https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments?apiView=SDK Use this Node.js Express API example to get the `instanceId` from an access token and then fetch app instance data using the Wix SDK with elevated permissions. Ensure you have the necessary imports and set up your Express server. ```javascript import express from "express"; import cors from "cors"; import { createClient, AppStrategy } from "@wix/sdk"; import { appInstances } from "@wix/app-management"; const app = express(); const port = 5000; app.use(cors()); app.get("/get-instance-data", async (req, res) => { try { const accessToken = req.headers["authorization"]; if (!accessToken) { throw new Error("Access token is required."); } const tokenData = await axios.post( "https://www.wixapis.com/oauth2/token-info", { token: accessToken, }, ); const instanceId = tokenData.data.instanceId; console.log(`App instance ID: ${instanceId}`); const elevatedClient = createClient({ auth: await AppStrategy({ appId: "", appSecret: "", accessToken: accessToken, }).elevated(), modules: { appInstances, }, }); const instanceResponse = await elevatedClient.appInstances.getAppInstance(); console.log("Response from Get App Instance:", instanceResponse.data); return res.json(instanceResponse.data); } catch (error) { console.error("Error processing request:", error.message); return res.status(500).json({ error: "Failed to process request" }); } }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); ``` -------------------------------- ### Navigate to server directory Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-set-up-an-app-with-the-app-dashboard Open a new terminal and navigate to your app's server directory to manage dependencies and start the server. ```bash cd product-of-the-day/server ``` -------------------------------- ### Complete Webhook Handling Example Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/webhooks/handle-events-with-webhooks-for-self-hosting-using-the-java-script-sdk This comprehensive example integrates all the previous steps: setting up an Express server, creating a WixClient, registering an order cancellation handler, and defining the webhook endpoint for processing events. It demonstrates a full self-hosted webhook implementation. ```javascript import express from "express"; import { AppStrategy, createClient } from "@wix/sdk"; import { orders } from "@wix/ecom"; const app = express(); const PUBLIC_KEY = ``; const APP_ID = ""; const client = createClient({ auth: AppStrategy({ appId: APP_ID, publicKey: PUBLIC_KEY, }), modules: { orders }, }); client.orders.onOrderCanceled((event) => { console.log(`onOrderCanceled event received with data:`, event); console.log(`App instance ID:`, event.metadata.instanceId); // // Handle your event here // }); app.post("/webhook", express.text(), async (request, response) => { try { await client.webhooks.process(request.body); } catch (err) { console.error(err); response .status(500) .send(`Webhook error: ${err instanceof Error ? err.message : err}`); return; } response.status(200).send(); }); app.listen(3000, () => console.log("Server started on port 3000")); ``` -------------------------------- ### Set up an Express Server Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/webhooks/handle-events-with-webhooks-for-self-hosting-using-the-java-script-sdk Initialize an Express server to handle incoming webhook requests. This is the foundational step for receiving events. ```javascript import express from "express"; const app = express(); ``` -------------------------------- ### Wix eCommerce Side Cart Plugin Code Example Source: https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/site-plugins/supported-wix-app-pages/wix-e-commerce/wix-e-commerce-side-cart?apiView=SDK This example demonstrates how to get current cart details and add items to the cart using the Wix eCommerce Current Cart API and refresh the cart UI with the eCommerce frontend API. Ensure you import the necessary modules. ```javascript import { currentCart } from "@wix/ecom"; import { ecom } from "@wix/site-ecom"; $w.onReady(function () { // Get properties for the current cart. currentCart.getCurrentCart().then((cart) => { const cartId = cart._id; const cartLineItems = cart.lineItems; }); // Add selected items to the cart on button click. $w("#addItems").onClick(async () => { const itemsToAdd = $w("#itemsToChoose").value; await currentCart.addToCurrentCart({ lineItems: itemsToAdd }); // Call refreshCart() to refresh the cart components. await ecom.refreshCart(); }); }); ``` -------------------------------- ### Call HTTP Functions from Frontend Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/supported-extensions/backend-extensions/api/add-api-extensions-with-the-cli Use the `httpClient` from `@wix/essentials` to make authenticated requests to your backend HTTP functions. This example demonstrates calling both GET and POST endpoints. ```tsx import { httpClient } from '@wix/essentials'; function Index() { const callMyBackendGET = async () => { const res = await httpClient.fetchWithAuth(`${import.meta.env.BASE_API_URL}/`); console.log(await res.text()); }; const callMyBackendPOST = async () => { const res = await httpClient.fetchWithAuth(`${import.meta.env.BASE_API_URL}/`, { method: 'POST', body: JSON.stringify({ id: 12345 }), }); console.log(await res.json()); }; return ( ); } ``` -------------------------------- ### Deprecated: Get Billing Information (Velo) Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-blocks/code-in-blocks/blocks-code-snippets This is a deprecated Velo example for retrieving decoded app instance information, including the vendor product ID for plan details. ```typescript import wixApplication from 'wix-application'; //... instance = await wixApplication.getDecodedAppInstance(); plan = instance.vendorProductId; //If there is no plan, the value is null. //add your logic for the different plans ``` -------------------------------- ### Build and Release App Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-create-a-product-widget-with-blocks-cli Run these commands to build your app and create a release version. This is necessary before testing navigation on a live site. ```bash npm run build npm run release ``` -------------------------------- ### Full App.js Code for Catalog Service Plugin Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-build-an-e-commerce-business-solution/step-5-implement-a-self-hosted-catalog-service-plugin This is the complete code for app.js, including JWT verification, Wix client setup, and the Get Catalog Items endpoint implementation. ```javascript const express = require('express'); const jose = require('jose'); const { createClient, AppStrategy } = require('@wix/sdk'); const { collections, items } = require("@wix/data"); const app = express(); const port = 3000; app.use(express.json()); app.use(express.text()); async function verify(jwt) { const alg = 'RS256' const spki = ``; try { if (typeof jwt !== 'string') { throw new Error('JWT must be a string'); } const publicKey = await jose.importSPKI(spki, alg) const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { issuer: 'wix.com', audience: '', maxTokenAge: 60, clockTolerance: 60 }) return payload; } catch (error) { throw new Error('JWT verification failed'); } } app.post('/get-catalog-items', async (request, response) => { try { const token = request.body; const body = await verify(token); const instanceId = body.data.metadata.instanceId; const requestedItems = body.data.request.catalogReferences; const wixClient = createClient({ modules: { collections, items }, auth: AppStrategy({ appId: "", appSecret: "", publicKey: ``, instanceId: instanceId, }), }); ``` -------------------------------- ### Navigate to App Folder Source: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-build-a-locations-app-with-the-cli Navigate to your newly created app's folder to begin development. ```bash cd my-locations-app ``` -------------------------------- ### Get Placement Status of Site Plugins Source: https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/site-plugins/build-a-dashboard-page-to-manage-your-site-plugin This example shows how to use the `getPlacementStatus()` function from the `wix-site-plugins.v1` module to check if your site plugins are currently placed in any slots on a user's site. ```APIDOC ## Get Placement Status of Site Plugins ### Description Use the `getPlacementStatus()` function to check whether your site plugin is currently placed in a slot on a specific site. This API returns an array of objects indicating the placement status for each of your app's site plugins. ### Method `plugins.getPlacementStatus()` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```javascript import { plugins } from "wix-site-plugins.v1"; ... const { placementStatuses } = await plugins.getPlacementStatus(); const myPluginPlacementStatus = placementStatuses[0]; if (myPluginPlacementStatus.placedInSlot) { onPluginPlacedSuccessfully(); } ``` ### Response #### Success Response (200) - **placementStatuses** (array) - An array of objects, where each object indicates the placement status of a site plugin. - **placedInSlot** (boolean) - Indicates whether the plugin is currently placed in a slot. #### Response Example ```json { "placementStatuses": [ { "pluginId": "your-plugin-id", "placedInSlot": true } ] } ``` ``` -------------------------------- ### Example config.json File Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-blocks/code-in-blocks/add-code-files-to-your-app A sample `config.json` file demonstrating how to define default settings, such as a stock symbol for an API call. These values can be edited by users on a per-site basis. ```json { "defaultSymbol": "wix" } ``` -------------------------------- ### Generate App Extension with Wix CLI Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/app-development/development-overview Use this command to start the process of adding a new extension to your Wix CLI app. It guides you through selecting an extension and providing configuration details. ```bash npm run generate ``` -------------------------------- ### Get App Instance ID in CLI Event Extension Source: https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments Retrieve the `instanceId` from the `metadata` of a CLI event. This example also shows how to optionally fetch app instance data using `appInstances.getAppInstance`. ```javascript import { posts } from "@wix/blog"; import { auth } from '@wix/essentials'; import { appInstances } from "@wix/app-management"; posts.onPostCreated(async (event) => { console.log(`App instance ID: ${event.metadata.instanceId}`); // (Optional) Fetch app instance data from Wix const elevatedGetAppInstance = auth.elevate(appInstances.getAppInstance); const { instance, site } = await elevatedGetAppInstance(); console.log("Response from Get App Instance:", { instance, site }); }); ``` -------------------------------- ### Complete Self-Hosted Webhook Handler Source: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/webhooks/handle-events-with-webhooks-for-self-hosting-without-the-java-script-sdk This complete example integrates Express server setup, JWT verification, event parsing, and event type handling for self-hosted Wix webhooks without the SDK. ```javascript const jwt = require("jsonwebtoken"); const express = require("express"); const app = express(); const PUBLIC_KEY = ``; app.post('/webhook', express.text(), (request, response) => { let event; let eventData; try { const rawPayload = jwt.verify(request.body, PUBLIC_KEY); event = JSON.parse(rawPayload.data); eventData = JSON.parse(event.data); } catch (err) { console.error(err); response.status(400).send(`Webhook error: ${err.message}`); return; } switch (event.eventType) { case "wix.ecom.v1.order_canceled": console.log(`wix.ecom.v1.order_canceled event received with data:`, eventData); console.log(`App instance ID:`, event.instanceId); // // handle your event here // break; default: console.log(`Received unknown event type: ${event.eventType}`); break; } response.status(200).send(); }); app.listen(3000, () => console.log("Server started on port 3000")); ```