UNPKG

@stylusapparel/opv3-merchant-api-nodejs

Version:

This is the official NodeJs wrapper for connecting to the StylusOP API V3

79 lines (68 loc) 2.19 kB
const stylusWrapper = require('../index.js'); const { MERCHANT_ID, MERCHANT_NAME, MERCHANT_SECRET, LIMIT_ORDERS } = require('./constants'); const stylusClient = stylusWrapper.createClient(MERCHANT_ID, MERCHANT_SECRET, { merchantName: MERCHANT_NAME, // Replace with your merchant name / ID sandbox: true, apiVersion: 'v3', tokenType: 'basic', }); stylusClient .oauthToken() .then((accessToken) => { console.log(`Access token: ${accessToken}`); }) .catch((error) => { console.error('Error getting the access token: ', error); handleError(error); }) .then(fetchOrders) .then((orders) => { console.log('Retrieved all orders: ', orders); }) .catch((error) => { console.error('Error fetching orders: ', error); handleError(error); }); /** * Example of how to fetch orders with pagination * @param {*} startOffset * @returns */ async function fetchOrders(startOffset = 0) { const allOrders = []; let currentOffset = startOffset; try { while (true) { const ordersResponse = await stylusClient.orders.list({ limit: LIMIT_ORDERS, offset: currentOffset, }); console.log(`Retrieved ${ordersResponse.orders.length} orders (offset: ${currentOffset})`); console.log(ordersResponse.orders.map((order) => `ID: ${order.orderKey} - Customer: ${order.shippingInfo.shipTo.name} - Status: "${order.status}"`).join('\n')); allOrders.push(...ordersResponse.orders); // If there are no more orders, break the loop if (!ordersResponse.page.hasMore) { break; } // Sleep for 5 seconds before fetching the next page await new Promise((resolve) => setTimeout(resolve, 5000)); currentOffset += LIMIT_ORDERS; } return allOrders; } catch (error) { console.error(`Error fetching orders at offset ${currentOffset}:`, error); throw error; } } // Error handler // function handleError(err) { // Handle error // if (err.status === 403 || err.status === 401 || err.errorCode === 'TOKEN_INVALID') { // Unauthorized console.error(`Error!\n(${err.errorCode}) ${err.message} ${JSON.stringify(err.rawError)}`); } else { // Other error console.error(`Error!\n(${err.errorCode}) ${err.message}`); } process.exit(1); }