Skip to content

Commit

Permalink
add support for idempotent post requests (beam-community#461)
Browse files Browse the repository at this point in the history
  • Loading branch information
swelham authored and snewcomer committed Mar 4, 2019
1 parent c4e0ec8 commit e49a271
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/stripe.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ defmodule Stripe do
[https://stripe.com/docs/connect/authentication#stripe-account-header](https://stripe.com/docs/connect/authentication#stripe-account-header)
* `:expand` - Takes a list of fields that should be expanded in the response
from Stripe. See [https://stripe.com/docs/api/expanding_objects](https://stripe.com/docs/api/expanding_objects)
* `:idempotency_key` - A string that is passed through as the "Idempotency-Key" header on all POST requests. This is used by Stripe's idempotency layer to manage
duplicate requests to the stripe API. See [https://stripe.com/docs/api/idempotent_requests](https://stripe.com/docs/api/idempotent_requests)
### HTTP Connection Pool
Expand Down
12 changes: 11 additions & 1 deletion lib/stripe/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,11 @@ defmodule Stripe.API do

def request(body, method, endpoint, headers, opts) do
{expansion, opts} = Keyword.pop(opts, :expand)
base_url = get_base_url()
{idempotency_key, opts} = Keyword.pop(opts, :idempotency_key)

base_url = get_base_url()
req_url = add_object_expansion("#{base_url}#{endpoint}", expansion)
headers = add_idempotency_header(idempotency_key, headers, method)

req_body =
body
Expand Down Expand Up @@ -317,4 +319,12 @@ defmodule Stripe.API do
end

defp add_object_expansion(url, _), do: url

defp add_idempotency_header(nil, headers, _), do: headers

defp add_idempotency_header(idempotency_key, headers, :post) do
Map.put(headers, "Idempotency-Key", idempotency_key)
end

defp add_idempotency_header(_, headers, _), do: headers
end
7 changes: 7 additions & 0 deletions test/stripe/core_resources/charge_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ defmodule Stripe.ChargeTest do
assert_stripe_requested(:post, "/v1/charges/ch_123/capture")
end

test "is captureable with idempotency opts" do
opts = [idempotency_key: "test"]
{:ok, %Stripe.Charge{} = charge} = Stripe.Charge.retrieve("ch_123")
assert {:ok, %Stripe.Charge{}} = Stripe.Charge.capture(charge, %{amount: 1000}, opts)
assert_stripe_requested(:post, "/v1/charges/ch_123/capture")
end

test "is retrievable with expansions opts" do
opts = [expand: ["balance_transaction"]]
assert {:ok, %Stripe.Charge{}} = Stripe.Charge.retrieve("ch_123", opts)
Expand Down

0 comments on commit e49a271

Please sign in to comment.