我正在开发一个 Go 应用程序,该应用程序涉及根据用户的登录轮询 Stripe 来获取客户和订阅信息。目标是检查客户或其订阅是否存在并且处于活动状态。但是,我遇到了一个问题,每当调用这些轮询函数时,似乎都会创建一个额外的客户,这不是预期的行为。
我实现了两个函数:pollForCustomerByLogin 和 pollForCustomerSubscriptionsByLogin,它们分别使用 Stripe API 来搜索客户及其订阅。这些函数应该只搜索和记录结果,而不创建或修改任何数据。这是轮询函数的简化版本:
// This function polls for a customer by login until found or max attempts reached.
func pollForCustomerByLogin(t *testing.T, login string, maxAttempts int, sleepDuration time.Duration) {
for attempt := 0; attempt < maxAttempts; attempt++ {
// Define search parameters
searchParams := &stripe.CustomerSearchParams{
SearchParams: stripe.SearchParams{
Query: fmt.Sprintf("Metadata[\"login\"]:\"%s\"", login),
Single: true,
},
}
// Perform search
result := customer.Search(searchParams)
if result.Next() {
fmt.Println("Customer found:", result.Customer().ID)
return
}
fmt.Printf("Customer with login %s not found. Attempt %d of %d\n", login, attempt+1, maxAttempts)
time.Sleep(sleepDuration)
}
t.Errorf("Customer with login %s not found after %d attempts", login, maxAttempts)
}
// This function polls for active subscriptions of a customer by login until found or max attempts reached.
func pollForCustomerSubscriptionsByLogin(t *testing.T, login string, maxAttempts int, sleepDuration time.Duration) {
for attempt := 0; attempt < maxAttempts; attempt++ {
// Define search parameters
searchParams := &stripe.SubscriptionSearchParams{
SearchParams: stripe.SearchParams{
Query: fmt.Sprintf("status:\"active\" AND metadata[\"login\"]:\"%s\"", login),
Single: true,
},
}
// Perform search
result := subscription.Search(searchParams)
if result.Next() {
fmt.Println("Subscription for Customer found:", result.Subscription().ID)
return
}
fmt.Printf("Subscription for Customer with login %s not found. Attempt %d of %d\n", login, attempt+1, maxAttempts)
time.Sleep(sleepDuration)
}
t.Errorf("Subscription for Customer with login %s not found after %d attempts", login, maxAttempts)
}
我希望这些功能仅搜索和记录现有客户或订阅,而不创建或修改任何 Stripe 数据。然而,运行这些轮询函数后,我注意到在 Stripe 中创建了一个额外的客户,这令人费解,因为函数中没有明确的创建逻辑。
您共享的代码不会创建新客户。
要弄清楚是什么创建了您看到的新客户,我建议:
Logs
部分POST /v1/customers
请求