paddle

package module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: May 16, 2023 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 ChargeOptions added in v0.0.9

type ChargeOptions struct {
	Amount     string
	ChargeName string
}

ChargeOptions represents options for charing.

type ChargeResponse added in v0.0.9

type ChargeResponse struct {
	InvoiceID      uint64 `json:"invoice_id,omitempty"`
	SubscriptionID uint64 `json:"subscription_id,omitempty"`
	Amount         string `json:"amount,omitempty"`
	Currency       string `json:"currency,omitempty"`
	PaymentDate    string `json:"payment_date,omitempty"`
	ReceiptURL     string `json:"receipt_url,omitempty"`
	Status         string `json:"status,omitempty"`
}

ChargeResponse represents a response for the subscription charge.

type Charges added in v0.0.9

type Charges api

Charges is an API to work with the Paddle subscription one-off charges.

func (*Charges) Charge added in v0.0.9

func (modifiers *Charges) Charge(ctx context.Context, subscriptionID uint64, options *ChargeOptions) (*ChargeResponse, *http.Response, error)

Charge charges.

Paddle docs: https://developer.paddle.com/api-reference/23cf86225523f-create-one-off-charge

type Client

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

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 CreateModifierOptions added in v0.0.9

type CreateModifierOptions struct {
	SubscriptionID      uint64
	ModifierRecurring   bool
	ModifierAmount      string
	ModifierDescription string
}

CreateModifierOptions represents options for creating a modifier.

type CreateModifierResponse added in v0.0.9

type CreateModifierResponse struct {
	SubscriptionID uint64 `json:"subscription_id,omitempty"`
	ModifierID     uint64 `json:"modifier_id,omitempty"`
}

CreateModifierResponse represents a response for the create subscription modifier.

type ListUsersOptions

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

ListUsersOptions represents options for getting subscription users.

type Modifiers added in v0.0.9

type Modifiers api

Modifiers is an API to work with the Paddle subscription modifiers.

func (*Modifiers) Create added in v0.0.9

Create creates new modifier.

Paddle docs: https://developer.paddle.com/api-reference/dc2b0c06f0481-create-modifier

type OptionalTime added in v0.0.6

type OptionalTime struct {
	Time time.Time
	Set  bool
}

OptionalTime represents the Time value that can be zero and forces you to process it differently.

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 RefundType added in v0.0.2

type RefundType string

RefundType represents refund type: full, vat or partial.

const (

	// RefundFull represents full refund.
	RefundFull RefundType = "full"
	// RefundVAT represents VAT refund.
	RefundVAT RefundType = "vat"
	// RefundPartial represents partial refund.
	RefundPartial RefundType = "partial"
)

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         OptionalTime `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 SubscriptionPaymentRefundedAlert added in v0.0.2

type SubscriptionPaymentRefundedAlert struct {
	AlertName               string     `schema:"alert_name"`
	AlertID                 uint64     `schema:"alert_id"`
	Amount                  *string    `schema:"amount"`
	BalanceCurrency         *string    `schema:"balance_currency"`
	BalanceEarningsDecrease *string    `schema:"balance_earnings_decrease"`
	BalanceFeeRefund        *string    `schema:"balance_fee_refund"`
	BalanceGrossRefund      *string    `schema:"balance_gross_refund"`
	BalanceTaxRefund        *string    `schema:"balance_tax_refund"`
	CheckoutID              *string    `schema:"checkout_id"`
	Currency                *string    `schema:"currency"`
	CustomData              *string    `schema:"custom_data"`
	EarningsDecrease        *string    `schema:"earnings_decrease"`
	Email                   *string    `schema:"email"`
	EventTime               time.Time  `schema:"event_time"`
	FeeRefund               *string    `schema:"fee_refund"`
	GrossRefund             *string    `schema:"gross_refund"`
	InitialPayment          bool       `schema:"initial_payment"`
	Instalments             int        `schema:"instalments"`
	MarketingConsent        bool       `schema:"marketing_consent"`
	OrderID                 *string    `schema:"order_id"`
	Passthrough             *string    `schema:"passthrough"`
	Quantity                *string    `schema:"quantity"`
	RefundReason            *string    `schema:"refund_reason"`
	RefundType              RefundType `schema:"refund_type"`
	Status                  *string    `schema:"status"`
	SubscriptionID          uint64     `schema:"subscription_id"`
	SubscriptionPaymentID   uint64     `schema:"subscription_payment_id"`
	SubscriptionPlanID      uint64     `schema:"subscription_plan_id"`
	TaxRefund               *string    `schema:"tax_refund"`
	UnitPrice               *string    `schema:"unit_price"`
	UserID                  uint64     `schema:"user_id"`
}

SubscriptionPaymentRefundedAlert is fired when a refund for an existing subscription is issued. Docs: https://developer.paddle.com/webhook-reference/4974afe939abc-subscription-payment-refunded

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
	KeepModifiers   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