paddle

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2022 License: MIT Imports: 19 Imported by: 0

README

paddle

Build codecov Go Report Card GoDoc

A Paddle API client for Go.

Installation

go get github.com/krasun/paddle

Usage

Import the library:

import "github.com/krasun/paddle"

Calling API methods:

var paddleClient *paddle.Client
switch environment {
case "sandbox":
    paddleClient, err = paddle.NewSandboxClient(paddle.Authentication{paddleVendorID, paddleVendorAuthCode})
    if err != nil {
        log.Fatalf("failed to instantiate paddle %s client: %s", environment, err)
        return
    }
case "production":
    paddleClient, err = paddle.NewProductionClient(paddle.Authentication{paddleVendorID, paddleVendorAuthCode})
    if err != nil {
        log.Fatalf("failed to instantiate paddle %s client: %s", environment, err)
        return
    }
default:
    log.Fatalf("unsupported Paddle environment: %s", environment)
    return
}

options := &paddle.UpdateUserOptions{
    // ... 
    Prorate:         true,
    BillImmediately: true,
    // ...
}
response, _, err := paddleClient.Users.Update(ctx, options)
if err != nil {
    log.Error(err)
    return
}

Handling webhooks:

webhooks, err := paddle.NewWebhooks(paddlePublicKey)
if err != nil {
    log.Fatalf("failed to instantiate Paddle webhooks client: %s", err)
    return
}

func handlePaddleWebhooks(webhooks *paddle.Webhooks, payments *payments) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()

        alert, err := webhooks.ParseRequest(r)
        if err != nil {
            log.Error(err)
            http.Error(w, "Sorry, something went wrong", http.StatusInternalServerError)
            return
        }

        switch alert := alert.(type) {
        // ... 
        case *paddle.SubscriptionCreatedAlert:
            err := payments.processSubscriptionCreated(ctx, alert)
            if err != nil {
                log.Error(err)
                http.Error(w, "Sorry, something went wrong", http.StatusInternalServerError)
                return
            }
        case *paddle.SubscriptionUpdatedAlert:
            // ... 
            return
        case *paddle.SubscriptionCancelledAlert:
            // ... 
            return
        // ...
        }
    }
}

Tests

To run tests, just execute:

$ go test . 

License

paddle is released under the MIT license.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

APIError represents a Paddle API error.

func (*APIError) Error

func (e *APIError) Error() string

Error formats the error as a string.

type Authentication

type Authentication struct {
	// VendorID identifies the seller account, can be found in Developer Tools > Authentication.
	VendorID int
	// VendorAuthCode is a private API key for authenticating API requests, should never be used in client side code or shared publicly.
	// And can be found in Developer Tools > Authentication.
	VendorAuthCode string
}

Authentication represents credentials for working with the Paddle API.

type CancelUserOptions

type CancelUserOptions struct {
	SubscriptionID uint64
}

CancelUserOptions represents options for cancel user subscription.

type Client

type Client struct {
	// Users represents an API for working with subscription users.
	Users *Users
}

Client is a Paddle client.

func NewProductionClient

func NewProductionClient(authentication Authentication) (*Client, error)

NewProductionClient creates a new Paddle production client.

func NewSandboxClient

func NewSandboxClient(authentication Authentication) (*Client, error)

NewSandboxClient creates a new Paddle sandbox client.

type ListUsersOptions

type ListUsersOptions struct {
	SubscriptionID uint64
	PlanID         uint64
	State          string
	Page           int
	ResultsPerPage int
}

ListUsersOptions represents options for getting subscription users.

type PaymentInformation

type PaymentInformation struct {
	PaymentMethod  string `json:"payment_method,omitempty"`
	CardType       string `json:"card_type,omitempty"`
	LastFourDigits string `json:"last_four_digits,omitempty"`
	ExpiryDate     string `json:"expiry_date,omitempty"`
}

PaymentInformation represents a user payment information.

type SubscriptionCancelledAlert

