Skip to content

Latest commit

 

History

History
2157 lines (1459 loc) · 29.9 KB

README.md

File metadata and controls

2157 lines (1459 loc) · 29.9 KB

Changelly Fiat API SDK for Typescript and Javascript

This SDK allows you to work with the Changelly Fiat API in JavaScript and TypeScript. JavaScript developers will find a fully featured library with convenient functions to automate all of the method calls within the Changelly fiat API; developers using TypeScript will find a rich definition of strict types.

Using this SDK

  1. Register on the Changelly website if you don't have an account yet.
  2. Write us at psp@changelly.com to get the API keys. Indicate the email that you used for registration on the Changelly website.

Note. If you have any questions with SDK integration, don't hesitate to write us at psp@changelly.com.

This tutorial will walk you through the basics of creating a project that uses the Changelly Fiat API SDK.

  1. First, run the following command to create a default package.json file:
> npm init --y
  1. If you choose to use TypeScript, you can now add TypeScript features to this project. The following steps will install TypeScript, create a tsconfig.json file, and gain access to most built-in types for NodeJS:
> npm install typescript
> npx tsc --init
> npm install -D @types/node
  1. Add the Changelly Fiat API SDK to your project via Node Package Manager:
> npm install @changelly/fiat-api-sdk-node
  1. Set your API keys to an environment variable such as CHANGELLY_PRIVATE_KEY and CHANGELLY_PUBLIC_KEY so that it will not be committed to source control.
  2. Create a basic index.ts file for your project that creates a Changelly Fiat API client:
import { ChangellyFiatClient } from "@changelly/fiat-api-sdk-node";

const client = new ChangellyFiatClient({
  privateKey: process.env["CHANGELLY_PRIVATE_KEY"],
  publicKey: process.env["CHANGELLY_PUBLIC_KEY"],
});
  1. Make an API call and check the result:
const providers = await client.getProviderList();
const currencies = await client.getCurrencyList();

console.log({ providers, currencies });
  1. For more information, see documentation.

API Reference

ChangellyFiatClient

Changelly Fiat API Node.js SDK class.

Constructor

Create ChangellyFiatClient instance.

new ChangellyFiatClient(
  params: ChangellyFiatClientParams
): ChangellyFiatClient

Parameters

Returns ChangellyFiatClient

Methods

buildSignature

Build X-Api-Signature.

buildSignature(
  params: ChangellyBuildSignatureParams
): string;

Parameters

Returns string — Changelly X-Api-Signature

validateOrderCallbackSignature

Validate order X-Callback-Signature.

validateOrderCallbackSignature(
  signature: string,
  orderId: string
): boolean;

Parameters

  • signature: string — The serialized string with an orderId signed by Changelly private key according to the RSA-SHA256 method.
  • orderId: string — Changelly order identifier.

Returns boolean — Is callback signature valid?

getProviderList

Get extended information about On-Ramp providers to users.

getProviderList(
  config?: AxiosRequestConfig
): Promise<ChangellyGetProviderListResponse[]>;

Parameters

Returns Promise<ChangellyGetProviderListResponse[]>

getCurrencyList

Get list of supported cryptos and fiat currencies.

getCurrencyList(
  params?: ChangellyGetCurrencyListParams,
  config?: AxiosRequestConfig
): Promise<ChangellyGetCurrencyListResponse[]>;

Parameters

Returns Promise<ChangellyGetCurrencyListResponse[]>

getCountryAvailabilityList

Get list of countries where crypto purchases are supported.

getCountryAvailabilityList(
  params?: ChangellyGetCountryAvailabilityParams,
  config?: AxiosRequestConfig
): Promise<ChangellyGetCountryAvailabilityResponse[]>;

Parameters

Returns Promise<ChangellyGetCountryAvailabilityResponse[]>

getOffers

Get list of purchase offers from On-Ramp providers.

getOffers(
  params: ChangellyGetOffersParams,
  config?: AxiosRequestConfig
): Promise<ChangellyGetOffersResponse[]>;

Parameters

Returns Promise<ChangellyGetOffersResponse[]>

createOrder

Create a crypto purchase order and get a redirect URL to the purchase page. If any of the optional parameters are not provided in the request, they will be returned with the "null" value in the response.

createOrder(
  data: ChangellyCreateOrderParams,
  config?: AxiosRequestConfig
): Promise<ChangellyCreateOrderResponse>;

Parameters

Returns Promise<ChangellyCreateOrderResponse[]>

validateWalletAddress

Check if the given wallet address and (optional) extra ID are valid for the given currency.

validateWalletAddress(
  data: ChangellyValidateWalletAddressParams,
  config?: AxiosRequestConfig
): Promise<ChangellyValidateWalletAddressResponse>;

Parameters

Returns Promise<ChangellyValidateWalletAddressResponse[]>

