• This repository has been archived on 24/Jul/2024
  • Stars
    star
    173
  • Rank 219,529 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript & Node.js SDKs for the Elastic Path Commerce Cloud eCommerce API

Elastic Path Commerce Cloud JavaScript SDK

npm version License: MIT contributions welcome follow on Twitter

A simple to use API interface to help get you off the ground quickly and efficiently with your Elastic Path Commerce Cloud JavaScript apps.

📚 API reference📚 Elastic Path Commerce Cloud

🛠 Installation

Install the package from npm and import in your project.

npm install --save @moltin/sdk

⛽️ Usage

To get started, instantiate a new Moltin client with your store credentials.

Note: This requires an Elastic Path Commerce Cloud account.

// JavaScript
import { gateway as MoltinGateway } from '@moltin/sdk'

const Moltin = MoltinGateway({
  client_id: 'XXX'
})

// Node.js
const MoltinGateway = require('@moltin/sdk').gateway

const Moltin = MoltinGateway({
  client_id: 'XXX',
  client_secret: 'XXX'
})

Alternatively you can include the UMD bundle via UNPKG like so:

<script src="https://unpkg.com/@moltin/sdk"></script>

<script>
  const Moltin = moltin.gateway({
    client_id: 'XXX'
  });
</script>

Note: If you're using webpack, you'll need to add the following to your projects configuration file.

node: {
  fs: 'empty'
}

You can now authenticate with the Moltin service 🎉

Moltin.Authenticate().then(response => {
  console.log('authenticated', response)
})

Check out the API reference to learn more about authenticating and the available endpoints.

Custom Host

If you're an enterprise customer with your own infrastructure, you'll need to specify your API URL when instantiating:

const Moltin = MoltinGateway({
  client_id: 'XXX',
  host: 'api.yourdomain.com'
})

Custom Storage

By default the Elastic Path Commerce Cloud SDK persists data to window.localStorage in the browser and node-localstorage in Node. If this doesn't suit your needs you can override the default storage with a MemoryStorageFactory which will persist data for the life cycle of the JavaScript VM:

import { gateway as MoltinGateway, MemoryStorageFactory } from '@moltin/sdk'

const Moltin = MoltinGateway({
  client_id: 'XXX',
  storage: new MemoryStorageFactory()
})

Or alternatively, create your own storage factory by passing in an object which implements the following interface:

interface StorageFactory {
  set(key: string, value: string): void;
  get(key: string): string | null;
  delete(key: string): void;
}

Multiple Gateways

You can support multiple gateways with a name property when initializing the gateway.

name should be unique to avoid sharing storage keys with the other gateways of the same name.

import { gateway as EPCCGateway } from "@moltin/sdk"

const gatewayOne = EPCCGateway({
    name: "my-first-gateway",
    client_id: 'XXX'
})

const gatewayTwo = EPCCGateway({
    name: "my-second-gateway",
    client_id: 'XXX'
})

Storage keys used for storage solutions are prefixed with the name provided and end with the relevant feature e.g. my-first-gateway_ep_cart, my-first-gateway_ep_credentials and my-first-gateway_ep_currency.

If no name property is provided to the EPCCGateway function, the legacy naming is maintained: mcart, moltinCredentials and mcurrency

Included Headers

There are currently several optional headers you can pass into the configuration, which include application, language and currency.

You can pass them into the config used by the gateway like this:

// JavaScript
import { gateway as MoltinGateway } from '@moltin/sdk'
// const MoltinGateway = require('@moltin/sdk').gateway -> for Node

const Moltin = MoltinGateway({
    client_id: 'XXX',
    client_secret: 'XXX'
    currency: 'YEN',
    language: 'en',
    application: 'my-app'
})

Retries

In case the server responds with status 429 - "Too Many Requests" SDK will wait for some time and retry the same API request up to a given number of times. You can fine tune this logic through following config parameters:

const Moltin = MoltinGateway({
    client_id: 'XXX',
    client_secret: 'XXX',
    retryDelay: 1000,
    retryJitter: 500,
    fetchMaxAttempts: 4
})

In case of a 429 response SDK will wait for retryDelay milliseconds (default 1000) before attempting to make the same call. If the server responds with 429 again it will wait for 2 * retryDelay ms, then 3 * retryDelay ms and so on. On top of that the random value between 0 and retryJitter (default 500) will be added to each wait. This would repeat up to fetchMaxAttempts (default 4) times.

Throttling (Rate Limiting)