type SubscriptionCancelledAlert struct {
	AlertName                 string    `schema:"alert_name"`
	AlertID                   uint64    `schema:"alert_id"`
	CancellationEffectiveDate time.Time `schema:"cancellation_effective_date"`
	CheckoutID                *string   `schema:"checkout_id"`
	Currency                  *string   `schema:"currency"`
	Email                     *string   `schema:"email"`
	EventTime                 time.Time `schema:"event_time"`
	MarketingConsent          bool      `schema:"marketing_consent"`
	Passthrough               *string   `schema:"passthrough"`
	Quantity                  *string   `schema:"quantity"`
	Status                    *string   `schema:"status"`
	SubscriptionID            *string   `schema:"subscription_id"`
	SubscriptionPlanID        *string   `schema:"subscription_plan_id"`
	UnitPrice                 *string   `schema:"unit_price"`
	UserID                    uint64    `schema:"user_id"`
}

SubscriptionCancelledAlert is triggered whenever a user cancel a subscription. Docs: https://developer.paddle.com/webhook-reference/subscription-alerts/subscription-cancelled

type SubscriptionCreatedAlert

type SubscriptionCreatedAlert struct {
	AlertName          string    `schema:"alert_name"`
	AlertID            uint64    `schema:"alert_id"`
	CancelURL          string    `schema:"cancel_url"`
	CheckoutID         *string   `schema:"checkout_id"`
	Currency           *string   `schema:"currency"`
	Email              *string   `schema:"email"`
	EventTime          time.Time `schema:"event_time"`
	MarketingConsent   bool      `schema:"marketing_consent"`
	NextBillDate       time.Time `schema:"next_bill_date"`
	Passthrough        *string   `schema:"passthrough"`
	Quantity           *string   `schema:"quantity"`
	Source             *string   `schema:"source"`
	Status             *string   `schema:"status"`
	SubscriptionID     uint64    `schema:"subscription_id"`
	SubscriptionPlanID uint64    `schema:"subscription_plan_id"`
	UnitPrice          *string   `schema:"unit_price"`
	UserID             uint64    `schema:"user_id"`
	UpdateURL          *string   `schema:"update_url"`
}

SubscriptionCreatedAlert is fired a new subscription is created, and a customer has successfully subscribed. Docs: https://developer.paddle.com/webhook-reference/subscription-alerts/subscription-created

type SubscriptionPaymentFailedAlert

type SubscriptionPaymentFailedAlert struct {
	AlertName             string    `schema:"alert_name"`
	AlertID               uint64    `schema:"alert_id"`
	Amount                *string   `schema:"amount"`
	CancelURL             string    `schema:"cancel_url"`
	CheckoutID            *string   `schema:"checkout_id"`
	Currency              *string   `schema:"currency"`
	Email                 *string   `schema:"email"`
	EventTime             time.Time `schema:"event_time"`
	MarketingConsent      bool      `schema:"marketing_consent"`
	NextRetryDate         time.Time `schema:"next_retry_date"`
	Passthrough           *string   `schema:"passthrough"`
	Quantity              *string   `schema:"quantity"`
	Status                *string   `schema:"status"`
	SubscriptionID        uint64    `schema:"subscription_id"`
	SubscriptionPlanID    uint64    `schema:"subscription_plan_id"`
	UnitPrice             *string   `schema:"unit_price"`
	UpdateURL             string    `schema:"update_url"`
	SubscriptionPaymentID uint64    `schema:"subscription_payment_id"`
	Instalments           int       `schema:"instalments"`
	OrderID               *string   `schema:"order_id"`
	UserID                uint64    `schema:"user_id"`
	AttemptNumber         *string   `schema:"attempt_number"`
}

SubscriptionPaymentFailedAlert is fired when a payment for an existing subscription fails. Docs: https://developer.paddle.com/webhook-reference/subscription-alerts/subscription-payment-failed

type SubscriptionPaymentSucceededAlert

