Requirements


Let’s begin!

1

Step 1: Initialize GQL client with your API key

Use your API Key to initialize authorization headers for your GQL client.

import { GraphQLClient, gql } from 'graphql-request'

const endpoint = 'https://graphql.api.rye.com/v1/query'
const client = new GraphQLClient(endpoint)
const headers = {
  'Authorization': 'Basic <API Key Here>',
  'Rye-Shopper-IP': 'xxx.xxx.x.x'
}
2

Step 2: Add external product to Rye inventory

Adding product data to inventory may take a few seconds, but the product id will be returned immediately. You can then use this product id to fetch product data in the next step. You can also do this via the Rye Console.

async function requestProduct() {
  const variables = {
    "input": {
      "url": "https://www.amazon.com/Verity-Colleen-Hoover-ebook/dp/B09H6T8LTR",
      "marketplace": "AMAZON"
    }
  };
  const query = gql`mutation RequestProductByURL(
    $input: RequestProductByURLInput!
  ) {
    requestProductByURL(input: $input) {
      productID
    }
  }`;
  const data = await client.request(query, variables, headers)
  console.log(JSON.stringify(data, undefined, 2))
}

await requestProduct();
3

Step 3: Fetch product data from Rye inventory

The product ID can be found in the response to the requestProduct mutation.

async function fetchProduct() {
  const variables = {
    "input": {
      "id": "B09H6T8LTR",
      "marketplace": "AMAZON"
    }
  };

  const query = gql`query DemoAmazonProductFetch($input: ProductByIDInput!) {
    product: productByID(input: $input) {
      title
      vendor
      url
      isAvailable
      images {
        url
      }
      price {
        displayValue
      }
      ... on AmazonProduct {
        ASIN
      }
    }
  }`;

  const data = await client.request(query, variables, headers)
  console.log(JSON.stringify(data, undefined, 2))
}

await fetchProduct();
4

Step 4: Create a cart

Allow developers to create a cart.

// Pre-requisite: Have an Apollo client initialized with the correct HTTP headers

const CREATE_CART = gql`
  mutation createCart($input: CartCreateInput!) {
    createCart(input: $input) {
      cart {
        id
        stores {
          ... on AmazonStore {
            store
            cartLines {
              quantity
              product {
                id
              }
            }
            offer {
              subtotal {
                value
                currency
                displayValue
              }
              margin {
                value
                currency
                displayValue
              }
              notAvailableIds
              shippingMethods {
                id
                label
                taxes {
                  value
                  currency
                  displayValue
                }
                price {
                  value
                  currency
                  displayValue
                }
                total {
                  value
                  currency
                  displayValue
                }
              }
            }
          }
        }
      }
      errors {
        code
        message
      }
    }
  }
`;

// useMutation will call the createCart mutation
const [createCart, { loading, error, data }] = useMutation(CREATE_CART);

// 
const createCartWithProducts = (product) => {
  const input = {
    items: {}
  };

  if (product.marketplace === Marketplace.AMAZON) {
    input.items.amazonCartItemsInput = [
      { productId: product.id, quantity: 1 },
    ];
  }

  if (product.marketplace === Marketplace.SHOPIFY) {
    input.items.shopifyCartItemsInput = [
      { variantId: product.id, quantity: 1 },
    ];
  }

  input.buyerIdentity = {
    city: 'city',
    countryCode: 'countryCode',
    provinceCode: 'provinceCode',
    postalCode: 'postalCode',
  };

  createCart({ variables: { input: input } });
  return;
}

5

Step 5: Add more products to your cart

Add more products to your cart with the product IDs and the cart ID of the desired cart.

Add item to cart

// Pre-requisite: Have an Apollo client initialized with the correct HTTP headers

export const ADD_CART_ITEMS = gql`
  mutation addCartItems($input: CartItemsAddInput!) {
    cart {
      id
      stores {
        ... on AmazonStore {
          store
          cartLines {
            quantity
            product {
              id
            }
          }
          offer {
            subtotal {
              value
              currency
              displayValue
            }
            margin {
              value
              currency
              displayValue
            }
            notAvailableIds
            shippingMethods {
              id
              label
              taxes {
                value
                currency
                displayValue
              }
              price {
                value
                currency
                displayValue
              }
              total {
                value
                currency
                displayValue
              }
            }
          }
        }
        ... on ShopifyStore {
          store
          cartLines {
            quantity
            variant {
              id
            }
          }
          offer {
            subtotal {
              value
              currency
              displayValue
            }
            margin {
              value
              currency
              displayValue
            }
            notAvailableIds
            shippingMethods {
              id
              label
              taxes {
                value
                currency
                displayValue
              }
              price {
                value
                currency
                displayValue
              }
              total {
                value
                currency
                displayValue
              }
            }
          }
        }
      }
    }
    errors {
      code
      message
    }
  }
`;

const [addProduct, { loading: addLoading, data: addProductResult }] =
    useMutation<AddCartProductResult>(ADD_CART_ITEMS);

const createCartWithProducts = (product) => {
  const input: CartItemsAddInput = {
    id: cart?.id!,
    items: {},
  };

  if (product.marketplace === Marketplace.AMAZON) {
    input.items.amazonCartItemsInput = [
      { productId: product.id, quantity: 1 },
    ];
  }

  if (product.marketplace === Marketplace.SHOPIFY) {
    input.items.shopifyCartItemsInput = [
      { variantId: product.id, quantity: 1 },
    ];
  }

  addProduct({ variables: { input } });
}
6

Step 6: Fetch cart shipping methods and cost

