5

I'm trying to use 2checkout REST API

https://knowledgecenter.2checkout.com/API-Integration/REST_5.0_Reference#/introduction/authentication/json-encoded-requests

Here's a snippet of how i try to request

const axios = require('axios')
const moment = require('moment')
const saltedMd5 = require('salted-md5');

let now = moment().format('YYYY-MM-DD HH:MM:SS')
let vendorCode = '250207358831'

let toHash = vendorCode.length + vendorCode + now.length + now

let salt = '~0CSl)!M@4rZ|zX5QR&s'
const hash = saltedMd5(toHash, salt)

axios.get('https://api.2checkout.com/rest/5.0/subscriptions/?Email=customer%40email.com&AvangateCustomerReference=1234567&ExternalCustomerReference=abcdefg&Page=1&Limit=10&PurchasedBefore=2015-12-29&PurchasedAfter=2015-01-15&ExpireBefore=2016-05-22&ExpireAfter=2015-07-23&Type=regular&Aggregate=false', {
  headers: {
    'X-Avangate-Authentication': `code="${vendorCode}" date="${now}" hash="${hash}"`,
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
}).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})

It returns status code 500. Does someone know how to retrieve subscriptions using the 2checkout API?

1
  • solved this issue? Commented Sep 2, 2020 at 6:55

2 Answers 2

0
class TwoCheckoutService {
    tco: {
        domain:string;
        apiUrl: string,
        apiUser:string,
        apiPass:string,
        sellerId:string,
        privateKey:string,
        secretKey:string,
        demo:boolean,
    };

    constructor(private userService: UserService) {
        this.tco = {=
            apiUrl: 'https://api.2checkout.com/rest/6.0',
            apiUser: "=",                              
            apiPass: "=",                              
            sellerId: "=",                                    
            privateKey: "=",     
            secretKey: "=",                                  
            demo: true,                                             
            // sandbox: false                                         
        };
    }

    private async _getAuthHeaders(): Promise<{[key:string]: string}> {

        var code = this.tco.sellerId;
        var date = moment().utc().format('YYYY-MM-DD hh:mm:ss');
        var stringToHash = code.toString().length + code + date.toString().length + date;
        var hmac = crypto.createHmac('md5', this.tco.secretKey);
        hmac.update(stringToHash, 'utf8');
        
        var hash  = hmac.digest('hex')
        var authHeader = `code="${code}" date="${date}" hash="${hash}"`

        return {
            'X-Avangate-Authentication': authHeader,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        };
    }

    async getProducts() {
        var url = this.tco.apiUrl + '/products/';
        var headers = await this._getAuthHeaders();
        console.log(headers);
        var res = await Axios.get(url, {
            headers: headers,
            params: {
                'Limit': 10,
                'Page': 1,
            },
            validateStatus: (status)=>true
        });

        if(res.status === 200) return res.data;
        return {
            error:  true,
            data: res.data,
            url: url,
            headers: headers
        }
    }
}

#This is an example in typescript nodejs ##requirements

  • crypto
  • axios
  • 2checkout api credentials
Sign up to request clarification or add additional context in comments.

Comments

0

Following is working nodejs code to fetch subscriptions using rest api v6 (Documentation: https://app.swaggerhub.com/apis/2Checkout-API/api-rest_documentation/6.0-oas3#/Subscription/get_subscriptions_)

const fetch = require('node-fetch');
const crypto = require('crypto');

const API_URL = 'https://api.2checkout.com/rest/6.0/subscriptions/';
const MERCHANT_CODE = 'TODO: set merchant code';
const SECRET_KEY = 'TODO: replace with secret key from https://secure.2checkout.com/cpanel/webhooks_api.php';
const LIMIT = 100;

function generateAuthHeader() {
    const requestDate = new Date().toISOString().slice(0, 19).replace('T', " "); // UTC Format: YYYY-MM-DD HH:MM:SS
    const stringToHash = `${MERCHANT_CODE.length}${MERCHANT_CODE}${requestDate.length}${requestDate}`;

    const hash = crypto.createHmac('sha256', SECRET_KEY).update(stringToHash).digest('hex');

    return `code="${MERCHANT_CODE}" date="${requestDate}" hash="${hash}" algo="sha256"`;
}

async function fetchSubscriptions(page = 1) {
    try {
        const url = `${API_URL}?Page=${page}&Limit=${LIMIT}&RecurringEnabled=true`;
        console.log(`Fetching Page: ${page}...`);

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Avangate-Authentication': generateAuthHeader(),
            },
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json();
        console.log(`Fetched ${data.Items.length} subscriptions on Page ${page}`);

        if (data.Items.length === LIMIT) {
            await fetchSubscriptions(page + 1);
        }

    } catch (error) {
        console.error('Error fetching subscriptions:', error.message);
    }
}

fetchSubscriptions();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.