File size: 2,277 Bytes
3e21b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
defmodule Mix.Tasks.PullSandboxSubscription do
  use Mix.Task
  use Plausible.Repo
  alias Plausible.{Repo, Auth.User, Billing.Subscription}
  require Logger

  # Steps to create a subscription in dev environment
  #
  # 1) Subscribe to a sandbox plan in the UI > User Settings. Instructions:
  #    https://developer.paddle.com/getting-started/ZG9jOjIxODY4NjYx-sandbox
  #
  # 2) find the created subscription_ID here:
  #    https://sandbox-vendors.paddle.com/subscriptions/customers
  #
  # 3) run from command line:
  #    mix pull_sandbox_subscription <subscription_ID>

  @headers [
    {"Content-type", "application/json"},
    {"Accept", "application/json"}
  ]

  def run([paddle_subscription_id]) do
    Mix.Task.run("app.start")

    config = Application.get_env(:plausible, :paddle)

    endpoint = Plausible.Billing.PaddleApi.vendors_domain() <> "/api/2.0/subscription/users"

    params = %{
      vendor_id: config[:vendor_id],
      vendor_auth_code: config[:vendor_auth_code],
      subscription_id: paddle_subscription_id
    }

    case HTTPoison.post(endpoint, Jason.encode!(params), @headers) do
      {:ok, response} ->
        body = Jason.decode!(response.body)

        if body["success"] do
          res = body["response"] |> List.first()
          user = Repo.get_by!(User, email: res["user_email"])
          {:ok, team} = Plausible.Teams.get_or_create(user)

          subscription = %{
            paddle_subscription_id: res["subscription_id"] |> to_string(),
            paddle_plan_id: res["plan_id"] |> to_string(),
            cancel_url: res["cancel_url"],
            update_url: res["update_url"],
            team_id: team.id,
            status: res["state"],
            last_bill_date: res["last_payment"]["date"],
            next_bill_date: res["next_payment"]["date"],
            next_bill_amount: res["next_payment"]["amount"] |> to_string(),
            currency_code: res["next_payment"]["currency"]
          }

          Subscription.changeset(%Subscription{}, subscription)
          |> Repo.insert!()

          Logger.notice("Subscription created for user #{user.id} (#{user.email})")
        else
          Logger.error(body["error"])
        end

      {:error, reason} ->
        Logger.error(reason)
    end
  end
end