Quick Integration Guide for Alchemy Pay Ramp Fiat-to-Crypto Payment Solution

Quickly enable cryptocurrency payments using the Alchemy Pay service

Introduction

Alchemy Pay is a leading crypto payment solution that combines traditional financial systems with blockchain technology, allowing users to purchase cryptocurrencies through fiat currencies and complete payments. Whether it's an e-commerce platform, app, or online service, integrating Alchemy Pay can help your users conduct cryptocurrency transactions using a payment method they're familiar with, simplifying the user experience and expanding your market.

Official documentation link

Advantages

  • User-friendly: Users can use familiar fiat payment methods to complete cryptocurrency purchases without too much learning cost.

  • Quick integration: With simple APIs and developer documentation, you can complete the integration of Alchemy Pay in a short time.

  • Security: Alchemy Pay uses multi-layer encryption and strict risk control systems to ensure the security and legality of transactions.

Reference example

https://github.com/CocosTechLabs/flappy-bird

Quick Integration Steps

1. Register as a Merchant and Get API Keys

First, go to the Alchemy Pay Official Website and register a merchant account to obtain your APPID and SECRETKEY. These will be used in your API requests for signing and authentication.

2. Implement API Signing

All Alchemy Pay API requests require signature authentication. The API signature is generated using HMAC-SHA256 encryption, and the signing process requires combining parameters in a specific format and generating the signature accordingly.

Here is the code for API signing:

import crypto from 'crypto';
import { URL } from 'url';

function apiSign(timestamp: string, method: string, requestUrl: string, body: string, secretkey: string): string {
    const content = timestamp + method.toUpperCase() + getPath(requestUrl) + getJsonBody(body);
    const signVal = crypto.createHmac('sha256', secretkey)
        .update(content, 'utf8')
        .digest('base64');

    return signVal;
}

function getPath(requestUrl: string): string {
    const uri = new URL(requestUrl);
    const path = uri.pathname;
    const params = Array.from(uri.searchParams.entries());

    if (params.length === 0) {
        return path;
    } else {
        const sortedParams = [...params].sort(([aKey], [bKey]) => aKey.localeCompare(bKey));
        const queryString = sortedParams.map(([key, value]) => `${key}=${value}`).join('&');
        return `${path}?${queryString}`;
    }
}

function getJsonBody(body: string): string {
    let map;

    try {
        map = JSON.parse(body);
    } catch (error) {
        map = {};
    }

    if (Object.keys(map).length === 0) {
        return '';
    }

    map = removeEmptyKeys(map);
    map = sortObject(map);

    return JSON.stringify(map);
}

The function apiSign generates the signature based on the timestamp, HTTP method, request URL, and the request body. You can refer to the official documentation for more details: API Sign Documentation.

3. Obtain User Token

Before a user can make a payment, you need to obtain a token for that user. This requires the user's email or a unique identifier (UID). Here’s how you can implement this functionality:

export async function getAlchemyPayToken(params: GetTokenParams): Promise<GetTokenResponse> {
    const timestamp = String(Date.now());
    const method = 'POST';
    const requestUrl = `${config.ALCHEMYPAY_DOMAIN}/open/api/v4/merchant/getToken`;
    const body = JSON.stringify(params);

    const sign = apiSign(timestamp, method, requestUrl, body, config.ALCHEMYPAY_SECRETKEY);

    try {
        const response = await axios.post<GetTokenResponse>(requestUrl, body, {
            headers: {
                'Content-Type': 'application/json',
                'appid': config.ALCHEMYPAY_APPID,
                'timestamp': timestamp,
                'sign': sign
            }
        });

        return response.data;
    } catch (error) {
        console.error('Error getting AlchemyPay token:', error);
        throw error;
    }
}

This function accepts the user’s email or UID as input and retrieves an accessToken for that user, which will be used to create payment orders.

4. Create a Payment Order

Once you’ve obtained the user token, you can create a payment order using the Alchemy Pay API. After the order is created, you will receive a payment URL that the user can use to complete the payment. Here’s an example implementation:

export async function createAlchemyPayOrder(params: CreateOrderParams, accessToken: string): Promise<CreateOrderResponse> {
    const timestamp = String(Date.now());
    const method = 'POST';
    const requestUrl = `${config.ALCHEMYPAY_DOMAIN}/open/api/v4/merchant/trade/create`;
    const body = JSON.stringify(params);
    const sign = apiSign(timestamp, method, requestUrl, body, config.ALCHEMYPAY_SECRETKEY);

    try {
        const response = await axios.post<CreateOrderResponse>(requestUrl, body, {
            headers: {
                'Content-Type': 'application/json',
                'appid': config.ALCHEMYPAY_APPID,
                'timestamp': timestamp,
                'access-token': accessToken,
                'sign': sign
            }
        });

        return response.data;
    } catch (error) {
        console.error('Error creating AlchemyPay order:', error);
        throw error;
    }
}

The request body for creating the order includes details such as the payment amount, cryptocurrency type, merchant order number, and other necessary information. Once the order is successfully created, you will receive a payment URL that you can provide to the user for payment.

5. Handle Callback Notifications

After the payment is completed, Alchemy Pay will send a notification to your system via the callback URL you provided in the payment order. You need to implement logic to handle this notification and confirm the payment status.

Conclusion

By integrating Alchemy Pay Ramp, you can provide users with a fast and simple fiat-to-crypto purchasing experience. This guide walks you through the essential steps for API signing, obtaining user tokens, and creating payment orders, ensuring you can quickly deploy the payment solution.

For more detailed information, please refer to the Alchemy Pay API Documentation.

Last updated