# Flowguard

## How to start with Yoursafe Flowguard

Welcome to the Yoursafe Flowguard SDK documentation. This guide will walk you through the steps necessary to set up and use the Flowguard class for integrating secure iframe elements into your payment system. This will allow you to accept secure payments with full control, offering unparalleled control over your payment flow while ensuring top-tier security and compliance.

---

### Yoursafe Flowguard overview

Following overview provides a high-level understanding of how Yoursafe Flowguard works.

![Flowguard architecture](https://flowguard.yoursafe.com/js/docs/assets/flowguard_architecture-E1d0PCI7.png)

---

### Before you start with integration

To ensure security, Flowguard elements can only be injected into **registered domains**.

---

### To use Flowguard elements

Follow these steps:

#### 1. Create a new website in the Control Center:

- *Log in to the **Control Center** → Navigate to **Setup Websites** → Click **Add new website** → Select **Flowguard API** type.*

#### 2. Submit the authorization form to confirm that your website is ready to be authorized. In this form, you must verify the following:

- All mandatory Flowguard elements are rendered on your website.

- The correct declineUrl and successUrl were provided during the initial API call.

- You are accepting postback from the Flowguard API (see the [backend documentation](/api/merchant/redoc) for more details).

- You have tested at least one successful payment using the [testing card](#testing-card) details provided in the **Control Center**.

Once these steps are completed, you will be able to process payments using Flowguard elements!

---

### Website testing mode

If your website is in testing mode, you must use the [testing card](#testing-card) details provided in the **Control Center** for a successful transaction.

---

### Domain Approval and CORS Configuration

<aside class="doc-callout">
<p>ℹ️ <strong>Reminder:</strong> <em>The Flowguard SDK host requires that all requests originate from an <strong>approved domain</strong> via CORS (Cross-Origin Resource Sharing) policies.</em></p>
</aside>

#### Why Domain Approval is Required

For security reasons, the Flowguard SDK enforces strict CORS policies. This means:

- **Requests must originate from domains that have been explicitly approved** in your Control Center configuration

- **Unauthorized domains will receive CORS errors** (typically appearing as "bad request" or "blocked by CORS policy" errors)

- **This prevents unauthorized websites** from loading and using our Flowguard elements

#### Using localhost for development

When developing locally, you can use `localhost` without needing to register it in the Control Center. **Content Security Policy (CSP) will not block localhost**, making it convenient for local development and testing.

#### Common CORS-Related Issues

If you encounter errors like:

- `"Access to fetch at 'https://flowguard.yoursafe.com/...' from origin 'https://yourdomain.com' has been blocked by CORS policy"`

- `"Bad Request"` errors when loading Flowguard elements

- `"Network Error"` or `"Failed to fetch"` messages

This typically indicates that your domain has not been properly registered or approved.

#### How to Resolve CORS Issues

- **Verify Domain Registration**: Ensure your domain is properly registered in the Control Center under **Setup Websites**

- **Check Domain Format**: Make sure you've registered the exact domain (including subdomains) from which you're loading the SDK - For `https://www.example.com` → register `www.example.com` - For `https://shop.example.com` → register `shop.example.com` - For `https://example.com` → register `example.com`

- **Include All Subdomains**: If you use multiple subdomains, each must be registered separately

---

### Backend setup

The first step in accepting payments with Yoursafe Flowguard is configuring the backend. There are two order types that are currently available for you - purchase or subscription.

**Purchase:**

- Start a purchase with `/purchase/start` endpoint and get the `sessionId` from the response. Follow [purchase documentation](/api/merchant/redoc#tag/Purchase) to learn more.

- Send the `sessionId` to the Flowguard SDK during Initialize Flowguard elements step.

**Subscription**:

- Start a subscription with `/subscription/start` endpoint and get the `sessionId` from the response. Follow [subscription documentation](/api/merchant/redoc#tag/Subscription) to learn more.

- Send the `sessionId` to the Flowguard SDK during Initialize Flowguard elements step.

---

### Frontend setup

The second step in accepting payments with Yoursafe Flowguard is configuring the frontend according to the following steps.

<aside class="doc-callout">
<p>ℹ️ <strong>Reminder:</strong> <em>Please note that the examples provided in this documentation are written in
plain <strong>JavaScript</strong>. If you&#39;re using a different language or framework, you will need to adjust
the code accordingly.</em></p>
</aside>

#### Load Flowguard SDK

To prevent blocking the loading of your page, add the Flowguard script at the bottom of the body tag or in the head tag with the defer attribute. The script must be loaded as a module.

Include the Flowguard JavaScript SDK from the CDN in your HTML:

```html
<script src="https://flowguard.yoursafe.com/js/flowguard.js" type="module" defer></script>
```

#### Create targets for Flowguard elements

Add target elements in your HTML where the iframes will be embedded. While the ID names can vary, make sure that the DOM ID matches the ID provided during initialization. All elements are mandatory.

```
<div id="card-number-element"></div>
  <div id="cvv-element"></div>
  <div id="cardholder-element"></div>
  <div id="exp-date-element"></div>
  <div id="price-element"></div>
```

#### Initialize Flowguard elements

Wait for `flowguard:loaded` before creating the Flowguard instance, and use `flowguard:ready` to start interacting with the instance. This ensures the SDK is loaded before configuration and the elements are ready before use.

The SDK dispatches three lifecycle events on `window`:

- `flowguard:loaded` — the SDK script has been evaluated and `window.Flowguard` is available.

- `flowguard:ready` — all configured elements (including `remember`, when used) are mounted and the form is safe to interact with. Dispatched once.

- `flowguard:error` — initialization failed and `flowguard:ready` will not follow. This covers invalid options as well as runtime failures such as an invalid or expired `sessionId` or a missing target element. The event is a `CustomEvent` carrying the failure in `event.detail.error` as `{ errorCode, errorDescription }`.

Register your listeners before the Flowguard script is evaluated (with the script tag setup shown above, any inline or earlier-loaded script does this naturally), otherwise `flowguard:loaded` may fire before you start listening.

Create an instance of the Flowguard class with the required options, using the **`sessionId`** received from the purchase/start API response. Additional options such as [placeholders](/docs/flowguard-sdk-placeholders--placeholders), [styles](/docs/flowguard-sdk-styles-introduction-to-styles--introduction-to-styles) and [error handlers](/docs/flowguard-sdk-errors-handling--errors-handling) can be included as needed.

Below is the minimal setup for initializing Flowguard and waiting for the ready event.

```
window.addEventListener('flowguard:loaded', () => {
const flowguard = new Flowguard({
  sessionId: 'YOUR_SESSION_ID',
  cardNumber: {
    target: '#card-number-element'
  },
  cvv: {
    target: '#cvv-element'
  },
  cardholder: {
    target: '#cardholder-element'
  },
  expDate: {
    target: '#exp-date-element'
  },
  price: {
    target: '#price-element'
  }
});

window.addEventListener('flowguard:ready', () => {
  console.log('Flowguard is ready to use');
  // safe to call flowguard.submit() here
});

window.addEventListener('flowguard:error', (event) => {
  console.log('Flowguard failed to load:', event.detail.error.errorDescription);
});
});
```

---

#### Submitting data

Submit card information for processing by calling the `submit` method on the Flowguard instance. For more details on how errors are handled, refer to the [error handling](/docs/flowguard-sdk-errors-handling--errors-handling) section.

```
flowguard.submit();
```

Below is a basic example demonstrating how to handle the submission in your code:

```
<button onclick="flowguard.submit()">Pay</button>
```

#### Removing elements

To remove all iframes created by Flowguard, use the `remove` method. This is particularly useful in Single Page Applications (SPAs) when you need to clean up elements.

```
flowguard.remove();
```

---

### Supported browsers

Flowguard elements are designed to work seamlessly across most modern browsers:

- The last 20 versions of all major browsers (including Chrome, Firefox, Edge, etc.), with the exception of those that are outdated and no longer maintained or widely used.

- Safari version 12 and later on macOS desktops.

- iOS Safari version 12.1 and later on iPhones and iPads.

---

### Testing Card

For testing purposes and to simulate transactions without actual charges, you can use the testing credit card details from your **Control Center**

- Log in to the **Control Center**

- navigate to **Setup Websites** tab

- click on your ***Flowguard*** website

- your testing card details is in the section **TESTING CARD** on the right side of the **Website detail** page

## Remember Card Integration

You can allow users to securely save their card information for future purchases.

Card details are stored in the **browser's local storage** in a masked format, ensuring that no sensitive data is exposed during future transactions. When prefilled, both the card number and the cardholder's name remain masked for added security. Users can remove their saved card at any time and choose to pay with a different card.

To enable the *Remember Card* option, simply provide a target for the remember element and include it during Flowguard initialization.

### Customizing the Remember Component

The Remember component is highly customizable, allowing you to adapt it to match your website's design. There are three primary styling categories with customizable base and hover states:

```
link: {
  base: {},
  hover: {}
}
label: {
  base: {},
  hover: {}
}
checkbox: {
  base: {}
}
```