Types

ChangellyFiatClientParams

interface ChangellyFiatClientParams {
  publicKey: string;
  privateKey: string;
  callbackPublicKey?: string;
  baseUrl?: string;
}

Properties

publicKey

string

Changelly Fiat API public key.

privateKey

string

Changelly Fiat API private key.

callbackPublicKey

string

(optional) Changelly Fiat API callback public key.

baseUrl

string

(optional) Base url of Changelly Fiat API. https://fiat-api.changelly.com/v1 by default.

ChangellyBuildSignatureParams

interface ChangellyBuildSignatureParams {
  baseUrl?: string;
  pathname: ChangellyRequestUrl | string;
  params?:
    | ChangellyGetCurrencyListParams
    | ChangellyGetCountryAvailabilityParams
    | ChangellyGetOffersParams;
  data?: ChangellyCreateOrderParams | ChangellyValidateWalletAddressParams;
}

Properties

baseUrl

string

(optional) Base url. https://fiat-api.changelly.com/v1 by default.

pathname

ChangellyRequestUrl | string

Request address.

params

ChangellyGetCurrencyListParams | ChangellyGetCountryAvailabilityParams | ChangellyGetOffersParams

(optional) Request query parameteres.

data

ChangellyCreateOrderParams | ChangellyValidateWalletAddressParams

(optional) Request body parameters.

ChangellyGetProviderListResponse

interface ChangellyGetProviderListResponse {
  code: ChangellyProvider;
  name: string;
  trustPilotRating: string;
  iconUrl: string;
}

Properties

code

ChangellyProvider

On-Ramp provider code.

name

string

On-Ramp provider's name.

trustPilotRating

string

Provider's rating on Trustpilot.

iconUrl

string

URL of On-Ramp provider's icon.

ChangellyGetCurrencyListParams

interface ChangellyGetCurrencyListParams {
  type?: ChangellyCurrency;
  providerCode?: ChangellyProvider;
}

Properties

type

ChangellyCurrency

(optional) Type of currency. If the currency type is not specified, the endpoint will return both fiat currencies and cryptocurrencies.

providerCode

ChangellyProvider

(optional) The provider whose currencies you want to view. If the On-Ramp provider code is not specified, the endpoint will return the supported currencies of all providers.

ChangellyGetCurrencyListResponse

interface ChangellyGetCurrencyListResponse {
  ticker: string;
  name: string;
  type: ChangellyCurrency;
  extraIdName: string | null;
  iconUrl: string;
  precision: string;
}

Properties

ticker

string

Currency ticker in uppercase. It is a unique identifier of the currency.

name

string

Currency name that you can specify in your interface.

type

ChangellyCurrency

Currency type.

extraIdName

string | null

Extra ID name of the cryptocurrency, for example, "Memo". Required for the following currencies: XRP, XLM, EOS, BNB. For fiat currencies and cryptocurrencies without an extra ID, extraIdName equals null. If the currency has an extra ID, you need to provide the walletExtraId parameter in the request to /v1/orders and /v1/validate-address endpoints.

iconUrl

string

URL of the currency icon.

precision

string

Currency precision. For fiat currencies, it is always equal to 2.

ChangellyGetCountryAvailabilityParams

interface ChangellyGetCountryAvailabilityParams {
  providerCode?: ChangellyProvider;
}

Properties

(optional) providerCode

ChangellyProvider

(optional) The provider whose countries you want to view. If the On-Ramp provider code is not specified, the endpoint will return the supported countries of all providers.

ChangellyGetCountryAvailabilityResponse

interface ChangellyGetCountryAvailabilityResponse {
  code: ChangellyProvider;
  name: string;
  states?: ChangellyState[];
}

Properties

code

ChangellyProvider

On-Ramp provider code.

name

string

On-Ramp provider's name.

states

ChangellyState[]

(optional) US states. Is returned if the code of the country is US.

ChangellyGetOffersParams

interface ChangellyGetOffersParams {
  providerCode?: ChangellyProvider;
  externalUserId?: string;
  currencyFrom: string;
  currencyTo: string;
  amountFrom: string;
  country: string;
  state?: string;
  ip?: string;
}

Properties

providerCode

ChangellyProvider

(optional) On-Ramp provider code.

externalUserId

string

(optional) User ID provided by you.

currencyFrom

string

Ticker of the pay-in currency in uppercase.

currencyTo

string

Ticker of the payout currency in uppercase.

amountFrom

string

Amount of currency the user is going to pay.

country

string

Country ISO 3166-1 code (Alpha-2).

state

string

(optional) State ISO 3166-2 code. Is required if the provided country is US.

ip

string

(optional) User's IP address.

ChangellyGetOffersResponse

Can be successful and fail.

Successfull offer

