如何使用AWS Lambda Node.js服务器实施Braintree并生成带有承诺的客户端令牌?

洛佩兹

我正在尝试clientToken从Braintree网关生成我应该从我的lambda连接到的Braintree,当我的UI触发它时,根据此处找到的文档,我需要该Lambda进行连接:https : //developers.braintreepayments.com/start/hello-服务器/节点

我试图在Lambda函数中实现此功能,我需要导出该函数以供我的无服务器应用程序的其余部分使用。此外,我尝试import根据需要使用ES6语句来导入Braintree功能。虽然,即使使用require语句,也会出现相同的错误

这是我的Lambda函数:

import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
import braintree from "braintree";

export async function main(event, context) {
    /*
            All secrets are declared in the serverless template for the specific function
            and stored in AWS SecretsManger
    */
    // create a Braintree gateway
    let gateway = braintree.connect({
        environment: braintree.Environment.Sandbox, // either Sandbox or Production
        merchantId: process.env.merchantId, // these come from the Lambda's environmental variables
        publicKey: process.env.publicKey,
        privateKey: process.env.privateKey
    });

    /*************************************************
    * Braintree related functions based on documentation at
    * https://developers.braintreepayments.com/start/hello-server/node
    */
    /////////////////////////////////////
    // get a client token from Braintree and send it to the client
    /////////////////////////////////////

    const getClientToken = (options = {}) => {

        console.log("getting client token: ", gateway); // console.logs will show up in AWS Cloudwatch

        let customerId = options && options.hasOwnProperty("customerID")
          ? options.customerID
          : null;

        // THIS IS THE ONLY THING THAT PRINTS TO CONSOLE!!!
        console.log("This is customerID: ", customerId);

        // NONE OF THIS WORKS!!!???
        gateway.clientToken.generate({})
            .then((res) => {
                console.log("maybe result: ", res); // <---- None of these print!?!?
                console.log("Maybe success/fail: ", res.success);
                console.log("maybe token: ", res.clientToken);
                // Code here
            })
            .catch (err => {
                console.log("ERROR CAUGHT: ", err);
                failure({
                  status: false,
                  error: "did it trigger 2: " + err
                });
            }
        );
    };

  // try to execute API calls
  try {
    switch (event.pathParameters.txnMethod) {

      case "get-client-token":
        // call getClientToken with the parsed version of optional body if present, otherwise call it with nothing
        getClientToken(
          event.hasOwnProperty("body")
            ? JSON.parse(event.body) 
            : null
        );
        break;

      default:
        failure({
          status: false,
          error: "invalid query string"
        });
        break;
    }
  } catch (error) {
    failure({
      status: false,
      error: "Did it trigger 1: " + error
    });
  }
}

console实际上,只有第一个语句会打印任何内容,之后所有内容都会自下而上失败gateway.clientToken.generate({}),最重要的是它会失败而不会引发任何错误...。

当我输出 console.log("getting client token: ", gateway);

我得到这样的数据结构:

