store: send a Stripe idempotency key

This commit is contained in:
sh-agents committed 2026-11-01 15:27:03 +00:00
1 parent 31479dc1af
commit 13b3ac8fb4
10 files changed
+84 -21

No files matched your search

+7
View File
@@ -157,6 +157,13 @@ absent `[btcpay]` does for Bitcoin and Monero. Its keys:
it expired and logs an error. Check such orders in the Stripe Dashboard. After a restart, the
hour starts again.
The service creates each payment intent with `metadata[order]`, the order's reference:
`badge:0x<code hash>` (`code_hash` in `sx_badge_service_badge_codes`). It is not a secret,
and support finds an intent's order from it in the Dashboard. The create also sends an
`Idempotency-Key` of that reference with the amount and currency, so a buyer who sends the same order
again after the first answer was lost gets the same intent, not a second one; Stripe keeps the key
for 24 hours.
The service fills `publishable_key` into the shell at boot: the built `index.html` ships
with an empty `<meta id="stripe-publishable-key" name="stripe-publishable-key" content="">`
(`web/public/index.html`), and the listener serves a copy with the configured key
@@ -0,0 +1,14 @@
{-# LANGUAGE OverloadedStrings #-}
module StoreService.Names.Abi
( hex,
)
where
import Data.ByteArray.Encoding (Base (Base16), convertToBase)
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Text.Encoding (decodeLatin1)
hex :: ByteString -> Text
hex bs = "0x" <> decodeLatin1 (convertToBase Base16 bs)
@@ -59,9 +59,11 @@ expiresItself = \case
settleWindow :: NominalDiffTime
settleWindow = 72 * 3600
-- | odReference names the order, the same on every retry of it, and is not secret.
data OrderDraft = OrderDraft
{ odAmount :: CurrencyAmount,
odCurrency :: Text
odCurrency :: Text,
odReference :: Text
}
deriving (Eq, Show)
@@ -140,7 +140,7 @@ listOpen env@StripeEnv {seCfg} = do
let q =
[("created[gte]", Just createdGte), ("limit", Just (B8.pack (show listPageSize)))]
<> maybe [] (\a -> [("starting_after", Just (TE.encodeUtf8 a))]) after
got <- stripeApi env listWhat methodGet ["v1", "payment_intents"] q Nothing
got <- stripeApi env listWhat methodGet ["v1", "payment_intents"] q [] Nothing
case got >>= decodeStripe listWhat of
Left e -> pure (Left e)
Right IntentList {ilData, ilHasMore} ->
@@ -236,14 +236,20 @@ instance J.FromJSON CreatedIntent where
createInvoice :: StripeEnv -> ServicePaymentMethod -> OrderDraft -> IO (Either ProviderError ProviderInvoice)
createInvoice _ (SPMCrypto _) _ = pure (Left (ProviderError "stripe offers no crypto payment method"))
createInvoice env (SPMCard CPStripe) OrderDraft {odAmount = CurrencyAmount minor, odCurrency} = do
let form =
[ ("amount", B8.pack (show minor)),
("currency", TE.encodeUtf8 (T.toLower odCurrency)),
createInvoice env (SPMCard CPStripe) OrderDraft {odAmount = CurrencyAmount minor, odCurrency, odReference} = do
let amount = B8.pack (show minor)
currency = TE.encodeUtf8 (T.toLower odCurrency)
reference = TE.encodeUtf8 odReference
form =
[ ("amount", amount),
("currency", currency),
-- Only card is offered, because a redirect-based method would navigate the top window out of the embedded frame.
("allowed_payment_method_types[]", "card")
("allowed_payment_method_types[]", "card"),
("metadata[order]", reference)
]
created <- stripeApi env what methodPost ["v1", "payment_intents"] [] (Just form)
-- Stripe answers a create sent again with the same key, for 24 hours, with the intent the first one made.
idempotencyKey = B8.intercalate ":" [reference, amount, currency]
created <- stripeApi env what methodPost ["v1", "payment_intents"] [] [("Idempotency-Key", idempotencyKey)] (Just form)
pure $ created >>= decodeStripe what <&> \CreatedIntent {ciId, ciClientSecret} ->
ProviderInvoice {piProviderRef = ciId, piDestination = SPDCard CPStripe ciClientSecret}
where
@@ -251,12 +257,12 @@ createInvoice env (SPMCard CPStripe) OrderDraft {odAmount = CurrencyAmount minor
cancelInvoice :: StripeEnv -> Text -> IO (Either ProviderError ())
cancelInvoice env pid =
fmap (fmap (const ())) $ stripeApi env "cancel intent" methodPost ["v1", "payment_intents", pid, "cancel"] [] (Just [])
fmap (fmap (const ())) $ stripeApi env "cancel intent" methodPost ["v1", "payment_intents", pid, "cancel"] [] [] (Just [])
readInvoice :: StripeEnv -> Text -> IO (Either ProviderError (Maybe PaymentSignal))
readInvoice env pid = do
now <- getCurrentTime
got <- stripeApi env what methodGet ["v1", "payment_intents", pid] [("expand[]", Just "latest_charge")] Nothing
got <- stripeApi env what methodGet ["v1", "payment_intents", pid] [("expand[]", Just "latest_charge")] [] Nothing
pure $ got >>= decodeStripe what >>= signalOf now
where
what = "read intent " <> pid
@@ -312,9 +318,10 @@ stripeApi ::
Method ->
[Text] ->
Query ->
[Header] ->
Maybe [(ByteString, ByteString)] ->
IO (Either ProviderError LB.ByteString)
stripeApi StripeEnv {seCfg, seManager} what verb segments query form = do
stripeApi StripeEnv {seCfg, seManager} what verb segments query headers form = do
r <- try $ do
req0 <- parseRequest (T.unpack url)
-- applyBasicAuth must wrap the record update, because updating requestHeaders after it would drop the header it adds.
@@ -325,7 +332,8 @@ stripeApi StripeEnv {seCfg, seManager} what verb segments query form = do
requestHeaders =
("Accept", "application/json")
: ("Stripe-Version", stripeApiVersion)
: [("Content-Type", "application/x-www-form-urlencoded") | isJust form],
: [("Content-Type", "application/x-www-form-urlencoded") | isJust form]
<> headers,
requestBody = RequestBodyBS (maybe "" (renderSimpleQuery False) form)
}
withResponse req seManager $ \resp -> do
@@ -23,6 +23,7 @@ where
import StoreService.Catalog (PricedOffer (..), priceOffer)
import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultExpiryMinutes, defaultSessionMinutes)
import StoreService.Names.Abi (hex)
import StoreService.Poller (ReadHints, queueReadHint)
import StoreService.Providers (OrderDraft (..), Provider (..), ProviderError (..), ProviderInvoice (..), WebhookError (..))
import StoreService.Store.Invoices (CreateError (..), InvoicePayment (..), InvoiceRow (..), NewInvoice (..), cancelOpenInvoice, codeHashExists, createInvoiceRows, cryptoCurrencyText, getInvoice, getInvoiceByProviderRef, invoiceStatusText, newInvoiceId, paymentHolds, readCatalogRows, textToInvoiceStatus, truncateToSecond)
@@ -546,7 +547,7 @@ createAtProvider WebEnv {weStore, weConfig} provider CreateRequest {crPriceId, c
-- truncate once, so the response, the row and the provider get the same value
now <- truncateToSecond <$> getCurrentTime
let expiresAt = addUTCTime (invoiceWindow weConfig crMethod) now
draft = OrderDraft {odAmount = poAmount priced, odCurrency = poCurrency priced}
draft = OrderDraft {odAmount = poAmount priced, odCurrency = poCurrency priced, odReference = "badge:" <> hex crCodeHash}
pCreateInvoice provider crMethod draft >>= \case
Left (ProviderError e) -> failed ("provider refused to create an invoice: " <> e) providerUnavailable
Right ProviderInvoice {piProviderRef, piDestination} -> do
+2
View File
@@ -452,6 +452,7 @@ executable simplex-store-service
StoreService.Group
StoreService.Group.Command
StoreService.Log
StoreService.Names.Abi
StoreService.Options
StoreService.Orders
StoreService.Poller
@@ -780,6 +781,7 @@ test-suite simplex-chat-test
StoreService.Group
StoreService.Group.Command
StoreService.Log
StoreService.Names.Abi
StoreService.Names.Chain
StoreService.Names.Registration
StoreService.Options
+2 -1
View File
@@ -536,7 +536,8 @@ fiftyFourDollars :: OrderDraft
fiftyFourDollars =
OrderDraft
{ odAmount = CurrencyAmount 5400,
odCurrency = "usd"
odCurrency = "usd",
odReference = "badge:0x01"
}
exampleCeiling :: Int
+13 -5
View File
@@ -2,6 +2,7 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Bots.StoreService.FakeStripe
( FakeStripe (..),
@@ -104,7 +105,9 @@ data FakeState = FakeState
fsFail :: FailPlan,
fsList :: Text,
fsPageSize :: Maybe Int,
fsRequests :: [FakeRequest]
fsRequests :: [FakeRequest],
-- | The intent each Idempotency-Key created, which Stripe answers a repeated create with.
fsIdempotent :: M.Map ByteString Text
}
initialState :: FakeState
@@ -115,6 +118,7 @@ initialState =
fsFail = FailPlan {fpCalls = 0, fpStatus = 0},
fsList = "intent-list",
fsPageSize = Nothing,
fsIdempotent = M.empty,
fsRequests = []
}
@@ -290,12 +294,16 @@ fakeApp stv req respond = do
let form = parseSimpleQuery (LB.toStrict b)
amount = fromMaybe 0 (lookup "amount" form >>= readMaybe . B8.unpack)
currency = maybe "usd" TE.decodeUtf8 (lookup "currency" form)
key = lookup "Idempotency-Key" (requestHeaders req)
(pid, s) <- atomically $ do
st <- readTVar stv
let pid = "pi_test_" <> T.justifyRight 4 '0' (tshow (fsNextId st))
s = IntentState {isStatus = "requires_payment_method", isAmount = amount, isCurrency = currency}
writeTVar stv st {fsNextId = fsNextId st + 1, fsIntents = M.insert pid s (fsIntents st)}
pure (pid, s)
case (key >>= (`M.lookup` fsIdempotent st)) >>= \pid -> (pid,) <$> M.lookup pid (fsIntents st) of
Just created -> pure created
Nothing -> do
let pid = "pi_test_" <> T.justifyRight 4 '0' (tshow (fsNextId st))
s = IntentState {isStatus = "requires_payment_method", isAmount = amount, isCurrency = currency}
writeTVar stv st {fsNextId = fsNextId st + 1, fsIntents = M.insert pid s (fsIntents st), fsIdempotent = maybe id (`M.insert` pid) key (fsIdempotent st)}
pure (pid, s)
serve (intentFixture s) (patchIntent pid s)
-- Real Stripe can't cancel a card payment that is processing, paid or already cancelled.
+18 -1
View File
@@ -26,6 +26,7 @@ import qualified Data.ByteString.Lazy as LB
import Data.Either (isLeft)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Network.HTTP.Types (hAuthorization, parseSimpleQuery)
@@ -45,6 +46,7 @@ badgeStripeTests = describe "badge stripe adapter" $ do
describe "against the fake Stripe" $ do
it "creates a PaymentIntent and reads back the client secret" testFakeCreatesCard
it "sends the create form Stripe documents, over HTTP Basic" testFakeCreateBody
it "sends an Idempotency-Key of the order, so a create sent again gets the same intent" testFakeCreateIsIdempotent
it "is refused when the secret key is wrong, rather than passing silently" testFakeWrongSecretKey
it "walks requires_payment_method through processing to succeeded, then refuses a cancel" testFakeLifecycle
it "cancels an open intent once, then refuses a second cancel" testFakeCancel
@@ -71,7 +73,10 @@ badgeStripeTests = describe "badge stripe adapter" $ do
it "accepts a signature up to 15 minutes from now, either way, and refuses one further out" testWebhookTimestampWindow
fiftyFourDollars :: OrderDraft
fiftyFourDollars = OrderDraft {odAmount = CurrencyAmount 5400, odCurrency = "usd"}
fiftyFourDollars = OrderDraft {odAmount = CurrencyAmount 5400, odCurrency = "usd", odReference = sampleReference}
sampleReference :: Text
sampleReference = "name:0x6a3c0f1e9b2d4c5a8e7f60192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d"
fiftyFourDollarsReceived :: Received
fiftyFourDollarsReceived = Received {rcvAmount = CurrencyAmount 5400, rcvCrypto = Nothing, rcvDue = Nothing}
@@ -123,9 +128,21 @@ testFakeCreateBody = withProvider $ \fake p -> do
lookup "currency" form `shouldBe` Just "usd"
-- Card only keeps the client confirm from redirecting the top window out of the embedded frame.
lookup "allowed_payment_method_types[]" form `shouldBe` Just "card"
lookup "metadata[order]" form `shouldBe` Just (TE.encodeUtf8 sampleReference)
lookup "Idempotency-Key" (frHeaders created) `shouldBe` Just (TE.encodeUtf8 sampleReference <> ":5400:usd")
lookup hAuthorization (frHeaders created) `shouldSatisfy` maybe False ("Basic " `B8.isPrefixOf`)
_ -> expectationFailure ("expected one create, got " <> show (length posts))
-- | Stripe answers a create sent again with the same Idempotency-Key with the intent the first one made.
testFakeCreateIsIdempotent :: IO ()
testFakeCreateIsIdempotent = withProvider $ \fake p -> do
ProviderInvoice {piProviderRef = first} <- createdInvoice p (SPMCard CPStripe)
ProviderInvoice {piProviderRef = again} <- createdInvoice p (SPMCard CPStripe)
again `shouldBe` first
other <- pCreateInvoice p (SPMCard CPStripe) fiftyFourDollars {odReference = "badge:0x01"}
fmap piProviderRef other `shouldSatisfy` either (const False) (/= first)
length <$> fakeIntentIds fake `shouldReturn` 2
testFakeWrongSecretKey :: IO ()
testFakeWrongSecretKey = bounded $ withFakeStripe $ \fake -> do
p <- stripeProvider (fsConfig fake) {sSecretKey = "sk_test_wrong"}
+4 -1
View File
@@ -9,6 +9,8 @@ module Bots.StoreService.WebTests (badgeWebTests) where
import StoreService.Catalog (catalogCurrency, defaultCatalog)
import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), PollConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..))
import StoreService.Log (logInfo)
import StoreService.Names.Abi (hex)
import StoreService.Orders (codeLifetime, settleOrder)
import StoreService.Poller
import StoreService.Providers
@@ -1069,7 +1071,7 @@ setVerifyThrows :: IORef StubState -> Bool -> IO ()
setVerifyThrows ref throws = atomicModifyIORef' ref $ \s -> (s {ssVerifyThrows = throws}, ())
sampleDraft :: OrderDraft
sampleDraft = OrderDraft {odAmount = CurrencyAmount 500, odCurrency = "usd"}
sampleDraft = OrderDraft {odAmount = CurrencyAmount 500, odCurrency = "usd", odReference = "badge:0x01"}
sampleProviderInvoice :: ProviderInvoice
sampleProviderInvoice = ProviderInvoice {piProviderRef = "pref-1", piDestination = SPDCrypto CCBtc "bc1qexampleaddress" "0.00050000"}
@@ -1814,6 +1816,7 @@ testCreateInvoice = bounded "create invoice" $ withCheckout $ \ref env client ->
method `shouldBe` SPMCrypto CCBtc
odAmount draft `shouldBe` CurrencyAmount 500
odCurrency draft `shouldBe` "usd"
odReference draft `shouldBe` "badge:" <> hex (codeDigest sampleCode)
other -> expectationFailure ("provider calls: " <> show other)
testXmrReachesTheProviderAsXmr :: IO ()