SDK supports throttling through use of throttled-queue library. Unlike the throttle functions of popular libraries, throttled-queue will not prevent any executions. Instead, every execution is placed into a queue, which will be drained at the desired rate limit. You can control throttling through following parameters:

const Moltin = MoltinGateway({
    client_id: 'XXX',
    client_secret: 'XXX',
    throttleEnabled: true,
    throttleLimit: 3,
    throttleInterval: 125
})

This feature is disabled by default and to enable it you need to set throttleEnabled to true. Once enabled you can use throttleLimit (default 3) and throttleInterval (default 125) to define what is the maximum number of calls per interval. For example setting throttleLimit = 5, throttleInterval = 1000 means maximum of 5 calls per second.

Handling File Upload

Files can be uploaded to the EPCC file service with the Moltin.Files.Create method. You should pass a FormData object as described in the documentation.

In a Node.js environment, where you may be using an alternative FormData implementation, you can include a second parameter to represent the Content-Type header for the request. This must be multipart/form-data and must include a boundary. For example, using the form-data package:

const FormData = require('form-data')
const formData = new FormData()
formData.append('file', buffer)

const contentType = formData.getHeaders()['content-type']

Moltin.Files.Create(formData, contentType)

Referencing a file stored elsewhere

If you want to create a file by simply referencing a file stored elsewhere, you can use this helper method:

Moltin.Files.Link('https://cdn.external-host.com/files/filename.png')

Just pass the URL to the Link method and creation will be handled for you.

TypeScript Support

The Elastic Path Commerce Cloud JavaScript SDK is fully supported in Typescript.

Imported module will contain all interfaces needed to consume backend services. i.e:

import * as moltin from '@moltin/sdk';

const product: moltin.ProductBase = {...}

If you do not want to use the namespace, you can extend the interfaces and define them yourself, like so:

// You can name the interface anything you like
interface Product extends product.ProductBase {
}

const product: Product = {...}

Here is an example of a simple product creation:

import { Moltin, gateway, ProductBase, Resource } from '@moltin/sdk';

async function main() {
  const g: Moltin = gateway({client_id, client_secret});
  const auth = await g.Authenticate();

  const newProduct: ProductBase = {
    type: "product",
    name: "My Product",
    slug: "my-prod",
    sku: "my-prod",
    manage_stock: false,
    description: "Some description",
    status: "draft",
    commodity_type: "physical",
    price: [
      {
        amount: 5499,
        currency: "USD",
        includes_tax: true
      }
    ]
  };

  const nP: Resource<Product> = await g.Products.Create(newProduct);
}

You can also extend any base interface compatible with flows to create any custom interfaces that you might be using by re-declaring @moltin/sdk module. Following example adds several properties to ProductsBase interface that correspond to flows added to the backend.

In your project add a definition file (with a .d.ts extension) with a following code:

import * as moltin from '@moltin/sdk';

declare module '@moltin/sdk' {

  interface Weight {
    g: number;
    kg: number;
    lb: number;
    oz: number;
  }

  interface ProductBase {
    background_color: string;
    background_colour: string | null;
    bulb: string;
    bulb_qty: string;
    finish: string;
    material: string;
    max_watt: string;
    new: string | null;
    on_sale: string | null;
    weight: Weight;
  }

}

This will affect base interface and all other Product interfaces that inherit from base interface so added properties will be present when creating, updating, fetching products.

❤️ Contributing

We love community contributions. Here's a quick guide if you want to submit a pull request:

  1. Fork the repository
  2. Add a test for your change (it should fail)
  3. Make the tests pass
  4. Commit your changes (see note below)
  5. Submit your PR with a brief description explaining your changes

Note: Commits should adhere to the Angular commit conventions.

Make sure you have Prettier installed for your editor with ESLint integration enabled.

⚡️ Development

The SDK is built with ES6 modules that are bundled using Rollup.

If you want to roll your own bundle, or make changes to any of the modules in src, then you'll need to install the package dependencies and run rollup while watching for changes.

npm install
npm start

To run test

npm test

You can learn more about the Rollup API and configuration here.

Terms And Conditions

  • Any changes to this project must be reviewed and approved by the repository owner.
  • For more information about the license, see MIT License.

More Repositories

1

laravel-cart

Laravel Facade and Service Provider for Moltin\Cart
PHP
276
star
2

react-demo-store

Moltin + React powered online store
JavaScript
195
star
3

cart

Shopping cart composer package
PHP
110
star
4

currency

Handles currency calculations, storage etc
PHP
108
star
5

nextjs-demo-store

🛍 Moltin powered Next.js storefront
JavaScript
101
star
6