type SubscriptionPaymentSucceededAlert struct {
	AlertName             string    `schema:"alert_name"`
	AlertID               uint64    `schema:"alert_id"`
	BalanceCurrency       *string   `schema:"balance_currency"`
	BalanceEarnings       *string   `schema:"balance_earnings"`
	BalanceFee            *string   `schema:"balance_fee"`
	BalanceGross          *string   `schema:"balance_gross"`
	BalanceTax            *string   `schema:"balance_tax"`
	CheckoutID            *string   `schema:"checkout_id"`
	Country               *string   `schema:"country"`
	Coupon                *string   `schema:"coupon"`
	Currency              *string   `schema:"currency"`
	CustomerName          *string   `schema:"customer_name"`
	Earnings              *string   `schema:"earnings"`
	Email                 *string   `schema:"email"`
	EventTime             time.Time `schema:"event_time"`
	Fee                   *string   `schema:"fee"`
	InitialPayment        bool      `schema:"initial_payment"`
	Instalments           int       `schema:"instalments"`
	MarketingConsent      bool      `schema:"marketing_consent"`
	NextBillDate          *string   `schema:"next_bill_date"`
	NextPaymentAmount     *string   `schema:"next_payment_amount"`
	OrderID               *string   `schema:"order_id"`
	Passthrough           *string   `schema:"passthrough"`
	PaymentMethod         *string   `schema:"payment_method"`
	PaymentTax            *string   `schema:"payment_tax"`
	PlanName              *string   `schema:"plan_name"`
	Quantity              *string   `schema:"quantity"`
	ReceiptURL            *string   `schema:"receipt_url"`
	SaleGross             *string   `schema:"sale_gross"`
	Status                *string   `schema:"status"`
	SubscriptionID        uint64    `schema:"subscription_id"`
	SubscriptionPaymentID uint64    `schema:"subscription_payment_id"`
	SubscriptionPlanID    uint64    `schema:"subscription_plan_id"`
	UnitPrice             *string   `schema:"unit_price"`
	UserID                uint64    `schema:"user_id"`
}

SubscriptionPaymentSucceededAlert is fired when a subscription payment is received successfully. Docs: https://developer.paddle.com/webhook-reference/subscription-alerts/subscription-payment-succeeded

type SubscriptionStatus

type SubscriptionStatus string

SubscriptionStatus represents subscription status: active, trialing, past due, paused or deleted.

const (

	// SubscriptionActive represents active subscription status.
	SubscriptionActive SubscriptionStatus = "active"
	// SubscriptionTrialing represents trialing subscription status.
	SubscriptionTrialing SubscriptionStatus = "trialing"
	// SubscriptionPastDue represents past due subscription status.
	SubscriptionPastDue SubscriptionStatus = "past_due"
	// SubscriptionPaused represents paused subscription status.
	SubscriptionPaused SubscriptionStatus = "paused"
	// SubscriptionDeleted represents deleted subscription status.
	SubscriptionDeleted SubscriptionStatus = "deleted"
)

type SubscriptionUpdatedAlert

type SubscriptionUpdatedAlert struct {
	AlertName             string    `schema:"alert_name"`
	AlertID               uint64    `schema:"alert_id"`
	CancelURL             string    `schema:"cancel_url"`
	CheckoutID            *string   `schema:"checkout_id"`
	Email                 *string   `schema:"email"`
	EventTime             time.Time `schema:"event_time"`
	MarketingConsent      bool      `schema:"marketing_consent"`
	NewPrice              *string   `schema:"new_price"`
	NewQuantity           *string   `schema:"new_quantity"`
	NewUnitPrice          *string   `schema:"new_unit_price"`
	NextBillDate          time.Time `schema:"next_bill_date"`
	OldPrice              *string   `schema:"old_price"`
	OldQuantity           *string   `schema:"old_quantity"`
	OldUnitPrice          *string   `schema:"old_unit_price"`
	Currency              *string   `schema:"currency"`
	Passthrough           *string   `schema:"passthrough"`
	Status                *string   `schema:"status"`
	SubscriptionID        uint64    `schema:"subscription_id"`
	SubscriptionPlanID    uint64    `schema:"subscription_plan_id"`
	UserID                uint64    `schema:"user_id"`
	UpdateURL             string    `schema:"update_url"`
	OldNextBillDate       time.Time `schema:"old_next_bill_date"`
	OldStatus             *string   `schema:"old_status"`
	OldSubscriptionPlanID *string   `schema:"old_subscription_plan_id"`
	PausedAt              *string   `schema:"paused_at"`
	PausedFrom            *string   `schema:"paused_from"`
	PausedReason          *string   `schema:"paused_reason"`
}