interface Offer {
  providerCode: ChangellyProvider;
  rate: string;
  invertedRate: string;
  fee: string;
  amountFrom: string;
  amountExpectedTo: string;
  paymentMethodOffers: ChangellyPaymentMethodOffer[];
}

Properties

providerCode

ChangellyProvider

On-Ramp provider code.

rate

string

The best rate of purchase among all payment methods. The rate includes all the fees.

invertedRate

string

Inverted rate of purchase.

fee

string

The lowest value of the total fee of purchase among all payment methods.

amountFrom

string

Amount of currency the user is going to pay.

amountExpectedTo

string

The largest amount of funds among all payment methods that the user is expected to get after the purchase.

paymentMethodOffers

ChangellyPaymentMethodOffer[]

Purchase details for each available payment type. Payment methods other than "card" will be available later.

Fail offer

interface Offer {
  providerCode: ChangellyProvider;
  errorType:
    | ChangellyErrorType.Timeout
    | ChangellyErrorType.Unavailable
    | ChangellyErrorType.Limits
    | ChangellyErrorType.Country
    | ChangellyErrorType.State
    | ChangellyErrorType.Currency
    | ChangellyErrorType.PaymentMethod
    | ChangellyErrorType.InvalidOffer;
  errorMessage: string;
  errorDetails: ChangellyErrorDetails[] | null;
}

Properties

providerCode

ChangellyProvider

On-Ramp provider code.

errorType

ChangellyErrorType (Timeout, Unavailable, Limits, Country, State, Currency, PaymentMethod, InvalidOffer)

Error type.

errorMessage

string

Error message.

errorDetails

ChangellyErrorDetails[] | null

Error details. If the error contains no details, errorDetails equals null.

ChangellyCreateOrderParams

type ChangellyCreateOrderParams = {
  externalOrderId: string;
  externalUserId: string;
  providerCode: ChangellyProvider;
  currencyFrom: string;
  currencyTo: string;
  amountFrom: string;
  country: string;
  state?: string;
  ip?: string;
  walletAddress: string;
  walletExtraId?: string;
  paymentMethod?: ChangellyPaymentMethod;
  userAgent?: string;
  metadata?: Record<string, unknown>;
};

Properties

externalOrderId

string

Order ID provided by you.

externalUserId

string

User ID provided by you.

providerCode

ChangellyProvider

On-Ramp provider code.

currencyFrom

string

Ticker of the pay-in currency in uppercase.

currencyTo

string

Ticker of the payout currency in uppercase.

amountFrom

string

Amount of currency the user is going to pay.

country

string

Country ISO 3166-1 code (Alpha-2).

state

string

(optional) State ISO 3166-2 code. Is required if the provided country is US.

ip

string

(optional) User's IP address.

walletAddress

string

Recipient wallet address. Here are 2 simple use cases of this parameter:

  • If you want to provide the cryptocurrency purchase service, you should enable the user to specify the wallet address.
  • If you want to sell your products for fiat and receive cryptocurrency in your wallet, you should specify your own wallet address.

walletExtraId

string

(optional) Property required for wallet addresses of currencies that use an additional ID for transaction processing (XRP, XLM, EOS, BNB).

paymentMethod

ChangellyPaymentMethod

(optional) The payment method code.

userAgent

string

(optional) User Agent.

metadata

Record<string, unknown>

(optional) Metadata object, which can contain any parameters you need.

ChangellyCreateOrderResponse

interface ChangellyCreateOrderResponse {
  redirectUrl: string;
  orderId: string;
  externalUserId: string;
  externalOrderId: string;
  providerCode: ChangellyProvider;
  currencyFrom: string;
  currencyTo: string;
  amountFrom: string;
  country: string;
  state: string | null;
  ip: string | null;
  walletAddress: string;
  walletExtraId: string | null;
  paymentMethod: ChangellyPaymentMethod | null;
  userAgent: string | null;
  metadata: Record<string, unknown> | null;
  createdAt: string;
}

Properties

redirectUrl

string

URL to the provider's purchase page.

orderId

string

Internal order ID provided by Fiat API.

externalUserId

string

User ID provided by you.

externalOrderId

string

Order ID provided by you.

providerCode

ChangellyProvider

On-Ramp provider code.

currencyFrom

string

Ticker of the pay-in currency in uppercase.

currencyTo

string

Ticker of the payout currency in uppercase.

amountFrom

string

Amount of currency the user is going to pay.

country

string

Country ISO 3166-1 code (Alpha-2).

state

string | null

State ISO 3166-2 code. Will be null if the provided country is not US.

ip

string | null

User's IP address.

walletAddress

string

Recipient wallet address.

walletExtraId

string | null

Property required for wallet addresses of currencies that use an additional ID for transaction processing (XRP, XLM, EOS, BNB).

