按照协议解析临时密钥响应时出现问题

问题描述 投票:0回答:1

在我的 iOS 应用程序中,我已将 stripe 与 sk_test 集成,现在我尝试使用 sk_live。我已在 .env、index.js、runtimeconfig.json 和 remoteconfig.json 中配置了实时密钥。当我尝试运行时,我的应用程序崩溃并显示错误消息,

断言失败:无法解析遵循 STPCustomerEphemeralKeyProvider 协议的临时密钥响应。确保您的后端将临时密钥的未修改 JSON 发送到您的应用程序。有关更多信息,请参阅 https://stripe.com/docs/mobile/ios/basic#prepare-your-api

所以看着我的条纹日志,我发现

resource_missing - 客户 没有这样的客户:'cus_...';测试模式下存在类似的对象,但使用实时模式密钥来发出此请求。

这让我意识到很多客户都处于测试模式。因此,我从测试模式中删除了所有客户信息,并部署了一个将他们的帐户转换为实时模式的功能。

以下是我在注册我的应用程序时创建 Stripe 客户的方法。

   exports.createStripeCustomer = functions.auth.user().onCreate(async (user) => {
    console.log('started');
  return await stripe.customers.create({
    email: user.email,
  }).then(async (customer) => {
    console.log('user stripe account id ----------->' + customer.id);
    return await stripe.accounts.create({
      type: 'express',
      country: 'US',
      email: user.email,
      capabilities: {
        card_payments: {requested: true},
        transfers: {requested: true}
      },
    }).then(async (connectedAccount) => {
      console.log('user connected account id ----------->' + connectedAccount.id);
      const data = {
        customer_id: customer.id,
        connected_account_id: connectedAccount.id
      };
      return await admin.database().ref(`/stripe_customers/${user.uid}`).set(data)
      .then(async (result) => {
        return result;
      });
    });
  });
});

下面是我尝试使用的将所有以前的测试帐户转换为真实帐户的功能。

    exports.createStripeCustomerIfDeleted = functions.https.onCall(async (data, context) => {
  try {
    // Check if the user is authenticated
    if (!context.auth) {
      throw new functions.https.HttpsError('unauthenticated', 'User is not authenticated');
    }

    // Check if the user already has a Stripe customer ID
    const snapshot = await admin.database().ref(`/stripe_customers/${context.auth.uid}`).once('value');
    if (!snapshot.exists()) {
      console.log('User does not have a Stripe customer ID');
      return { success: true, message: 'User does not have a Stripe customer ID' };
    }

    // Check if the Stripe customer already exists in Stripe
    const stripeCustomer = await stripe.customers.list({ email: context.auth.token.email });
    if (stripeCustomer.data.length > 0) {
      console.log('Stripe customer already exists in Stripe');
      return { success: true, message: 'Stripe customer already exists in Stripe' };
    }

    // Delete the corresponding entry from Firebase
    await admin.database().ref(`/stripe_customers/${context.auth.uid}`).remove();
    console.log('Firebase entry deleted');

    // Create a new Stripe customer
    const customer = await stripe.customers.create({
      email: context.auth.token.email,
    });

    // Create a new Stripe connected account
    const connectedAccount = await stripe.accounts.create({
      type: 'express',
      country: 'US',
      email: context.auth.token.email,
      capabilities: {
        card_payments: { requested: true },
        transfers: { requested: true }
      },
    });

    // Save the Stripe customer ID and connected account ID to the database
    const newData = {
      customer_id: customer.id,
      connected_account_id: connectedAccount.id
    };
    await admin.database().ref(`/stripe_customers/${context.auth.uid}`).set(newData);

    console.log('Stripe customer created successfully');
    return { success: true, message: 'Stripe customer created successfully' };
  } catch (error) {
    console.error('Error creating Stripe customer:', error);
    throw new functions.https.HttpsError('internal', 'Error creating Stripe customer', error);
  }
});

这样做的目的是

  1. 检查帐户是否已通过身份验证(应该是)
  2. 检查stripe_customers下是否有引用当前用户UID的数据。 (之所以存在,是因为这些信息是在用户创建帐户后创建的)
  3. 然后检查stripe中是否有当前用户的匹配信息。如果有,则什么也不做。如果没有,请执行第 4 步。
  4. 删除firebase中stripe_customers下与UID相关的所有信息。
  5. 重新创建 stripe customerId 和 linkedAccountId 并将其保存到 firebase 和 stripe。
  6. 要快乐。

此外,在确认用户已通过身份验证后,我在应用程序委托中调用此函数。

    func createStripeCustomerIfDeleted(for userId: String) {
    // Call the Firebase Callable Cloud Function to create a Stripe customer
    Functions.functions().httpsCallable("createStripeCustomerIfDeleted").call(["userId": userId]) { (result, error) in
        if let error = error as NSError? {
            print("Error triggering createStripeCustomerIfDeleted: \(error.localizedDescription)")
            // Handle error
        } else if let data = result?.data as? [String: Any] {
            if let success = data["success"] as? Bool, success {
                print("Stripe customer created successfully")
                // Handle success
            } else {
                print("Failed to create Stripe customer: \(data["message"] as? String ?? "Unknown error")")
                // Handle failure
            }
        }
    }
}

当我检查我的功能日志时,我看到

收到请求 - 客户 ID:

我到底遗漏了什么?

最后,我认识到这种情况只有在我使用 sk_live 时才会发生。如果我将 sk_test 与真实账户一起使用,则不会发生这种情况。但如果我将 sk_live 与测试或真实账户一起使用,我就会看到这些问题。

swift firebase firebase-realtime-database google-cloud-functions stripe-payments
1个回答
0
投票

您的后端很可能使用测试模式 API 密钥,而您的 iOS 应用程序使用实时模式可发布密钥。这就是为什么客户是在测试模式下创建的,而在实时模式下无法访问该客户,根据

resource_missing - customer No such customer: 'cus_...'; a similar object exists in test mode, but a live mode key was used to make this request.

您应该保持我们的后端API密钥和前端可发布密钥一致,它们应该都处于测试模式或实时模式。

© www.soinside.com 2019 - 2024. All rights reserved.