Skip to content

Instantly share code, notes, and snippets.

@venkatd
Last active October 17, 2024 13:49
Show Gist options
  • Save venkatd/90da3c77f612f1f7f86da6d5b6eca474 to your computer and use it in GitHub Desktop.
Save venkatd/90da3c77f612f1f7f86da6d5b6eca474 to your computer and use it in GitHub Desktop.
defmodule MyApp.Billing.StripeClient do
def new(opts \\ []) do
Req.new(
base_url: "https://api.stripe.com/v1",
auth: {:bearer, Application.fetch_env!(:my_app, MyApp.Billing)[:stripe_secret_key]}
)
|> Req.merge(opts)
|> Req.Request.prepend_request_steps(encode_stripe_post: &encode_stripe_post/1)
end
defp encode_stripe_post(%Req.Request{method: :post, options: %{form: form}} = req) do
%{req | options: %{req.options | form: encode_form_url(form)}}
end
defp encode_stripe_post(%Req.Request{} = req) do
req
end
defp encode_form_url(data) do
encode_form_url(data, nil)
end
defp encode_form_url(data, prefix) when is_map(data) do
Enum.flat_map(data, fn {key, value} ->
final_key = if prefix, do: "#{prefix}[#{key}]", else: to_string(key)
case value do
nil ->
[]
map when is_map(map) ->
encode_form_url(map, final_key)
list when is_list(list) ->
encode_form_url(list, final_key)
_ ->
[{final_key, value}]
end
end)
end
defp encode_form_url(data, prefix) when is_list(data) do
Map.new(Enum.with_index(data), fn {value, index} ->
{index, value}
end)
|> encode_form_url(prefix)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment