# Quick Start

## Idea

The idea is pretty simple, FieldsRaven is exposing the Metafields API on the storefront through a Shopify app proxy so you may take full advantage of creating (or updating) metafields on the storefront.

As a developer you just need to write in Liquid, JS and FieldsRaven will handle what's under the hood to help you unlock the full potential of Shopify themes.

I built FieldsRaven to be a storefront metafields kit for Shopify.

{% hint style="danger" %}
Make sure on the storefront that FieldsRaven requests are to be sent by a logged-in customers, it adds an extra layer of security.
{% endhint %}

## I installed the app, now what?

When FieldsRaven app is installed successfully on a Shopify store, there are a couple of steps you need to do to be able to start creating/updating metafields.

### Step 1

Create a new Shopify theme snippet named `raven-mac-gen.liquid`, copy & paste the below code snippet into the new snippet in Shopify admin and don't forget to **save**! ([Screen recording](https://monosnap.com/file/7wfOIwmMnH520aXt5QXdLj1MRGaZ3u))

<figure><img src="https://1211303336-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNP07jPPCyBlsAnUAqYNM%2Fuploads%2F7AR399mluFR3ttByV5uf%2FFieldsRaven%20Dev%20%C2%B7%20Edit%20~%20FieldsRaven%20%5BDev%5D%20%C2%B7%20Shopify%202023-10-23%2010-35-54.png?alt=media&#x26;token=401b6b50-d15e-4862-bae4-a95fdd0ce165" alt=""><figcaption></figcaption></figure>

```liquid
{%- liquid
  assign raven_api_secret = shop.metafields.fields_raven.api_secret
  assign raven_digest_string = raven_id | append: resource_id
  assign raven_mac = raven_digest_string | hmac_sha256: raven_api_secret
-%}
{
  raven_id: '{{ raven_id }}',
  resource_id: '{{ resource_id }}',
  raven_mac: '{{ raven_mac }}'
}
```

### Step 2

