javascript - 如何处理 promise 链中的多个错误?

标签 javascript reactjs stripe-payments aws-amplify

我使用 AWS Amplify 进行身份验证,使用 Stripe 进行付款以创建注册页面。

问题:我找不到将电子邮件和密码部分(来自 AWS Amplify)的验证与付款信息部分(来自 Stripe)相结合的方法。

我当前的代码创建一个 Stripe token 并调用 API(带有有效的付款信息),然后处理来自 userSignupRequest 的错误消息,该错误消息负责处理电子邮件和密码字段。

如何使用付款信息验证电子邮件和密码,然后在 AWS 和 Stripe 中创建帐户?

enter image description here

  // Stripe payment process
  this.props.stripe.createToken(
    {
      email: this.state.email
    }
  ).then(result => {
    // PROBLEM: Form server validation from Stripe
    if(result.error){
      return this.setState({ errors: { errorMsg: result.error.message }, isLoading: false })
    }

    // if success, create customer and subscription with result.token.id
    const apiName = 'NameOfAPI';
    const path = '/stripe/signup';
    let myInit = {
      body: {
        "stripeToken": result.token.id,
        "email": this.state.email
      }
    }

    API.post(apiName , path, myInit).then(reponse => {
      this.props.userSignupRequest(this.state.email, this.state.password, reponse).then(user => {
        this.setState({
          confirmAccount: true,
          isLoading: false,
          userEmail: this.state.email,
          errors: {}
        })
        this.props.history.push('/signup#confirm-account')
      }).catch(err => {
        // PROBLEM: Form server validation 
        this.setState({ errors: { errorMsg: err.message }, isLoading: false })
      })

    }).catch(err => {
      console.log(err)
      this.setState({ errors: { errorMsg: err }, isLoading: false })
    });

  })

最佳答案

看起来我们有一个非常相似的堆栈。我的解决方案是在服务器端处理所有事情。您需要为 lambda 函数授予适当的 IAM 权限才能访问 Cognito。下面的代码有点长。我用async/await ,这确实为我清理了一切。不过,您需要将 Lambda 与节点 8 结合使用才能使用 async/await。

我验证一切都与客户端的正确格式匹配(即电子邮件确实是电子邮件,密码的长度正确)。我意识到唯一可能出现的错误是 Cognito 的“现有用户”错误。这个想法是:在尝试使用 Stripe 注册该用户之前测试该用户是否存在。 Stripe 无法“测试”用户的信用卡是否有效。要么全有,要么全无。如果有效,它将通过,如果无效,您将收到错误。如果成功,您就可以使用 Cognito 注册该用户,并且知道您不应该收到错误(您已经在客户端验证了电子邮件和密码,并且您知道该用途尚不存在)。

作为引用,这里是 aws-sdk for cognito .

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider({
  region: "region",
  userPoolId: "cognito_user_pool_id",
});

module.exports.signUpUser = (payload) => {
  const usernamePayload = {
    UserPoolId: "cognito_user_pool_id",
    Username: payload.email,
  };

  // I use emails for usernames.

    new Promise((resolve, reject) => {
      cognito.adminGetUser(usernamePayload, (error, response) => {
        if (error && error.code === 'UserNotFoundException') {
          resolve(false);
        } else if (error) {
          reject(error);
        } else {
          // if adminGetUser doesn't fail, it means the username exists
          resolve(true);
        }
      });
    }).then((usernameExists) => {
      if (!usernameExists) {
        // run stripe API stuff
        // always run before sign up below to catch stripe errors
        // and return those errors to client
        // before you sign up the user to Cognito

        // since you've already verified the user does not exist
        // it would be rare for an error to come up here
        // as long as you validate passwords and emails client-side
        const signUpPayload = {
          ClientId: "cognito_user_pool_client_id",
          Username: payload.email,
          Password: payload.password,
          UserAttributes: [
            {
              Name: 'email',
              Value: payload.email,
            },
          ],
        };

          new Promise((resolve, reject) => {
            cognito.signUp(signUpPayload, (error, response) => {
              if (error) {
                reject(error);
              } else {
                resolve(response);
              }
            });
          }).catch((error) => {
            // you should hopefully encounter no errors here
            // once you get everything setup correctly
            console.log(error);
          })
      } else {
        // means username already exists, send error to client
        // saying username exists
      }
    }).catch((error) => {
      // may want to dispatch this error to client
      console.log(error);
    });

  return null;
};

关于javascript - 如何处理 promise 链中的多个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50580499/

相关文章:

javascript - 从 HTML 获取付款金额以在 Node.js 文件中收费

react-native - Stripe Connect 帐户 - return_url - 链接回 Expo 应用程序

javascript - 如何检查特定列的所有行中是否包含 "abc"

reactjs - 用于生产的 Preact 和 Webpack

javascript - 为什么每次组件重新渲染时都会运行 useEffect?

reactjs - HOC 传递属性

javascript - 如何阅读 Stripe webhook 响应

javascript - 如何根据条件附加gapi-auth2.attach Click Handler

javascript - Next.js 中动态导入模块的单例对象

javascript - 在 JQuery Mobile 的选择菜单中设置默认选择?