paymentMethod

ChangellyPaymentMethod | null

The payment method code.

userAgent

string | null

User Agent.

metadata

Record<string, unknown> | null

Metadata object, which can contain any parameters you need. If you don't provide the metadata object in the request, null will be returned in metadata in the response. If you specify an empty object in the request, an empty object will be returned in the response.

createdAt

string

Time in ISO 8601 format.

ChangellyValidateWalletAddressParams

interface ChangellyValidateWalletAddressParams {
  currency: string;
  walletAddress: string;
  walletExtraId?: string;
}

Properties

currency

string

Cryptocurrency ticker in uppercase.

walletAddress

string

Recipient wallet address.

walletExtraId

string

(optional) Property required for wallet addresses of currencies that use an additional ID for transaction processing (XRP, XLM, EOS, BNB).

ChangellyValidateWalletAddressResponse

interface ChangellyValidateWalletAddressResponse {
  result: boolean;
  cause: "walletAddress" | "walletExtraId" | null;
}

Properties

result

boolean

Is false if the wallet address or extra ID is incorrect.

cause

"walletAddress" | "walletExtraId" | null

Specifies whether the wallet address or extra ID is incorrect. If the result is true, cause equals null.

ChangellyState

interface ChangellyState {
  code: string;
  name: string;
}

Properties

code

string

State ISO 3166-2 code.

name

string

State name.

ChangellyPaymentMethodOffer

interface ChangellyPaymentMethodOffer {
  amountExpectedTo: string;
  method: ChangellyPaymentMethod;
  methodName: string;
  invertedRate: string;
  fee: string;
}

Properties

amountExpectedTo

string

The amount of funds that the user is expected to get after the purchase.

method

ChangellyPaymentMethod

The payment method code.

methodName

string

The payment method name.

invertedRate

string

Current rate of purchase, which includes all the fees.

fee

string

Total fee of the purchase.

ChangellyErrorDetails

interface ChangellyErrorDetails {
  cause: string;
  value: string;
}

Properties

cause

string

Error cause. For example, it can equal the missing request parameter for the validation error type.

value

string

Error value.

Enumerations

ChangellyRequestUrl

enum ChangellyRequestUrl {
  ProvderList = "/v1/providers",
  CurrencyList = "/v1/currencies",
  CountryAvailability = "/v1/available-countries",
  GetOffers = "/v1/offers",
  CreateOrder = "/v1/orders",
  ValidateWalletAddress = "/v1/validate-address",
}

Members

  • ProvderList: "/v1/providers"
  • CurrencyList: "/v1/currencies"
  • CountryAvailability: "/v1/available-countries"
  • GetOffers: "/v1/offers"
  • CreateOrder: "/v1/orders"
  • ValidateWalletAddress: "/v1/validate-address"

ChangellyProvider

enum ChangellyProvider {
  Moonpay = "moonpay",
  Banxa = "banxa",
  Wert = "wert",
}

Members

  • Moonpay: "moonpay"
  • Banxa: "banxa"
  • Wert: "wert"

ChangellyCurrency

enum ChangellyCurrency {
  Crypto = "crypto",
  Fiat = "fiat",
}

Members

  • Crypto: "crypto"
  • Fiat: "fiat"

ChangellyErrorType

enum ChangellyErrorType {
  Validation = "validation",
  Timeout = "timeout",
  Unavailable = "unavailable",
  Limits = "limits",
  Country = "country",
  State = "state",
  Currency = "currency",
  PaymentMethod = "paymentMethod",
  InvalidOffer = "invalidOffer",
  Unauthorized = "unauthorized",
  TooManyRequests = "tooManyRequests",
  InternalServerError = "internalServerError",
}

Members

  • Validation: "validation" — Validation error.
  • Timeout: "timeout" — Request to the provider was not completed in the allotted time.
  • Unavailable: "unavailable" — Request failed at the provider's end.
  • Limits: "limits" — Specified pay-in amount is less than the minimum or more than the maximum value for the fiat currency.
  • Country: "country" — Specified country is not supported by the provider.
  • State: "state" — Offer requested for the United States, but the state parameter is not provided.
  • Currency: "currency" — Specified currency pair is not supported by the provider.
  • PaymentMethod: "paymentMethod" — Specified payment method is not supported by the provider.
  • InvalidOffer: "invalidOffer" — On-Ramp provider returned an invalid offer.
  • Unauthorized: "unauthorized" — Unauthorized error
  • TooManyRequests: "tooManyRequests" — Too many requests error
  • InternalServerError: "internalServerError" — Internal server error

ChangellyPaymentMethod

enum ChangellyPaymentMethod {
  Card = "card",
  Sepa = "sepa_bank_transfer",
}

Members

  • Card: "card"
  • Sepa: "sepa_bank_transfer"