> ## Documentation Index
> Fetch the complete documentation index at: https://developer.vetcove.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Embed the Vetcove storefront in your mobile app

> A step-by-step guide to setting up the Vetcove Home Delivery storefront within your mobile app.

This guide describes how to integrate the embedded shopping experience and what is required to set it up.

The embedded shopping experience allows a Group or Clinic to "host" Vetcove's Home Delivery shopping portal directly within a mobile app using an iFrame or WebView. This provides a seamless, native-like experience while enabling auto-authentication for users (clients) and deep-linking into specific parts of the online storefront, such as checkout.

> [!NOTE]
>
> If you encounter any issues configuring the embedded shopping experience, we're here to help! Please reach out to your onboarding specialist for assistance.

## Getting started

### Requirements

To set up the embedded shopping experience, you will need:

* An **API Key** (Instructions on how to get one available in [Getting started with API Keys](https://developer.vetcove.com/guides/getting-started.md))
* A list of **live clinic IDs**
* A **backend server** to handle authentication requests
* Your **mobile app** to integrate the WebView or iFrame

## API overview

The integration requires two API calls:

1. **Generate an auto-authentication token** for a client using [this API](https://developer.vetcove.com/accounts/auto-authenticate-a-client.md).
2. **Create a Client and Patient** (only if the client does not exist in our system).

> [!WARNING]
>
> API calls should be made from your backend server to prevent exposing the API Key in frontend code or bundles. DO NOT expose the API Key in your mobile app.

## API flow

**1. Step 1: Request an Auto-Authentication Token**

To authenticate a client, make a POST request to the `/ext/v2/accounts/auto-auth/` [endpoint](https://developer.vetcove.com/accounts/auto-authenticate-a-client.md).

#### **Request payload**

You must provide a `clinic_id` (Clinic ID of the associated Clinic) and either `client_email` or `client_phone_number`. If both are available, we recommend using `client_phone_number`.

```json theme={null}
{
    "clinic_id": 1,
    "client_email": "foo@bar.com"
}
```

Or, using a phone number:

```json theme={null}
{
    "clinic_id": 1,
    "client_phone_number": "1234567890"
}
```

#### **Successful response**

If the request is valid, the API will return an authentication token and relevant URLs.

```json theme={null}
{
    "auto_auth_token": "ABCD123",
    "expiry": 155774433222,
    "base_url": "https://clinic1.ourvet.com/pet",
    "fullscreen_url": "https://clinic1.ourvet.com/pet?auto_auth_token=ABCD1234",
    "embed_url": "https://clinic1.ourvet.com/pet?auto_auth_token=ABCD1234&render_type=embed"
}
```

If the request is successful, you can **skip Step 2** and proceed to Step 3.

#### **Error responses**

* **401 Unauthorized**: Invalid API token. Verify the token and header format.

* **400 Bad Request**: Invalid JSON payload or validation errors.

  ```json theme={null}
  {
      "error": {
          "type": "validation_error",
          "message": "The following fields are invalid: clinic_id"
      }
  }
  ```

* **404 Not Found**: No client exists for the provided details. Proceed to **Step 2** to create a Client and Patient.

  ```json theme={null}
  {
      "error": {
          "type": "server_error",
          "message": "No Client Found for Clinic id=1 with email or phone number provided"
      }
  }
  ```

**2. Creating a Client and Patient**

If Step 1 resulted in a **404 Not Found**, you must create a Client and Patient in our system before retrying authentication.

Make a POST request to the `/ext/v2/clinic-clients/` [endpoint](https://developer.vetcove.com/clients-and-patients/create-a-clinic-client.md).

#### **Request payload**

```json theme={null}
{
    "clinic_id": 1,
    "phone_number": "1234567890",
    "email": "foo@bar.com",
    "first_name": "Foo",
    "last_name": "Bar",
    "pim_id": "GDHJSCX",
    "primary_address": {
            "address_one": "123 Foo Bar Lane",
            "address_two": "APT 2B",
            "city": "Brattleboro",
            "state": "MO",
            "zipcode": "85292"
    },
    "clinic_patients": [
        {
            "name": "FoorBar Dog",
            "species": "CANINE",
            "pim_id": "FDHSJLX",
            "weight": 82,
            "birth_month": 2,
            "birth_year": 2018
        }
    ]
}
```

#### **Successful response**

Once you receive a **201 Created** response, return to **Step 1** and request an authentication token using the newly created Client's email or phone number.

**3. Step 3: Using the Auto-Authentication Token**

> 🚧 **Ensure you received an auth token before proceeding!**
>
> If Step 1 failed, check your payload or return to Step 2 to create a Client and Patient.

Once you receive a successful response, take the `embed_url` and return it in your API response for the WebView or iFrame integration.

## Implementing in React Native

### Backend integration

Before implementing the WebView, you'll need to create a backend API endpoint that handles the authentication flow described in Steps 1 and 2. This endpoint should:

1. Accept client information from your mobile app
2. Make the POST request to `/ext/v2/accounts/auto-auth/` with your API key
3. Handle the 404 response by creating a new client if needed (Step 2)
4. Return the `embed_url` to your mobile app

In the React Native example below, we assume you have created an endpoint at `https://api.your-backend.com/vetcove-auth` that implements this logic. Replace `API_URL` in the example with your actual backend endpoint URL.

> [!WARNING]
>
> Never call the Vetcove API directly from your mobile app. Always proxy requests through your backend to keep your API key secure.

### React Native WebView example

```jsx theme={null}
import React, { useState, useEffect, useCallback } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import { WebView } from 'react-native-webview';

const API_URL = 'https://api.fake-corporate-group-url.com/homedelivery-auth';

const VetcoveEmbeddedWebview = () => {
  const [autoAuthURL, setAutoAuthUrl] = useState(null);
  const [isLoading, setLoading] = useState(false);

  const fetchAuthUrl = useCallback(() => {
    setLoading(true);
    fetch(API_URL, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      }
    })
      .then(response => response.json())
      .then(data => {
        setAutoAuthUrl(data.embed_url);
        setLoading(false);
      });
  }, []);

  useEffect(() => {
    fetchAuthUrl();
  }, []);

  return autoAuthURL ? (
    <WebView
      source={{ uri: autoAuthURL }}
      allowsInlineMediaPlayback={true}
      mediaPlaybackRequiresUserAction={false}
    />
  ) : (
    <View><Text>Loading...</Text></View>
  );
};

export default VetcoveEmbeddedWebview;
```

## WebView best practices

To enhance the WebView experience, use the following recommended props:

```jsx theme={null}
scrollEnabled={true}
overScrollMode='never'
bounces={false}
decelerationRate='normal'
allowsInlineMediaPlayback={true}
mediaPlaybackRequiresUserAction={false}
```

These settings help ensure a smooth and seamless embedded shopping experience.

> [!WARNING]
>
> Set `allowsInlineMediaPlayback` and `mediaPlaybackRequiresUserAction` for iOS. Without `allowsInlineMediaPlayback`, storefront videos open in the native full-screen player on iPhone instead of playing inline. Without `mediaPlaybackRequiresUserAction={false}`, muted background videos won't autoplay. See the [react-native-webview reference](https://github.com/react-native-webview/react-native-webview/blob/master/docs/Reference.md#allowsinlinemediaplayback) for details.