Check if your cart looks good, and fetch the estimated checkout cost and available shipping methods for the cart.

Get an existing carts details


// Pre-requisite: Have an Apollo client initialized with the correct HTTP headers
const GET_CART = gql`
  query cart($id: ID!) {
    getCart(id: $id) {
      id,
      stores {
        ... on AmazonStore {
          store
          cartLines {
            quantity,
            product{
              id
            }
          }
          offer {
          subtotal {
            value
            currency
            displayValue
          }
          margin {
            value
            currency
            displayValue
          }
          notAvailableIds
          shippingMethods {
            id
            label
            taxes {
              value
              currency
              displayValue
            }
            price {
              value
              currency
              displayValue
            }
            total {
              value
              currency
              displayValue
            }
          }
          }
        }
        ... on ShopifyStore {
          store
          cartLines {
            quantity,
            variant{
              id
            }
          }
          offer {
          subtotal {
            value
            currency
            displayValue
          }
          margin {
            value
            currency
            displayValue
          }
          notAvailableIds
          shippingMethods {
            id
            label
            taxes {
              value
              currency
              displayValue
            }
            price {
              value
              currency
              displayValue
            }
            total {
              value
              currency
              displayValue
            }
          }
        }
      }
    }
  }
`;

const [getCart, { loading, data }] = useLazyQuery(GET_CART);

getCart({ variables: { id } });
7

Step 7: Update buyer identity

Update buyer identity information if it was not provided during cart creation as it is required to be able to submit the cart.

Update buyer identity for a cart

// Pre-requisite: Have an Apollo client initialized with the correct HTTP headers

export const UPDATE_BUYER_IDENTITY = gql`
  mutation updateCartBuyerIdentity($input: CartBuyerIdentityUpdateInput!) {
    updateCartBuyerIdentity(input: $input) {
      cart {
        id
        stores {
          ... on AmazonStore {
            store
            cartLines {
              quantity
              product {
                id
              }
            }
            offer {
              subtotal {
                value
                currency
                displayValue
              }
              margin {
                value
                currency
                displayValue
              }
              notAvailableIds
              shippingMethods {
                id
                label
                taxes {
                  value
                  currency
                  displayValue
                }
                price {
                  value
                  currency
                  displayValue
                }
                total {
                  value
                  currency
                  displayValue
                }
              }
            }
          }
          ... on ShopifyStore {
            store
            cartLines {
              quantity
              variant {
                id
              }
            }
            offer {
              subtotal {
                value
                currency
                displayValue
              }
              margin {
                value
                currency
                displayValue
              }
              notAvailableIds
              shippingMethods {
                id
                label
                taxes {
                  value
                  currency
                  displayValue
                }
                price {
                  value
                  currency
                  displayValue
                }
                total {
                  value
                  currency
                  displayValue
                }
              }
            }
          }
        }
      }
      errors {
        code
        message
      }
    }
  }
`;

const [updateBuyerIdentity, { data }] = useMutation(UPDATE_BUYER_IDENTITY);

const input = {
  id: cartId,
  buyerIdentity: {
    city,
    address1,
    address2,
    firstName,
    lastName,
    email,
    phone,
    postalCode,
    provinceCode,
    countryCode,
  },
};

updateBuyerIdentity({ variables: { input } });
8

Step 8: Submit your cart

Submit your cart via rye-pay and Spreedly iFrame.

Submit cart via rye-pay

import { RyePay, SubmitStoreResult, SubmitCartResult } from '@rye-api/rye-pay';

const ryePay = new RyePay();

const loadSpreedly = () => {
    ryePay.init({
      apiKey,
      numberEl: 'spreedly-number',
      cvvEl: 'spreedly-cvv',
      environment: prod,
      onReady: () => {
        // Customize card number field and cvv field
        ryePay.setStyle(
          'number',
          'display:inline; width: 30%; border-radius: 3px; border: 1px solid #ccc;',
        );
        ryePay.setStyle(
          'cvv',
          'display: inline; width: 30%; border-radius: 3px; border: 1px solid #ccc;',
        );
      },
      onErrors: (errors: SpreedlyError[]) => {
        for (const { key, message, attribute } of errors) {
          console.log(`new error: ${key}-${message}-${attribute}`);
        }
      },
      enableLogging: true,
      onIFrameError: (err: FrameError) => {
        console.log(`frameError: ${JSON.stringify(err)}`);
      }
    });
  };

loadSpreedly();

const submit = () => {
  ryePay.submit({
    first_name: 'John',
    last_name: 'Doe',
    month: '04',
    year: '2025',
    cartId: 'cartId', // IMPORTANT! Make sure the cartId is valid
    address1: 'address1',
    address2: 'address2',
    zip: 'zip',
    city: 'city',
    country: 'country',
    state: 'state',
    selectedShippingOptions: [],
    shopperIp: 'xxx.xxx.x.x', // IMPORTANT! Make sure this is set correctly
  });
}

submit();
9

Step 9: Display the results of the transaction

The result of theryePay.submit should return the cart data and any possible errors that occurred during the submission of the cart. Errors can occur on the Cart level and the Store level:

  • For the cart level: result.errors will provide an array of errors related to submitting the cart with appropriate error messages and codes
  • For the store level: result.cart.stores[idx].errors will provide an array of errors related to submitting the order to the store with appropriate error messages and codes
10

Step 10: Cart management

  • To update the number of existing products in the cart, use the updateCartItems mutation.
  • To remove existing products from the cart, use the deleteCartItems mutation.
  • To remove the entire cart, use the removeCart mutation.

Next steps