Как отправить http-запрос в Stripe вместо curl-запроса? - PullRequest
0 голосов
/ 19 апреля 2019

Я могу успешно отправить запрос curl в Stripe API, вот так:

curl https://api.stripe.com/v1/customers?limit=3 \
  -u sk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: \
  -G

Как я могу сделать с зависимостью Elixir: HTTPoison, чтобы отправить HTTP-запрос?

1 Ответ

2 голосов
/ 19 апреля 2019

HTTPoison модуль имеет функцию get для выполнения HTTP GET запросов.

Вы можете запустить h HTTPoison.get в вашем iex, чтобы получить полезное справочное сообщение.

Хорошей практикой является запуск iex с загруженными библиотеками, изучение необходимых вам функций с различными значениями и проверка возвращаемых или генерируемых данных.

В этом случае что-то вроде этого должно помочь вам начать:

url = "https://api.stripe.com/v1/customers?limit=3"
headers = [ {"Authorization", "Bearer " <> "sk_test_xxxxxxxxxxxxxxxxxxx"} ]

case HTTPoison.get(url, headers, []) do
  {:ok, %HTTPoison.Response{body: body, status_code: 200}} -> 
      # some data is returned
      "success body = " <> Poison.decode!(body)
  {:ok, %HTTPoison.Response{status_code: other_status_code}} -> 
      # api was not able to process our request, check body for details
      "some error returned from endpoint"
  {:error, reason} -> 
      "problem with network or reaching/getting endpoint"
end

.

Часть Poison.decode!(body) будет выглядеть примерно так

%{
  "data" => [
    %{
      "account_balance" => 0,
      "address" => nil,
      "created" => 1555667607,
      "currency" => nil,
      "default_source" => "card_xxxxxxxxxx",
      "delinquent" => false,
      "description" => nil,
      "discount" => nil,
      "email" => "xxx@exemple.com",
      "id" => "cus_xxxxxxxxx",
      "invoice_prefix" => "ASDSADASD",
      "invoice_settings" => %{
        "custom_fields" => nil,
        "default_payment_method" => nil,
        "footer" => nil
      },
      "livemode" => false,
      "metadata" => %{},
      "name" => nil,
      "object" => "customer",
      "phone" => nil,
      "preferred_locales" => [],
      "shipping" => nil,
      "sources" => %{
        "data" => [
          %{
            "address_city" => nil,
            "address_country" => nil,
            "address_line1" => nil,
            "address_line1_check" => nil,
            "address_line2" => nil,
            "address_state" => nil,
            "address_zip" => nil,
            "address_zip_check" => nil,
            "brand" => "Visa",
            "country" => "US",
            "customer" => "cus_EuirEmfjcPKg4Q",
            "cvc_check" => nil,
            "dynamic_last4" => nil,
            "exp_month" => 4,
            "exp_year" => 2020,
            "fingerprint" => "XXXXXXc",
            "funding" => "credit",
            "id" => "card_123123XXX",
            "last4" => "4242",
            "metadata" => %{},
            "name" => nil,
            "object" => "card",
            "tokenization_method" => nil
          }
        ],
        "has_more" => false,
        "object" => "list",
        "total_count" => 1,
        "url" => "/v1/customers/cus_EEEEASDSADAS/sources"
      },
      "subscriptions" => %{
        "data" => [],
        "has_more" => false,
        "object" => "list",
        "total_count" => 0,
        "url" => "/v1/customers/cus_EERASDASD/subscriptions"
      },
      "tax_info" => nil,
      "tax_info_verification" => nil
    },

    ------ more objects in array here, removed for brewity -------

  ],
  "has_more" => true,
  "object" => "list",
  "url" => "/v1/customers"
}
...