> ## Documentation Index
> Fetch the complete documentation index at: https://docs.1price.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Build: Code

> Integrate 1Price into your application in 15 mins

<Tip>
  **Prerequisite:** You should have connected Stripe before starting. More info
  [here](/quickStart#2-connect-stripe-1-min)
</Tip>

<Note>
  We have created personalized guides to integrate with the following apps:
  [React/Nextjs](/integrations/react), [Framer](/integrations/framer),
  [Webflow](/integrations/webflow), [Wordpress](/integrations/wordpress),
  [Gumroad](/integrations/gumroad).
</Note>

<Warning>
  Ensure you have started an experiment to the status `In Progress` before
  following the guide
</Warning>

<Frame>
  <iframe autoplay width="700" height="394" src="https://www.youtube.com/embed/m0Ed-8NS3Y8" title="1Price Complete Code Setup" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen />
</Frame>

<Tip>
  **CodeSandbox:** You can see the exact working code to help with
  implementation
  [here](https://codesandbox.io/p/devbox/1price-demo-forked-fwylmj?workspaceId=b5b1c612-c839-4312-b977-a30fb346f3f2)
</Tip>

## Step One: Copy Embeded Code

### Client Side Implementation

Insert our script tag in your website's head tag.

<CodeGroup>
  ```html HTML theme={null}
  <script
    src="https://widget.1price.co/script.js"
    data-1p="YOUR_WORKSPACE_ID"
    defer
  ></script>
  ```

  ```javascript Next.js theme={null}
  "use client"; // NextJS 13 requires this. Remove if you are using NextJS 12 or lower.

  import Script from "next/script";

  const YourComponent = () => {
    return (
      <Script
        src="https://widget.1price.co/script.js"
        data-1p="YOUR_WORKSPACE_ID" // Required
      ></Script>
    );
  };
  ```
</CodeGroup>

The script needs to be added on your landing page, app, or any other page where you want to use 1Price. This script will add a global variable called ` $1Price` to your window object which will categorize new users.

<Warning>
  Replace value of `YOUR_WORKSPACE_ID` with your unique `data_1p` found on
  [connect](https://app.1price.co/connect)
</Warning>

<Warning>
  Note: 1Price is not responsible for any API failures. Setup proper fallback
  values when implementing our API
</Warning>

### Server Side Implementation

<Warning>
  We HIGHLY advise AGAINST server side implementation. The 1Price script performs serveral analytics actions and has been tested thoroughly. Adding your own implementation risks the loss of important data and innacurate results.

  This is also a beta feature.
</Warning>

**Fetching the 1Price Object**

Each time you have a new visitor, you must fetch the 1Price object and store it. We recommend storing it in a cookie for three hours.

```
GET https://app.1price.co/api/get1PriceObject?workspace_id=&country_code=
```

<ParamField path="workspace_id" type="string" required>
  The workspace of your account found in
  [connect](https://app.1price.co/connect)
</ParamField>

<ParamField path="country_code" type="string">
  The country code of the user
</ParamField>

**Obtaining a country code**

We recommend using [ipAPI](https://ipapi.co/api/) to get the country code of the user.

**Re-Validating The Experiment**

To prevent duplicate analytics of a customer visting pages or reloading, if you detect a valid cookie, call the following API

```
GET  https://app.1price.co/api/v1/revalidate_experiment/
```

<ParamField path="origin" type="string">
  The origin of the request
</ParamField>

<ParamField path="customer_id" type="string" required>
  The customer linked to the offer
</ParamField>

<ParamField path="offer_id" type="string" required>
  The offer shown for experiments
</ParamField>

<ParamField path="experiment_id" type="string" required>
  The experiment linked to the offer
</ParamField>

## Step Two: Dynamic Price Number

To have adaptive pricing, change the price value to correspond with the [1Price Experiment](/build/firstExp). This value will be used during pricing tables within the app and landing page.

<Tip>
  For comprehensive tests, check out our [interactive
  playground](https://codesandbox.io/p/devbox/1price-demo-forked-fwylmj?workspaceId=b5b1c612-c839-4312-b977-a30fb346f3f2).
</Tip>

```javascript POST theme={null}
fetch("https://widget.1price.co/api/v2/price_value", {
  method: "POST",
  body: JSON.stringify({
    one_price: $1Price,
    unique_id: USER_ID, // OPTIONAL
  }),
})
  .then((response) => response.json())
  .then((data) => {
    console.log("Products", data);
  })
  .catch((error) => {
    console.log(error);
  });
```

<Warning>
  Replace value of `USER_ID` with the value of your customer's unique id.
</Warning>

This endpoint returns a **JSON object containing pricing details** for your products, including monthly and yearly pricing options, and currency information. The response includes:

`Success Status`

`Currency`

`Product Details`

Use this data to dynamically populate your pricing table and ensure your visitors always see the most up-to-date pricing information.

### `$1Price` Parameters:

<ParamField path="workspace_id" type="string" required>
  The workspace of your account
</ParamField>

<ParamField path="customer_id" type="string" required>
  The customer linked to the offer
</ParamField>

<ParamField path="experiment_id" type="string" required>
  The experiment linked to the offer
</ParamField>

<ParamField path="offer_id" type="string" required>
  The offer shown for experiments
</ParamField>

<ParamField path="currency" type="string">
  Optional parameter to specify the currency for returned pricing values (e.g.,
  "usd", "eur", "gbp")
</ParamField>

### Additional parameters include:

<ParamField path="unique_id" type="string">
  Optional parameter to maintain consistent pricing for a specific customer
  across multiple sessions
</ParamField>

<AccordionGroup>
  <Accordion title="Sample Response" icon="code" iconType="solid">
    <CodeGroup>
      ```javascript Success Message theme={null}
      {
      "success": true,
      "currency": "usd",
      "products": [
      {
        "name": "Basic Plan",
        "monthly": {
          "price": 9.99,
          "formatted_price": "$9.99 USD",
          "interval": "month",
          "billing_scheme": "per_unit",
          "interval_count": 1,
          "stripe_price_id": "price_1ABC123XYZ",
          "metadata": {
             description: "reg offer",
             original_price_id: "price_EFA4F456UVW"
          }
         },
        "yearly": {
          "price": 99.99,
          "formatted_price": "$99.99 USD",
          "interval": "year",
          "billing_scheme": "per_unit",
          "interval_count": 1,
          "stripe_price_id": "price_2DEF456UVW",
          "metadata": {
             description: "60% off",
             original_price_id: "price_AFeF456UVW"
          }
         },
       }
      ]
      }
      ```

      ```javascript Failure Message theme={null}
      {
       "success": false,
      }
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

## Step Three: Track Purchases

To determine the success of a experiment, we track multiple data points on [Results](/build/results). Simply add a `oneprice_cid` to your Stripe Checkout Session

You'll need to send the 1Price generated priceId to your backend server when creating a Stripe subscription.

<CodeGroup>
  ```javascript Example Stripe Checkout Session theme={null}
  const session = await stripe.checkout.sessions.create({
    success_url: "https://example.com/success",
    cancel_url: "https://example.com/cancel",
    metadata: { oneprice_cid: YOUR_1PRICE_CID },
    line_items: [{ price: YOUR_PRICE_ID, quantity: 1 }],
    mode: "subscription",
  });
  ```

  ```javascript Example Stripe Subscription Session theme={null}
  const subscription = await stripe.subscriptions.create({ 
    customer: 'cus_Mzbketpctz1F', 
    metadata: { oneprice_cid: YOUR_1PRICE_CID },
    items: [
      { price: YOUR_PRICE_ID },
    ],
  });
  ```
</CodeGroup>

<Warning>
  Replace value of `YOUR_1PRICE_CID` with the value of your \$1Price.customer\_id
  and the value of `YOUR_PRICE_ID` with the dynamic price\_id (from your response
  request).
</Warning>

<Note>
  Example above is with Javascript, but it is the same with every language. You
  just need to send the oneprice\_cid from client side to your backend server either
  with params, query, or body and then send it to Stripe with metadata when a
  stripe checkout session.

  Also note, we can only track Checkout Sessions at the moment. Subscription Creations is in beta. [Message us for access](mailto:hello@1price.co)
</Note>

<Tip>
  If the Stripe API is called on the client side, you will need to use the
  1Price Global variation from either `$1Price` or `window.$1Price`
</Tip>

## Handling Subscription Upgrades

We recommend having your own billing pages given the structure of price experiments. However, for customers who use the Stripe billing portal, our beta `/v3/price_value` endpoint contains a `stripeCheckoutSubscriptionUpdate` property.

To retrieve this property simply follow the [Step 2](#step-two-dynamic-price-number) and access the `stripeCheckoutSubscriptionUpdate` property.

When creating your [Stripe portal sessions](https://docs.stripe.com/api/customer_portal/configurations) you will first need to create a custom session. The following is an example of how to create a custom session using the NodeJS library.

```javascript theme={null}
const configuration = await stripe.billingPortal.configurations.create({
        features: {
            subscription_update: {
                enabled: true,
                default_allowed_updates: ['price'],
                // The object retrieved from the v3 endpoint
                products: stripeCheckoutSubscriptionUpdate  
            },
        },
        business_profile: {
            privacy_policy_url: 'https://example.com/privacy',
            terms_of_service_url: 'https://example.com/terms',
        },
    })
```

Once your configuration is made you can create your custom session using the following code.

```javascript theme={null}
const session = await stripe.billingPortal.sessions.create({
        customer: stripeCustomerID,
        return_url: req.nextUrl.origin,
        configuration: configuration.id, // The configuration ID you created
    })
```

## 🧪 ​{" "} Test Integration:

1. Start an experiment on 1Price <br />
2. Make a test purchase on your website/app
3. Ensure transaction was tracked on dashboard

> **BONUS:** You can create a 100% off coupon on Stripe and use that code to make the test purchase, so you do not get charged.

### FAQs

**Why do get the error: 'Start an experiment to activate script'?**

This error appears when there are no active experiments in your workspace. To resolve this, go to your dashboard and set at least one experiment's status to `In Progress`. The script will automatically activate once you have an active experiment.

**What's the difference between `data-1p` and `workspace_id`?**

These are two references to the same identifier. `data-1p` is used when embedding the script tag, while `workspace_id` is used when accessing it programmatically through `$1Price.workspace_id`. Both contain the same unique workspace identifier.

**Do I need to specify the `uniqueId` and `currency`?**

The `uniqueId` parameter is optional and can be used to maintain consistent pricing for a specific customer across multiple sessions. The `currency` parameter is also optional and can be used to specify the currency for returned pricing values.

**How can I preview what a specific customer segment sees?**

You can preview the pricing for any offer by making a GET request to:

```javascript theme={null}
http://widget.1price.co/api/v2/price_value?offer_id=YOUR_OFFER_ID
```

This is useful for verifying the pricing that different customer segments will see.

**I have additional questions, how can I contact you?**

You can always contact us via live chat or [email](hello@1price.co) and we can set up a price experiment together!
