You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Twilio Functions调用USAePay API返回504错误及Buffer废弃警告咨询

问题修复方案

1. 运行错误(callback调用问题)排查

你现有代码的核心问题是混淆了Node.js常规HTTP服务和Twilio Functions的运行逻辑:

  • Twilio Functions是无服务器运行环境,无需自行引入express、body-parser搭建HTTP服务,你定义的app.post路由不会被触发,且全程没有调用callback()函数,导致函数执行超时抛出错误。
  • 正确逻辑是直接在handler函数内发起USAePay接口请求,请求结束后调用callback()返回结果即可。

2. buffer废弃警告修复

new Buffer()构造方法早已被Node.js废弃,只需将对应代码替换为Buffer.from()即可:
将

var authKey = new Buffer(apikey + ":" + apihash).toString('base64');

修改为

const authKey = Buffer.from(apikey + ":" + apihash).toString('base64');

修正后完整代码

exports.handler = function(context, event, callback) {
    const request = require('request');
    const sha256 = require('sha256');

    // 构造API鉴权信息
    const seed = "abcdefghijklmnop";
    const apikey = "xxxxxxxxxxxxxxxxxxxxxxxx";
    const prehash = apikey + seed;
    const apihash = 's2/'+ seed + '/' + sha256(prehash);
    const authKey = Buffer.from(apikey + ":" + apihash).toString('base64');
    const authorization = "Basic " + authKey;

    // 直接发起USAePay扣款请求
    const options = {
        url: 'https://sandbox.usaepay.com/api/v2/transactions',
        method: 'POST',
        json: true,
        headers: {
            "Authorization": authorization
        },
        body: {
            "command": "cc:sale",
            "amount": "5.00",
            "amount_detail": {
                "tax": "1.00",
                "tip": "0.50"
            },
            "creditcard": {
                "cardholder": "John doe",
                "number": "4000100011112224",
                "expiration": "0919",
                "cvc": "123",
                "avs_street": "1234 Main",
                "avs_zip": "12345"
            }
        }
    };

    request(options, (err, apiRes, body) => {
        if(err) {
            // 错误场景调用callback返回错误
            return callback(null, {
                statusCode: 500,
                body: JSON.stringify({message: "internal server error"})
            });
        }
        // 成功场景调用callback返回结果
        return callback(null, {
            statusCode: 200,
            body: JSON.stringify({
                result: body.result,
                error: body.error || ""
            })
        });
    });
};

注:request库已经停止维护,后续如果出现兼容问题,可以替换为Twilio Functions内置的got或axios库发起请求。

内容的提问来源于stack exchange,提问作者jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 21:36:04