Currency conversion

Grabbing the conversion rate inside a Checkout UI extension is tricky business! There are a few approaches. I thought I’d share our specific approach!

1.) Set a Money metafield called currency_unit, with a large number, e.g 10,000,000
2.) Use query to grab the metafield IN CONTEXT of the current shopping session
3.) You’ll get your large number in the shopping currency, and can do a division to grab the conversion rate!

Pros:

  • This conversion rate will use Shopify Market conversion rates, rather than generic rates.
  • Does not rely on an external source (e.g currencies.js or storefront added cart attributes)

Here’s some “example” code:

Create the metafield:

export const SET_METAFIELD_MUTATION = /* GraphQL */ `
  mutation CreateAppOwnedMetafield(
    $metafieldsSetInput: [MetafieldsSetInput!]!
  ) {
    metafieldsSet(metafields: $metafieldsSetInput) {
      metafields {
        id
        namespace
        key
      }
      userErrors {
        field
        message
      }
    }
  }
`

const moneyMetafield = {
    namespace: 'my_namespace',
    key: 'shop_currency_unit',
    value: JSON.stringify({
      amount: '100000.00',
      currency_code: currencyCode,
    }),
    ownerId: shopGid,
    type: 'money',
  }

const response = await fetch(
    `https://${shop}/admin/api/${apiVersion}/graphql.json`,
    {
      method: 'POST',
      body: JSON.stringify({
        query: SET_METAFIELD_MUTATION,
        variables: {
          metafieldsSetInput: [moneyMetafield],
        },
      }),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': token,
      },
    },
  )
  const jsonResult: any = await response.json()

Query from your Checkout extension:

export const CurrencyFromShopQuery  = `
  query getCurrencyRateFromShop ($namespace: String!, $key: String!, $language: LanguageCode!, $country: CountryCode!) @inContext(country: $country, language: $language) {
    shop {
      id
      currencyUnitField: metafield(namespace: $namespace, key: $key) {
        value
      }
    }
  }
`;

Hope that helps!

5 Likes

This is awesome!! Thanks for sharing this bkspace!

1 Like