diff --git a/lib/stripe/api.ex b/lib/stripe/api.ex index 15aa0dcd..4d45b59f 100644 --- a/lib/stripe/api.ex +++ b/lib/stripe/api.ex @@ -94,6 +94,12 @@ defmodule Stripe.API do |> Map.put("Content-Type", "multipart/form-data") end + @spec maybe_add_auth_header_oauth(headers, String.t(), String.t() | nil) :: headers + defp maybe_add_auth_header_oauth(headers, "deauthorize", api_key), + do: add_auth_header(headers, api_key) + + defp maybe_add_auth_header_oauth(headers, _endpoint, _api_key), do: headers + @spec add_auth_header(headers, String.t() | nil) :: headers defp add_auth_header(existing_headers, api_key) do api_key = fetch_api_key(api_key) @@ -208,8 +214,9 @@ defmodule Stripe.API do @doc """ A low level utility function to make an OAuth request to the Stripe API """ - @spec oauth_request(method, String.t(), map) :: {:ok, map} | {:error, Stripe.Error.t()} - def oauth_request(method, endpoint, body) do + @spec oauth_request(method, String.t(), map, String.t() | nil) :: + {:ok, map} | {:error, Stripe.Error.t()} + def oauth_request(method, endpoint, body, api_key \\ nil) do base_url = "https://connect.stripe.com/oauth/" req_url = base_url <> endpoint req_body = Stripe.URI.encode_query(body) @@ -217,6 +224,7 @@ defmodule Stripe.API do req_headers = %{} |> add_default_headers() + |> maybe_add_auth_header_oauth(endpoint, api_key) |> Map.to_list() req_opts = diff --git a/test/stripe/api_test.exs b/test/stripe/api_test.exs index 92e5d891..eb658feb 100644 --- a/test/stripe/api_test.exs +++ b/test/stripe/api_test.exs @@ -16,4 +16,27 @@ defmodule Stripe.APITest do assert Stripe.APIMock.oauth_request(:post, "www", %{body: "body"}) == :post end + + test "oauth_request sets authorization header for deauthorize request" do + defmodule HackneyMock do + def request(_, _, headers, _, _) do + kv_headers = + headers + |> Enum.reduce(%{}, fn {k, v}, acc -> Map.put(acc, k, v) end) + + {:ok, 200, headers, Poison.encode!(kv_headers)} + end + end + + Application.put_env(:stripity_stripe, :http_module, HackneyMock) + + {:ok, body} = Stripe.API.oauth_request(:post, "deauthorize", %{}) + assert body["Authorization"] == "Bearer sk_test_123" + + {:ok, body} = Stripe.API.oauth_request(:post, "deauthorize", %{}, "1234") + assert body["Authorization"] == "Bearer 1234" + + {:ok, body} = Stripe.API.oauth_request(:post, "token", %{}) + assert Map.keys(body) |> Enum.member?("Authorization") == false + end end