SubscriptionUpdatedAlert is fired when the plan, price, quantity, status of an existing subscription changes, or if the payment date is rescheduled manually. Docs: https://developer.paddle.com/webhook-reference/subscription-alerts/subscription-updated

type UpdateUserOptions

type UpdateUserOptions struct {
	SubscriptionID  uint64
	PlanID          uint64
	Prorate         bool
	BillImmediately bool
}

UpdateUsersOptions represents options for update user subscription.

type UpdateUserResponse

type UpdateUserResponse struct {
	SubscriptionID uint64       `json:"subscription_id,omitempty"`
	PlanID         uint64       `json:"plan_id,omitempty"`
	UserID         uint64       `json:"user_id,omitempty"`
	NextPayment    *UserPayment `json:"next_payment,omitempty"`
}

UpdateUserResponse represents a response for the update user subscription request.

type User

type User struct {
	SubscriptionID     int                 `json:"subscription_id,omitempty"`
	PlanID             int                 `json:"plan_id,omitempty"`
	UserID             int                 `json:"user_id,omitempty"`
	UserEmail          string              `json:"user_email,omitempty"`
	MarketingConsent   bool                `json:"marketing_consent,omitempty"`
	UpdateURL          string              `json:"update_url,omitempty"`
	CancelURL          string              `json:"cancel_url,omitempty"`
	State              string              `json:"state,omitempty"`
	SignupDate         string              `json:"signup_date,omitempty"`
	LastPayment        *UserPayment        `json:"last_payment,omitempty"`
	NextPayment        *UserPayment        `json:"next_payment,omitempty"`
	PaymentInformation *PaymentInformation `json:"payment_information,omitempty"`
	PausedAt           string              `json:"paused_at,omitempty"`
	PausedFrom         string              `json:"paused_from,omitempty"`
}

User represents a Paddle user.

type UserPayment

type UserPayment struct {
	Amount   float64 `json:"amount,omitempty"`
	Currency string  `json:"currency,omitempty"`
	Date     string  `json:"date,omitempty"`
}

UserPayment represents a user payment.

type Users

type Users api

Users is an API to work with the Paddle subscription users.

func (*Users) Cancel

func (users *Users) Cancel(ctx context.Context, options *CancelUserOptions) (*http.Response, error)

Cancel cancel the user subscription.

Paddle docs: https://developer.paddle.com/api-reference/b3A6MzA3NDQ3MzU-cancel-user

func (*Users) List

func (users *Users) List(ctx context.Context, options *ListUsersOptions) ([]*User, *http.Response, error)

List returns subscription users.

Paddle docs: https://developer.paddle.com/api-reference/b3A6MzA3NDQ3MzA-list-users

func (*Users) Update

func (users *Users) Update(ctx context.Context, options *UpdateUserOptions) (*UpdateUserResponse, *http.Response, error)

Update updates user subscription.

Paddle docs: https://developer.paddle.com/api-reference/b3A6MzA3NDQ3MzQ-update-user

type Webhooks

type Webhooks struct {
	// contains filtered or unexported fields
}

Webhooks validates and parses webhook alerts.

func NewWebhooks

func NewWebhooks(publicKey []byte) (*Webhooks, error)

NewWebhooks returns a new instance of the webhooks.

func (*Webhooks) ParseRequest

func (webhooks *Webhooks) ParseRequest(r *http.Request) (interface{}, error)

ParseRequest validates the Paddle webhook request and returns typed alert in case of success, otherwise it returns an error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL