diff --git a/packages/join-block/join.php b/packages/join-block/join.php index 289d43d..3947e1a 100644 --- a/packages/join-block/join.php +++ b/packages/join-block/join.php @@ -3,7 +3,7 @@ /** * Plugin Name: Common Knowledge Join Flow * Description: Common Knowledge join flow plugin. - * Version: 1.4.46 + * Version: 1.4.47 * Author: Common Knowledge * Text Domain: common-knowledge-join-flow * License: GPLv2 or later diff --git a/packages/join-block/readme.txt b/packages/join-block/readme.txt index 9ef9e0d..44c417f 100644 --- a/packages/join-block/readme.txt +++ b/packages/join-block/readme.txt @@ -4,7 +4,7 @@ Tags: membership, subscription, join Contributors: commonknowledgecoop Requires at least: 5.4 Tested up to: 7.0 -Stable tag: 1.4.46 +Stable tag: 1.4.47 Requires PHP: 8.2 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html @@ -107,6 +107,8 @@ Need help? Contact us at [hello@commonknowledge.coop](mailto:hello@commonknowled == Changelog == += 1.4.47 = +* Fix: retrying a custom-amount join after a declined card failed with a Stripe idempotency error, because a new Stripe price was created on every attempt = 1.4.46 = * Fix: members with an address line over 50 characters were not added to Action Network = 1.4.45 = diff --git a/packages/join-block/src/Services/StripeService.php b/packages/join-block/src/Services/StripeService.php index c07d64e..ee6d064 100644 --- a/packages/join-block/src/Services/StripeService.php +++ b/packages/join-block/src/Services/StripeService.php @@ -273,10 +273,12 @@ public static function getOrCreateOneTimePriceForProduct($product, float $amount $existingPrices = \Stripe\Price::search([ 'query' => "active:'true' AND product:'{$product->id}' AND type:'one_time' AND currency:'{$currency}'", + 'limit' => 100, ]); - foreach ($existingPrices->data as $price) { - if ($price->unit_amount === $stripeAmount) { + // Products can hold hundreds of prices, so look beyond the first page. + foreach ($existingPrices->autoPagingIterator() as $price) { + if ((int) $price->unit_amount === $stripeAmount) { $joinBlockLog->info("One-time price for product '{$product->id}' amount {$stripeAmount} already exists."); return $price; } @@ -565,17 +567,28 @@ public static function getOrCreatePriceForProduct($product, $amount, $currency, // Stripe requires the price in lowest denomination of the currency. E.G. cents for USD, pence for GBP. // So we multiply the amount by 100 to get the price in this format. // We store the amount in whole units of the currency, e.g. dollars for USD, pounds for GBP. - $stripePrice = $amount * 100; + // + // The cast matters: callers pass floats, and Stripe returns unit_amount + // as an int, so a float here never strictly equals an existing price. + // That made every custom-amount join create a fresh Price, which in + // turn changed the subscription request on every retry and tripped + // Stripe's idempotency check (see RE-174). + $stripePrice = (int) round(((float) $amount) * 100); + // Stripe stores currencies lowercase; plan config uses uppercase. + $currency = strtolower((string) $currency); try { $joinBlockLog->info("Searching for existing Stripe price for recurring product '{$product->id}' with currency '{$currency}' and amount {$stripePrice}"); $existingPrices = \Stripe\Price::search([ 'query' => "active:'true' AND product:'{$product->id}' AND type:'recurring' AND currency:'{$currency}'", + 'limit' => 100, ]); - foreach ($existingPrices->data as $price) { - if ($price->unit_amount === $stripePrice) { + // Products can hold hundreds of prices, so look beyond the first page. + foreach ($existingPrices->autoPagingIterator() as $price) { + $priceInterval = $price->recurring->interval ?? null; + if ((int) $price->unit_amount === $stripePrice && $priceInterval === $interval) { $joinBlockLog->info("Recurring price for product '{$product->id}' with currency '{$currency}' and amount {$stripePrice} already exists."); return $price; } diff --git a/packages/join-block/tests/StripePriceReuseTest.php b/packages/join-block/tests/StripePriceReuseTest.php new file mode 100644 index 0000000..c9f326f --- /dev/null +++ b/packages/join-block/tests/StripePriceReuseTest.php @@ -0,0 +1,288 @@ + 'Custom', + 'amount' => '1', + 'allow_custom_amount' => true, + 'frequency' => 'monthly', + 'currency' => 'USD', + 'description' => '', + 'stripe_price_id' => 'price_default', + ]; + + protected function setUp(): void + { + parent::setUp(); + Monkey\setUp(); + + Monkey\Functions\when('sanitize_title')->alias(function ($title) { + $title = strtolower((string) $title); + $title = preg_replace('/[^a-z0-9]+/', '-', $title); + return trim($title, '-'); + }); + + global $joinBlockLog; + $joinBlockLog = new class { + // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps + public function info(string $msg, array $ctx = []): void {} + + // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps + public function warning(string $msg, array $ctx = []): void {} + + // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps + public function error(string $msg, array $ctx = []): void {} + }; + + \Stripe\Stripe::setApiKey('sk_test_fake'); + $this->stripe = $this->fakeStripe(); + \Stripe\ApiRequestor::setHttpClient($this->stripe); + } + + protected function tearDown(): void + { + global $joinBlockLog; + $joinBlockLog = null; + \Stripe\ApiRequestor::setHttpClient(null); + Monkey\tearDown(); + parent::tearDown(); + } + + /** + * A minimal in-memory Stripe: one product, a list of prices that search + * returns in pages, and a record of every subscription request. + */ + private function fakeStripe(): object + { + return new class implements \Stripe\HttpClient\ClientInterface { + public array $prices = []; + public array $createdPrices = []; + public array $subscriptionRequests = []; + public array $priceSearchQueries = []; + + public function addPrice(int $unitAmount, string $currency = 'usd', ?string $interval = 'month'): string + { + $id = 'price_' . (count($this->prices) + 1); + $this->prices[] = [ + 'id' => $id, + 'object' => 'price', + 'active' => true, + 'product' => 'prod_test', + 'unit_amount' => $unitAmount, + 'currency' => $currency, + 'type' => $interval ? 'recurring' : 'one_time', + 'recurring' => $interval ? ['interval' => $interval] : null, + ]; + return $id; + } + + public function request($method, $absUrl, $headers, $params, $hasFile, $apiMode = 'v1') + { + $path = parse_url($absUrl, PHP_URL_PATH); + parse_str((string) parse_url($absUrl, PHP_URL_QUERY), $query); + // stripe-php hands GET parameters over separately, not in the URL. + if ($method === 'get') { + $query = array_merge($query, (array) $params); + } + + if ($method === 'get' && $path === '/v1/products/search') { + $body = $this->searchResult('/v1/products/search', [[ + 'id' => 'prod_test', + 'object' => 'product', + 'name' => 'Membership: Custom', + ]], $query); + } elseif ($method === 'get' && $path === '/v1/prices/search') { + $this->priceSearchQueries[] = $query['query'] ?? ''; + if (count($this->priceSearchQueries) > 50) { + throw new \RuntimeException('Runaway price search pagination'); + } + $type = str_contains($query['query'] ?? '', "type:'one_time'") ? 'one_time' : 'recurring'; + $matching = array_values(array_filter( + $this->prices, + fn ($p) => $p['type'] === $type + )); + $body = $this->searchResult('/v1/prices/search', $matching, $query); + } elseif ($method === 'post' && $path === '/v1/prices') { + $id = $this->addPrice( + (int) $params['unit_amount'], + $params['currency'], + $params['recurring']['interval'] ?? null + ); + $this->createdPrices[] = $params; + $body = $this->prices[count($this->prices) - 1]; + } elseif ($method === 'post' && $path === '/v1/subscriptions') { + $key = null; + foreach ($headers as $header) { + if (stripos($header, 'Idempotency-Key:') === 0) { + $key = trim(substr($header, strlen('Idempotency-Key:'))); + } + } + $this->subscriptionRequests[] = ['params' => $params, 'idempotencyKey' => $key]; + $body = ['id' => 'sub_test', 'object' => 'subscription', 'status' => 'incomplete']; + } else { + throw new \RuntimeException("Unexpected Stripe request: $method $absUrl"); + } + + return [json_encode($body), 200, []]; + } + + /** Page through $items the way Stripe's search API does. */ + private function searchResult(string $url, array $items, array $query): array + { + $limit = (int) ($query['limit'] ?? 10); + $offset = (int) ($query['page'] ?? 0); + $page = array_slice($items, $offset, $limit); + $hasMore = $offset + $limit < count($items); + + return [ + 'object' => 'search_result', + 'url' => $url, + 'data' => $page, + 'has_more' => $hasMore, + 'next_page' => $hasMore ? (string) ($offset + $limit) : null, + ]; + } + }; + } + + private function product(): \Stripe\Product + { + return \Stripe\Product::constructFrom(['id' => 'prod_test', 'object' => 'product']); + } + + // ------------------------------------------------------------------------- + // The RE-174 regression + // ------------------------------------------------------------------------- + + public function testRetryingACustomAmountJoinSendsAnIdenticalSubscriptionRequest(): void + { + $customer = \Stripe\Customer::constructFrom(['id' => 'cus_test', 'object' => 'customer']); + $key = 'join_sub_same_session'; + + // The form posts the custom amount as a string, as in production. + StripeService::createSubscription($customer, $this->customPlan, '1', null, false, false, $key); + StripeService::createSubscription($customer, $this->customPlan, '1', null, false, false, $key); + + $this->assertCount(1, $this->stripe->createdPrices, 'The retry should reuse the price made by the first attempt.'); + $this->assertCount(2, $this->stripe->subscriptionRequests); + + [$first, $retry] = $this->stripe->subscriptionRequests; + $this->assertSame($key, $first['idempotencyKey']); + $this->assertSame($key, $retry['idempotencyKey']); + $this->assertSame( + $first['params'], + $retry['params'], + 'Stripe rejects a reused idempotency key if the request parameters differ.' + ); + } + + // ------------------------------------------------------------------------- + // Price matching + // ------------------------------------------------------------------------- + + public function testExistingRecurringPriceIsReusedForAFloatAmount(): void + { + $existing = $this->stripe->addPrice(500); + + $price = StripeService::getOrCreatePriceForProduct($this->product(), 5.0, 'usd', 'month'); + + $this->assertSame($existing, $price->id); + $this->assertSame([], $this->stripe->createdPrices); + } + + public function testFractionalAmountsRoundToWholeMinorUnits(): void + { + // 3.3 * 100 is 329.99999999999994 as a float; truncating would give 329. + $existing = $this->stripe->addPrice(330); + + $price = StripeService::getOrCreatePriceForProduct($this->product(), 3.3, 'usd', 'month'); + + $this->assertSame($existing, $price->id); + $this->assertSame([], $this->stripe->createdPrices); + } + + public function testNewPricesAreCreatedWithAnIntegerAmount(): void + { + StripeService::getOrCreatePriceForProduct($this->product(), 3.3, 'usd', 'month'); + + $this->assertCount(1, $this->stripe->createdPrices); + $this->assertSame(330, $this->stripe->createdPrices[0]['unit_amount']); + } + + public function testUppercasePlanCurrencyIsSearchedAndCreatedLowercase(): void + { + StripeService::getOrCreatePriceForProduct($this->product(), 1.0, 'USD', 'month'); + + $this->assertStringContainsString("currency:'usd'", $this->stripe->priceSearchQueries[0]); + $this->assertSame('usd', $this->stripe->createdPrices[0]['currency']); + } + + public function testPriceWithTheSameAmountButADifferentIntervalIsNotReused(): void + { + // The donation product is shared across tiers, so it can hold monthly + // and yearly prices for the same amount. + $this->stripe->addPrice(500, 'usd', 'year'); + + $price = StripeService::getOrCreatePriceForProduct($this->product(), 5.0, 'usd', 'month'); + + $this->assertCount(1, $this->stripe->createdPrices); + $this->assertSame('month', $price->recurring->interval); + } + + public function testMatchingRecurringPriceOnALaterSearchPageIsFound(): void + { + // Production products hold hundreds of prices; search returns pages. + for ($i = 1; $i <= 150; $i++) { + $this->stripe->addPrice(10000 + $i); + } + $existing = $this->stripe->addPrice(500); + + $price = StripeService::getOrCreatePriceForProduct($this->product(), 5.0, 'usd', 'month'); + + $this->assertSame($existing, $price->id); + $this->assertSame([], $this->stripe->createdPrices); + } + + public function testMatchingOneTimePriceOnALaterSearchPageIsFound(): void + { + for ($i = 1; $i <= 150; $i++) { + $this->stripe->addPrice(10000 + $i, 'usd', null); + } + $existing = $this->stripe->addPrice(500, 'usd', null); + + $price = StripeService::getOrCreateOneTimePriceForProduct($this->product(), 5.0, 'USD'); + + $this->assertSame($existing, $price->id); + $this->assertSame([], $this->stripe->createdPrices); + } +} diff --git a/packages/join-e2e/tests/settings/features-integrations.spec.ts b/packages/join-e2e/tests/settings/features-integrations.spec.ts index 1d38f70..aed46a7 100644 --- a/packages/join-e2e/tests/settings/features-integrations.spec.ts +++ b/packages/join-e2e/tests/settings/features-integrations.spec.ts @@ -92,7 +92,8 @@ test.describe('Use Stripe', () => { expect(priceCreated?.body).toMatchObject({ product: 'prod_e2e_1', unit_amount: '700', - currency: 'GBP', + // Stripe stores currencies lowercase, so prices are searched for and created that way. + currency: 'gbp', recurring: { interval: 'month' }, }); expect(productCreated?.headers.authorization).toBe('Bearer sk_test_e2e'); diff --git a/packages/join-flow/src/index.tsx b/packages/join-flow/src/index.tsx index c30d87d..022e721 100644 --- a/packages/join-flow/src/index.tsx +++ b/packages/join-flow/src/index.tsx @@ -23,7 +23,7 @@ const init = () => { const sentryDsn = getEnvStr("SENTRY_DSN"); Sentry.init({ dsn: sentryDsn, - release: "1.4.46" + release: "1.4.47" }); if (getEnv("USE_CHARGEBEE")) {