gatsby-demo-store

Elastic Path + Gatsby powered online store
JavaScript
93
star
7

php-sdk

Community built SDK for using Moltin with PHP
PHP
47
star
8

ios-sdk

Swift SDK for the Moltin eCommerce API
Swift
37
star
9

shopkit

Powerful, embeddable cart and checkout.
JavaScript
30
star
10

vue-demo-store

JavaScript
27
star
11

ios-swift-example

A Swift demo app using the Moltin iOS SDK.
Swift
23
star
12

gatsby-source-moltin

🚀 Gatsby source plugin for building Elastic Path Commerce Cloud powered eCommerce websites
JavaScript
21
star
13

framework

Lightweight store framework built using Slim, Twig, Bootstrap and the Moltin SDK.
CSS
19
star
14

moltin-request

🎮 Minimal Elastic Path Commerce Cloud API request library for Node
TypeScript
17
star
15

ruby-sdk

Moltin Ruby SDK
Ruby
16
star
16

examples

⚡️ Collection of examples using the Moltin API
JavaScript
16
star
17

terraform-stack

A group of more formulated Terraform modules
HCL
13
star
18

nextjs-tutorial-code

JavaScript
12
star
19

react-redux-moltin-boilerplate

boilerplate setup for a moltin store built in react + redux
JavaScript
12
star
20

moltin-micro-checkout

💳 One-click moltin purchase with Stripe
JavaScript
10
star
21

redis-scripts

Script to maintain Redis databases
Shell
9
star
22

react-microsite

🛍 Moltin powered microsite built with Create React App & Shopkit
JavaScript
9
star
23

swift-demo-app

An eCommerce example App in swift
Swift
7
star
24

menagerie

Serverless image resizing, manipulation, and optimzation S3 proxy
TypeScript
7
star
25

terraform-rancher-ha

Terraform Rancher HA cluster in AWS
HCL
7
star
26

python-sdk

Moltin python SDK
Python
6
star
27

android-sdk

Java
6
star
28

lua-multipart-parser

A simple HTTP multipart encoder/decoder for Lua
Lua
6
star
29

ios-objc-example

An Objective-C demo app using the Moltin iOS SDK.
Objective-C
6
star
30

terraform-modules

A group of base Terraform modules
HCL
6
star
31

docs.moltin.com

6
star
32

ios-swift-tutorial

A getting started with Swift tutorial for the Moltin iOS eCommerce SDK.
Swift
5
star
33

android-example

Java
5
star
34

integration-server-example-php

A small example of an integration server written in PHP to demonstrate the usage of moltin integration webhooks
PHP
5
star
35

tax

Tax calculations for Moltin\Cart
PHP
4
star
36

progressive-web-app

Example commerce app using Ionic and Angular 2
JavaScript
3
star
37

developers.moltin.com

3
star
38

moltin-next-checkout

⚡️ Next.js demo for one-click moltin purchasing
JavaScript
3
star
39

csharp-sdk

C# API interface and SDK
C#
2
star
40

node-demo-store

JavaScript
2
star
41

applepayexample-completed

This is the a completed project for the apple pay demo guide. https://developers.moltin.com/guides/apple-google-pay
Swift
2
star
42

moltin-product-importer

Import products from a CSV into Moltin though the API
JavaScript
2
star
43

cordova-square-reader

A Cordova plugin to interface with the native Square Reader SDK libraries.
Swift
2
star
44

transfer-flow-data

Serverless function to pass flow data from cart items on to order items
JavaScript
1
star
45

apple-pay-swift-tutorial

A getting started with Apple Pay tutorial for the Moltin iOS eCommerce SDK, written in Swift.
Swift
1
star
46

tf_azure_public_ip

A Terraform module to provide a Public IP on Microsoft Azure.
HCL
1
star
47

v2-import

A quick n dirty PHP import script for products & categories in v2
PHP
1
star
48

ansible-rancher-agent

Ansible role to register host to our Rancher server
Shell
1
star
49

moltin-stripe-paymentintents

💳 SCA compliant payments with Moltin and Stripe
JavaScript
1
star
50

moltin-paymentrequest-api

💳 Demoing the Payment Request API with moltin
JavaScript
1
star
51

moltin-shippo-rates

📦 Get shipping rates for orders by Shippo for your moltin store
JavaScript
1
star
52

ios-getting-started-tutorial

A getting started tutorial for the Moltin iOS eCommerce SDK.
Objective-C
1
star
53

moltin-shippo-tracking

📦 Update orders via a webhook with a delivery status by Shippo
JavaScript
1
star