如何使用set 2 checkout身份验证标头?

问题描述 投票:0回答:2
https://knowledgecenter.2checkout.com/api-integration/rest_5.0_reference#/introduction/authentication/json-encoded-requestsists

这里是我尝试要求的片段 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) })

返回状态代码500。是否有人知道如何使用2Checkout API检索订阅?

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
        }
    }
}

#这是打字稿nodejs中的一个示例 ##要求
node.js 2checkout
2个回答
0
投票
crypto

2CHECKOUTAPI凭据
  • tolowing正在使用REST API V6(文档:
  • Https://app.swaggerhub.com/apis/2checkout-api/api/api-rest_documentation/6.0-oas3#/subscription/get_subscript_
  • 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();

0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.