Create a `Raven` in FieldsRaven app. ([Screen recording](https://monosnap.com/file/dwfWJFBtUBZiqJUaOhhh2uH4EKUq7w))&#x20;

## Make your first request

Now that you created a `Raven` to carry messages and added the code snippet to a theme, it's time to create/update your first metafield.<br>

The end-point that makes this possible is this end-point: `/apps/raven/create_update_metafield` which expects an object with the following attributes: `raven_id, resource_id, value, raven_mac`.

## Create/update metafield.

<mark style="color:orange;">`PUT`</mark> `/apps/raven/create_metafield`

All parameters are expected to be wrapped in an object

#### Request Body

| Name                                           | Type                 | Description                                                           |
| ---------------------------------------------- | -------------------- | --------------------------------------------------------------------- |
| raven\_id<mark style="color:red;">\*</mark>    | string               |                                                                       |
| resource\_id<mark style="color:red;">\*</mark> | string               | If a shop metafield is being created/updated the value must be `shop` |
| value<mark style="color:red;">\*</mark>        | string, number, json | metafield value                                                       |
| raven\_mac<mark style="color:red;">\*</mark>   | string               | Message auth code, generated by `raven-mac-gen.liquid` snippet        |

{% tabs %}
{% tab title="200 Metafield successfully queued" %}

```javascript
{
    "status": 200,
    "json": {
        "message": "Sit tight the raven is on it!"
    }
}
```

{% endtab %}

{% tab title="422: Unprocessable Entity Metafield error" %}

```javascript
{
    "status": 422,
    "json": {
        "message": "🚨🚨 OOOPS SOMETHING WENT WRONG 🚨🚨",
        "errors": {
            "resource_name": [
                "pagex is not a valid value_type"
            ]
        }
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
All parameters are expected to be wrapped in an object
{% endhint %}

{% hint style="info" %}
If you are creating a shop metafield `resource_id` value should be `shop`
{% endhint %}

{% tabs %}
{% tab title="FieldsRaven Storefront JS Kit" %}

```javascript
{% if customer %}
  <script type="text/javascript">
    window.addEventListener('FieldsRavenJSKitReady', (event) => {
      ravenSubmit = () => {
        const ravenObj = {%- render 'raven-mac-gen', resource_id: page.id, raven_id: 'WGv2c24' -%}
        const valueObj = { value: `Hello Raven! @ ${Date.now()}` };
        const requestParams = Object.assign({}, ravenObj, valueObj);
        const response = FieldsRaven.send(requestParams);
        response.then(res => {
          if (res.status === 200) {
            console.log('🎉', res.json)
          } else {
            console.error('😞', res)
          }
        })
        .catch(e => console.error(e));
      }
    });    
  </script>
  <!-- CTA -->
  <button id="fieldsraven-demo" onclick="ravenSubmit()">send the Raven!</button>
{% else %}
  <p><a href='/account/login'>Login</a> or <a href='/account/register'>create an account</a> to unlock this feature!</p>
{% endif %}

```

{% endtab %}

{% tab title="Vanilla JS" %}

```html
// Liquid
{% if customer %}
  <script type="text/javascript">
    window.addEventListener('FieldsRavenJSKitReady', (event) => {
      ravenSubmit = () => {
        const ravenObj = {%- render 'raven-mac-gen', resource_id: page.id, raven_id: 'WGv2c24' -%}
        const valueObj = { value: `Hello Raven! @ ${Date.now()}` };
        const requestParams = { raven: Object.assign({}, ravenObj, valueObj) };
        
        const response = fetch('/apps/raven/create_metafield', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestParams)
        })

        response
          .then(res => res.json())
          .then(resJson => console.log('resJson: ', resJson))
      }
    });    
  </script>
  <!-- CTA -->
  <button id="fieldsraven-demo" onclick="ravenSubmit()">send the Raven!</button>
{% else %}
  <p><a href='/account/login'>Login</a> or <a href='/account/register'>create an account</a> to unlock this feature!</p>
{% endif %}
```

{% endtab %}
{% endtabs %}

## Storefront Kit

After installing the app, there should be a few `App embeds` in your `Customize > Theme settings > App embeds`.

![](https://1211303336-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNP07jPPCyBlsAnUAqYNM%2Fuploads%2FOftRip4W9tMLWM0E4Nla%2FFieldsRaven%20Dev%20~%20Customize%20Dawn%20~%20Shopify%202022-02-07%2022-58-14.png?alt=media\&token=b77dab57-9719-4523-9ced-bf0735ca111a)

For conveniance there is a `Storefront Kit` which contains few a JavaScript function to create/update metafields.

The `Storefront Kit` function will return a `promise`, when the `promise` is resolved it will return a JavaScript `object` that you may hook into to check on the status of the request and update the UI if you wish.

Example for a successful request

```javascript
{
    "status": 200,
    "json": {
        "message": "Sit tight the raven is on it!"
    }
}
```

Example for a failed request

```javascript
{
    "status": 422,
    "json": {
        "message": "🚨🚨 OOOPS SOMETHING WENT WRONG 🚨🚨",
        "errors": {
            "resource_name": [
                "pagex is not a valid value_type"
            ]
        }
    }
}
```

## Pre-built theme examples

At the moment there are two `App embeds` examples to demo what might be built on top of FieldsRaven.

1. Birthday Popup: an example implementation for a customer birthday reward popup. ([Screen recording](https://monosnap.com/file/M0DEkzpRBIYuGcNciqo1AGEIvQgZJk)). [Learn more](https://docs.fieldsraven.app/app-embeds/customer-birthday-popup).

2. Sitemap and Search engines Hide/Show: an example implementation for sitemap/search engines to hide pages/templates from search results & sitemap (`nofollow`, `noindex`). ([Screen recording](https://monosnap.com/file/h1EoPtbxRYRgmGR6Z4ob4OMCp4601H)). [Learn more](https://docs.fieldsraven.app/app-embeds/sitemap-manager).

Each of those `App embeds` have settings, make sure to check them out.

## Creating metafields on `onload`

If you're using FieldsRaven storefront kit, the kit triggers a `FieldsRaven:ready` event when it's loaded. So the following will do the trick.

```javascript
window.addEventListener('FieldsRavenJSKitReady', (event) => {
  console.log('FieldsRaven storefront kit loaded!');
});
```

If you'd rather not use FieldsRaven Storefront Kit, then this should do the trick:

```javascript
window.addEventListener('DOMContentLoaded', (event) => {
  console.log('DOM fully loaded and parsed');
});
```