getting client token:  BraintreeGateway {
  config:
   Config {
     timeout: 60000,
     apiVersion: '5',
     graphQLApiVersion: '2018-09-10',
     publicKey: 'sbxkeys',
     privateKey: 'sbxkeys',
     merchantId: 'sbxkeys',
     environment:
      Environment {
        server: 'api.sandbox.braintreegateway.com',
        port: '443',
        authUrl: 'https://auth.sandbox.venmo.com',
        ssl: true,
        graphQLServer: 'payments.sandbox.braintree-api.com',
        graphQLPort: '443' } },
  graphQLClient: GraphQLClient { _service: GraphQL { config: [Config] } },
  http:
   Http {
     config:
      Config {
        timeout: 60000,
        apiVersion: '5',
        graphQLApiVersion: '2018-09-10',
        publicKey: 'sbxkeys',
        privateKey: 'sbxkeys',
        merchantId: 'sbxkeys',
        environment: [Environment] } },
  addOn:
   AddOnGateway {
     gateway: [Circular],
     config:
      Config {
        timeout: 60000,
        apiVersion: '5',
        graphQLApiVersion: '2018-09-10',
        publicKey: 'sbxkeys',
        privateKey: 'sbxkeys',
        merchantId: 'sbxkeys',
        environment: [Environment] } },
  address:
   AddressGateway {
     gateway: [Circular],
     config:
      Config {
        timeout: 60000,
        apiVersion: '5',
        graphQLApiVersion: '2018-09-10',
        publicKey: 'sbxkeys',
        privateKey: 'sbxkeys',
        merchantId: 'sbxkeys',
        environment: [Environment] } },
  clientToken:
   ClientTokenGateway {
     gateway: [Circular],
     config:
      Config {
        timeout: 60000,
        apiVersion: '5',
        graphQLApiVersion: '2018-09-10',
        publicKey: 'sbxkeys',
        privateKey: 'sbxkeys',
        merchantId: 'sbxkeys',
        environment: [Environment] } },
  creditCard:
   CreditCardGateway {
     gateway: [Circular],
     config:
      Config {
        timeout: 60000,
        apiVersion: '5',
        graphQLApiVersion: '2018-09-10',
        publicKey: 'sbxkeys',
        privateKey: 'sbxkeys',
        merchantId: 'sbxkeys',
        environment: [Environment] } },
  creditCardVerification:


...........



所以我尝试将以下内容更改gateway.clientToken.generate({})为:

  • gateway.BraintreeGateway.clientToken.generate({}) 希望`generate()方法与该结构相关联,以下是我对其进行测试时收到的错误:
TypeError: Cannot read property 'clientToken' of undefined"

我认为那里什么也没有。

如何使用ES6导入语句在无服务器lambda函数中生成Braintree令牌?

洛佩兹

我意识到这些lambda是异步函数,并且由于我们必须等待Braintree返回的响应,因此我们必须声明嵌套async/await语句的正确组合

下面的代码是我通过正确的Promise链实现提交的最终实现,以正确处理async流程:

import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
import braintree from "braintree";

export async function main(event, context) {
    /*
            All secrets are declared in the serverless template for the specific function
            and stored in AWS SecretsManger
    */
    // create a Braintree gateway
    let gateway = braintree.connect({
        environment: braintree.Environment.Sandbox, // either Sandbox or Production
        merchantId: process.env.merchantId, // these come from the Lambda's environmental variables
        publicKey: process.env.publicKey,
        privateKey: process.env.privateKey
    });

    /*************************************************
    * Braintree related functions based on documentation at
    * https://developers.braintreepayments.com/start/hello-server/node
    */
    /////////////////////////////////////
    // get a client token from Braintree and send it to the client
    /////////////////////////////////////
    const getClientToken = async (options = {}) => {
        console.log("Getting client token...");
        //console.log("hasOwnProps: ", options.hasOwnProperty("customerID") );

        let customerId = options && options.hasOwnProperty("customerID")
          ? options.customerID
          : null;

        console.log("This is customerID: ", customerId);

        return await gateway.clientToken.generate({});
    };

    /////////////////////////////////////
    // purchase an item using Braintree's transaction method
    /////////////////////////////////////
    const purchaseItem = async (purchaseInformation) => {
        /* console.log(
          "purchaseInformation: ",
          util.inspect(purchaseInformation, { showHidden: false, depth: null })
        ); */
        return await gateway.transaction.sale(
            {
                amount: purchaseInformation.amount,
                paymentMethodNonce: purchaseInformation.nonce,
                options: {
                    submitForSettlement: true
                }
            }
        );
    };

  /*************************************************
   * Enter here
   */
  // view the event that was received
  console.log("event: ", event);
  let result;

  // try to execute API calls
  try {
    switch (event.pathParameters.txnMethod) {
      case "get-client-token":
        // call getClientToken with the parsed version of optional body if present, otherwise call it with nothing
        await getClientToken(
            event.hasOwnProperty("body")
                ? JSON.parse(event.body) 
                : null)
            .then((res) => {
                //console.log("maybe result: ", res);
                //console.log("Maybe success/fail: ", typeof(res.success));
                //console.log("maybe token: ", res.clientToken);
                // Code here
                if(res.success.toString() === "true"){

                    //console.log("SUCCESS token: ", res.clientToken);
                    return context.succeed(success({
                        status: true,
                        clientToken: res.clientToken
                    }));
                } else {

                    return failure({
                        status: false,
                        error: "Braintree ClientToken Failure."
                    });
                }
            })
            .catch (err => {
                console.log("ERROR CAUGHT: ", err);

                return failure({
                  status: false,
                  error: "did it trigger 2: " + err
                });
            });
        break;

      case "purchase-item":
        console.log("purchasing item");
        const data = JSON.parse(event.body);
        await purchaseItem(data)
            .then((res) => {
                // Code here
                if(res.success === true){
                    console.log("~~~~~~~~~~~");
                    console.log("This is RES: ", res);
                    console.log("This is ERR>RES: ", res.ErrorResponse);
                    return context.succeed(success({
                        status: true,
                        TxnAuth: res
                    }));
                } else if (res.success === false) {
                    console.log("#################");
                    console.log(res.result);
                    return failure({
                        status: false,
                        error: "Error validating payment server information"
                    });
                } else {

                    return failure({
                        status: false,
                        error: "Braintree Server Failure."
                    });
                }
            })
            .catch (err => {
                console.log("ERROR CAUGHT: ", err);
                console.log("*********");
                return failure({
                    status: false,
                    error: "did it trigger 3pmt: " + err
                });
            });
        break;

      default:
        return failure({
          status: false,
          error: "invalid query string"
        });
        break;
    }
  } catch (error) {
    return failure({
      status: false,
      error: "API Call to Braintree Failed: " + error
    });
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用无服务器模块在本地调试AWS Lambda Node.js?

如何使用Node.js AWS Lambda发送HTTP请求?

如何使用带有Node.js代码的AWS Lambda从URL下载文件

如何使用AWS Lambda和Node.js将项目放入AWS DynamoDb

如何使用node.js和aws-sdk从lambda访问aws参数存储

使用 node.js 的 AWS Lambda 不执行承诺功能

如何使用Node.js中的图层在AWS SAM模板的lambda中使用共享代码?

如何将node.js快速服务器转换为AWS Lambda?

如何使用无服务器框架通过AWS API网关返回用Node.js编写的AWS Lambda函数的错误?

如何将AWS Secret Manager与Node.js Lambda一起使用

如何在Node.js服务器上的多个客户端之间同步数据

如何将jwt从swift客户端传递到node.js服务器

如何从Node.js服务器流到客户端

Node.js,如何在客户端退出后使服务器保持活动状态?

如何在Node.js中将文件从服务器发送到客户端

如何在Node / Express中将JS从客户端移动到服务器?

在客户端和Node.js服务器上使用静态JavaScript文件

在本地使用Node.js时客户端和服务器的时间不同

如何在Node.js中使用带有API Gateway的AWS Lambda发送二进制响应?

如何检查 Node.JS AWS Lambda 数据?

如何从AWS Lambda node.js异步函数返回数据?

AWS Lambda-使用Node.js获取路径参数

使用Node JS将AWS Lambda XML转换为JSON

我在客户端使用 next.js 工作,在服务器端使用 node.js 表达

如何使用Node.js在服务器上接收与客户端发布数据格式相同的发布数据?

如何使用node对客户端(html,js,css)进行整数运算并在服务器中运行

如何使用jquery ajax和node js在快速框架中将数据从客户端传递到服务器?

如何使用node.js将表单数据从客户端脚本发送到服务器脚本

如何使用客户端JavaScript从MongoDB和没有框架的Node.js服务器中查找并返回数据?