How to capture and store email of user with Stripe-Elixir

98 Views Asked by At

I have the following code and I am able to create new users. The email is not stored.

Code:

    defmodule StripeTestWeb.PaymentController do
      use StripeTestWeb, :controller
      use Stripe.API

      def index(conn, _params) do

        {:ok, customer_data} = Stripe.Customer.create(%{email: conn.body_params['stripeEmail']})

        render(conn, "index.html")
      end
    end

enter image description here

How do I capture and store their email ?

1

There are 1 best solutions below

2
Aleksei Matiushkin On

There are two glitches with this code I can spot on:

  1. there is a significant difference between single quotes and double quotes in Elixir’s literals/terms. The difference is described in details in Elixir Guide, Chapter 6 and in general is: single quotes used for char lists that have basically nothing in common with binaries (strings.)

Look:

iex|1 ▶ 'abc' == [97, 98, 99]
#⇒ true

'abc' is essentially the same as (in pseudocode)

[
   ascii-value-of(character a),
   ascii-value-of(character b),
   ascii-value-of(character c)
]

This should be probably considered a legacy that came back from XX century. Whenever you need a binary (the string,) always use double quotes.

  1. Another issue would be you assign and immediately discard the value returned from Stripe.Customer.create. This is unlikely what you actually want to do; to pass it to the underlying controller, use Plug.Conn.assign/3 (or at least validate the outcome of a call to create function and somehow deal with errors.

The summing up, the solution that would be likely robust looks like:

defmodule StripeTestWeb.PaymentController do
  use StripeTestWeb, :controller
  use Stripe.API

  def index(conn, %{"stripeEmail" => email} = _params) do
    with {:ok, customer_data} <- Stripe.Customer.create(%{email: email}) do
      conn
      |> assign(:customer_data, customer_data)
      |> render("index.html")
    else
      # render error page
    end
  end
end