Created
February 4, 2020 07:50
-
-
Save aloukissas/e9d62743064377f8d2850baf9ecd19e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_subscription(email, plan_id, payment_method_id) do | |
case Repo.get_by(User, email: email) do | |
%User{customer_id: nil, name: name} = user -> | |
params = %{ | |
name: name, | |
email: email, | |
payment_method: payment_method_id, | |
invoice_settings: %{ | |
default_payment_method: payment_method_id | |
} | |
} | |
case Stripe.Customer.create(params) do | |
{:ok, %Stripe.Customer{id: customer_id}} -> | |
case Stripe.Subscription.create(%{ | |
customer: customer_id, | |
items: [%{plan: plan_id}] | |
}) do | |
{:ok, %Stripe.Subscription{id: subscription_id}} -> | |
case User.update(user, %{ | |
customer_id: customer_id, | |
subscription_id: subscription_id | |
}) do | |
{:ok, %User{}} -> | |
{:ok, :subscription_created} | |
{:error, _} -> | |
{:ok, :user_update_error} | |
end | |
{:error, %Stripe.Error{}} -> | |
{:error, :create_subscription_error} | |
end | |
{:error, %Stripe.Error{}} -> | |
{:error, :create_customer_error} | |
end | |
%User{customer_id: customer_id} when is_binary(customer_id) and customer_id != "" -> | |
{:error, :customer_exists_error} | |
nil -> | |
{:error, :unknown_user_error} | |
_ -> | |
{:error, :user_lookup_error} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment