uphold

package module
v0.0.0-...-55655a3 Latest Latest
Warning

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

Go to latest
Published: May 1, 2016 License: MIT Imports: 11 Imported by: 0

README

Uphold

Uphold is a Go library for accessing Uphold API

GoDoc Build Status

Install

go get -u github.com/gufran/uphold

Usage

import( 
    "http"
    "github.com/gufran/uphold"
)

func main() {
    client := uphold.NewClient(http.DefaultClient)

    // List all cards of a user
    cards, _, err := client.Card.ListAll()
    if err != nil {
        log.Fatalf("unexpected error: %s", err)
    }

    fmt.Printf("%+v", cards)
}

Note that this example will not actually work since Uphold API require OAuth token. The library does not directly handle the authorization, instead pass an oauth http client to NewClient method.

Authentication

If you have an oauth token you can use it for authentication

func main() {
    tokenSource := oauth2.StaticTokenSource(
        &oauth2.Token{AccessToken: "<oauthtoken>"},
    )

    authClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
    client := uphold.NewClient(authClient)
  
    cards, _, err := client.Card.ListAll()
    if err != nil {
        log.Fatalf("unexpected error: %s", err)
    }

    fmt.Printf("%+v", cards)
}

There is also ConfigureOAuth method if you wish to initiate the OAuth process to authenticate a new user. Use it like this

// This example assumes that you have a webserver running to facilitate the
// oauth steps

var (
    cred = uphold.Credential{
        ClientID: "<client id>",
        ClientSecret: "<client secret>",
    }

    terms = uphold.Terminals{
        AuthURL: "http://url.to-oauth.provider/",
        TokenURL: "http://url.to-oauth.provider/token-exchange",
        RedirectURL: "http://url.to-your-app.oauth/handler",
    }

    scopes = []uphold.Permissions{
        uphold.PermissionAccountsRead,
        uphold.PermissionUserRead,
        uphold.PermissionCardsRead,
        uphold.PermissionTransactionDeposit,
        uphold.PermissionTransferApplication,
    }
)

randomStateString := "completely random string"

// Initiate the oauth process with app
func InitiateOAuthHandler(w http.ResponseWriter, r *http.Request) {
    oauthConf := uphold.ConfigureOAuth(cred, terms, scopes)

    url := oauthConf.AuthCodeURL(randomStateString, oauth2.AccessTypeOffline)
    http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

// handle callback from oauth provider and generat token
func OAuthCallbackHandler(w http.ResponseWriter, r *http.Request) {
    if state := r.FormValue("state"); state != randomStateString {
        fmt.Print("invalid state. cannot proceed")
        // ... handle the condition, redirect user or log
        return
    }

    code := r.FormValue("code")
    token, err := oauthConf.Exchange(oauth2.NoContext, code)
    if err != nil {
        fmt.Printf("failed to exchange the code for token: %s", err)
        // ... handle the condition, redirect the user or log
        return
    }

    // ... Store the token somewhere safe to use it later

    authClient := oauth2.NewClient(oauth2.NoContext, token)
    client := uphold.NewClient(authClient)
  
    cards, _, err := client.Card.ListAll()
    if err != nil {
        log.Fatalf("unexpected error: %s", err)
    }

    fmt.Printf("%+v", cards)
}

TODO

  1. Tests for Transaction service
  2. Users endpoint service
  3. Transparency endpoint service
  4. Pagination support

Contribution

Any reasonable pull request is greatly appreciated. Please fork the repository and hack away.

License

The MIT License (MIT)

Copyright (c) 2016 Mohammad Gufran

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	LiveAuthURL    = "https://uphold.com/authorize/"
	SandBoxAuthURL = "https://sandbox.uphold.com/authorize/"
	TokenAccessURL = "https://api.uphold.com/oauth2/token"
	APIURL         = "https://api.uphold.com/v0/"
)

Various URL endpoints defined by Uphold

View Source
const (
	PermissionUserRead                        Permission = "user:read"
	PermissionCardsRead                                  = "cards:read"
	PermissionCardsWrite                                 = "cards:write"
	PermissionAccountsRead                               = "accounts:read"
	PermissionContactsRead                               = "contacts:read"
	PermissionContactsWrite                              = "contacts:write"
	PermissionTransactionsRead                           = "transactions:read"
	PermissionTransactionsDeposit                        = "transactions:deposit"
	PermissionTransactionsWithdraw                       = "transactions:withdraw"
	PermissionTransactionsTransferSelf                   = "transactions:transfer:self"
	PermissionTransactionsTransferOthers                 = "transactions:transfer:others"
	PermissionTransactionsTransferApplication            = "transactions:transfer:application"
)

Available OAuth permissions

View Source
const (
	CurrencyAED CurrencyCode = "AED"
	CurrencyARS              = "ARS"
	CurrencyAUD              = "AUD"
	CurrencyBRL              = "BRL"
	CurrencyBTC              = "BTC"
	CurrencyCAD              = "CAD"
	CurrencyCHF              = "CHF"
	CurrencyCNY              = "CNY"
	CurrencyDKK              = "DKK"
	CurrencyEUR              = "EUR"
	CurrencyGBP              = "GBP"
	CurrencyHKD              = "HKD"
	CurrencyILS              = "ILS"
	CurrencyINR              = "INR"
	CurrencyJPY              = "JPY"
	CurrencyKES              = "KES"
	CurrencyMXN              = "MXN"
	CurrencyNOK              = "NOK"
	CurrencyNZD              = "NZD"
	CurrencyPHP              = "PHP"
	CurrencyPLN              = "PLN"
	CurrencySEK              = "SEK"
	CurrencySGD              = "SGD"
	CurrencyUSD              = "USD"
	CurrencyVOX              = "VOX"
	CurrencyXAG              = "XAG"
	CurrencyXAU              = "XAU"
	CurrencyXPL              = "XPL"
	CurrencyXPT              = "XPT"
)

Currencies supported by Uphold

View Source
const (
	TxnTypeTransfer   TxnType = "transfer"
	TxnTypeDeposit            = "deposit"
	TxnTypeWithdrawal         = "withdrawal"
)

Valid transaction types

View Source
const (
	TxnStatusPending   TxnStatus = "pending"
	TxnStatusWaiting             = "waiting"
	TxnStatusCancelled           = "cancelled"
	TxnStatusCompleted           = "completed"
)

Valid transaction statuses

View Source
const (
	FeesTypeDeposit    FeesType = "deposit"
	FeesTypeExchange            = "exchange"
	FeesTypeNetwork             = "network"
	FeesTypeWithdrawal          = "withdrawal"
)

Valid fees types

View Source
const (
	DestinationTypeEmail    DestinationType = "email"
	DestinationTypeExternal                 = "external"
	DestinationTypeCard                     = "card"
)

Valid destination types

View Source
const (
	AccountTypeCard AccountType = "card"
	AccountTypeSepa             = "sepa"
	AccountACH                  = "ach"
)

Valid account types

Variables

View Source
var CurrencyDesc = map[CurrencyCode]string{
	CurrencyAED: "United Arab Emirates Dirham",
	CurrencyARS: "Argentine Peso",
	CurrencyAUD: "Australian Dollars",
	CurrencyBRL: "Brazilian Real",
	CurrencyBTC: "Bitcoin",
	CurrencyCAD: "Canadian Dollars",
	CurrencyCHF: "Swiss Franc",
	CurrencyCNY: "Yuan",
	CurrencyDKK: "Danish Krone",
	CurrencyEUR: "Euros",
	CurrencyGBP: "Pounds",
	CurrencyHKD: "Hong Kong Dollars",
	CurrencyILS: "Israeli Sheqel",
	CurrencyINR: "Indian Rupee",
	CurrencyJPY: "Yen",
	CurrencyKES: "Kenyan Shillings",
	CurrencyMXN: "Mexican Pesos",
	CurrencyNOK: "Norwegian Krone",
	CurrencyNZD: "New Zealand Dollars",
	CurrencyPHP: "Philippine Peso",
	CurrencyPLN: "Polish Zloty",
	CurrencySEK: "Swedish Krona",
	CurrencySGD: "Singapore Dollars",
	CurrencyUSD: "U.S. dollars",
	CurrencyVOX: "Voxels",
	CurrencyXAG: "Silver",
	CurrencyXAU: "Gold",
	CurrencyXPL: "Palladium",
	CurrencyXPT: "Platinum",
}

CurrencyDesc is the description of currencies

Functions

func CheckResponse

func CheckResponse(r *http.Response) error

CheckResponse checks the API response for errors, and returns them if present. A response is considered an error if it has a status code outside the 200 range. API error responses are expected to have either no response body, or a JSON response body that maps to ErrorResponse. Any other response body will be silently ignored.

The error type will be *RateLimitError for rate limit exceeded errors, and *TwoFactorAuthError for two-factor authentication errors.

func ConfigureOAuth

func ConfigureOAuth(c Credential, t Terminals, s []Permission) *oauth2.Config

ConfigureOAuth returns an OAuth configuration

func PermissionsToSlice

func PermissionsToSlice(p []Permission) []string

PermissionsToSlice converts a group of permissions into a slice of strings

Types

type Account

type Account struct {
	ID       string        `json:"id,omitempty"`
	Currency string        `json:"currency,omitempty"`
	Status   AccountStatus `json:"status,omitempty"`
	Label    string        `json:"label,omitempty"`
	Type     AccountType   `json:"type,omitempty"`
}

Account object in Uphold

type AccountService

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

AccountService works with Account API endpoint

func (*AccountService) List

func (a *AccountService) List(ID string) (*Account, *Response, error)

List a user account owned by the app

func (*AccountService) ListAll

func (a *AccountService) ListAll() (*[]Account, *Response, error)

ListAll accounts for a user

type AccountStatus

type AccountStatus string

AccountStatus is the status of an account

const (
	AccountStatusOK     AccountStatus = "ok"
	AccountStatusFailed               = "failed"
)

Valid account types

type AccountType

type AccountType string

AccountType is the type of an account

type Card

type Card struct {
	ID                string            `json:"id,omitempty"`
	Address           map[string]string `json:"address,omitempty"`
	Available         float32           `json:"available,string,omitempty"`
	Balance           float32           `json:"balance,string,omitempty"`
	Currency          string            `json:"currency,omitempty"`
	Label             string            `json:"label,omitempty"`
	LastTransactionAt *time.Time        `json:"lastTransactionAt,omitempty"`
	Settings          *CardSettings     `json:"settings,omitempty"`
	Addresses         *[]CardAddress    `json:"addresses,omitempty"`
	Normalized        []NormalizedCard  `json:"normalized,omitempty"`
}

Card object in Uphold

type CardAddress

type CardAddress struct {
	ID      string `json:"id,omitempty"`
	Network string `json:"network,omitempty"`
}

CardAddresses available on a card

type CardService

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

CardService works with card API endpoints

func (*CardService) Add

func (c *CardService) Add(n Card) (*Card, *Response, error)

Add a new card to user account

func (*CardService) List

func (c *CardService) List(ID string) (*Card, *Response, error)

List the card with given ID

func (*CardService) ListAll

func (c *CardService) ListAll() (*[]Card, *Response, error)

ListAll lists all available cards

func (*CardService) Update

func (c *CardService) Update(o Card) (*Card, *Response, error)

Update a card on user account

type CardSettings

type CardSettings struct {
	Position int  `json:"position,omitempty"`
	Starred  bool `json:"starred,omitempty"`
}

CardSettings available on card

type Client

type Client struct {
	UserAgent string

	Ticker      *TickerService
	Account     *AccountService
	Card        *CardService
	Contact     *ContactService
	Transaction *TransactionService
	// contains filtered or unexported fields
}

Client is an Uphold HTTP client

func NewClient

func NewClient(http *http.Client) *Client

NewClient returns an Uphold API client

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided in url, in which case it is resolved relative to the BaseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request body.

func (*Client) Rate

func (c *Client) Rate() RequestRate

Rate specifies the current rate limit for the client as determined by the most recent API call. If the client is used in a multi-user application, this rate may not always be up-to-date.

func (*Client) UseSandbox

func (c *Client) UseSandbox()

UseSandbox uses the sandbox URL for authentication

type Contact

type Contact struct {
	ID        string   `json:"id,omitempty"`
	Name      string   `json:"name,omitempty"`
	FirstName string   `json:"firstName,omitempty"`
	LastName  string   `json:"lastName,omitempty"`
	Emails    []string `json:"emails,omitempty"`
	Addresses []string `json:"addresses,omitempty"`
	Company   string   `json:"company,omitempty"`
}

Contact object in Uphold

type ContactService

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

ContactService works with contact API endpoints

func (*ContactService) List

func (c *ContactService) List(ID string) (*Contact, *Response, error)

List a contact by given ID

func (*ContactService) ListAll

func (c *ContactService) ListAll() (*[]Contact, *Response, error)

ListAll contacts for a user

type Credential

type Credential struct {
	ClientID     string
	ClientSecret string
}

Credential pair to use for oAuth request

type CurrencyCode

type CurrencyCode string

CurrencyCode is ISO 4217 code of currency

func (CurrencyCode) String

func (c CurrencyCode) String() string

String implements Stringer and converts currency code to a string

type CurrencyPair

type CurrencyPair struct {
	Ask      float32 `json:"ask,string,omitempty"`
	Bid      float32 `json:"bid,string,omitempty"`
	Currency string  `json:"currency,omitempty"`
	Pair     string  `json:"pair,omitempty"`
}

CurrencyPair object in Uphold

type Denomination

type Denomination struct {
	Currency string  `json:"currency,omitempty"`
	Pair     string  `json:"pair,omitempty"`
	Amount   float32 `json:"amount,string,omitempty"`
	Rate     float32 `json:"rate,string,omitempty"`
}

Denomination is the denomination object in Uphold

type Destination

type Destination struct {
	CardID      string          `json:"CardId,omitempty"`
	Amount      float32         `json:"amount,string,omitempty"`
	Base        float32         `json:"base,string,omitempty"`
	Commission  float32         `json:"commission,string,omitempty"`
	Currency    string          `json:"currency,omitempty"`
	Description string          `json:"description,omitempty"`
	Fees        float32         `json:"fees,string,omitempty"`
	Rate        float32         `json:"rate,string,omitempty"`
	Type        DestinationType `json:"type,omitempty"`
}

Destination object in Uphold

type DestinationType

type DestinationType string

DestinationType is the destination type of a transaction

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response
}

ErrorResponse as returned by Uphold

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

Error returns the string representation of the error

type Fees

type Fees struct {
	Amount   float32    `json:"amount,string,omitempty"`
	Currency string     `json:"currency,omitempty"`
	Target   FeesTarget `json:"target,omitempty"`
	Type     FeesType   `json:"type,omitempty"`
}

Fees object in Uphold

type FeesTarget

type FeesTarget string

FeesTarget is the target of fees

const (
	FeesTargetOrigin      FeesTarget = "origin"
	FeesTargetDestination            = "destination"
)

Valid fees targets

type FeesType

type FeesType string

FeesType is the type of fees on transaction

type Normalized

type Normalized struct {
	Amount     float32 `json:"amount,string,omitempty"`
	Commission float32 `json:"commission,string,omitempty"`
	Rate       float32 `json:"rate,string,omitempty"`
	Currency   float32 `json:"currency,string,omitempty"`
}

Normalized object in Uphold

type NormalizedCard

type NormalizedCard struct {
	Available float32 `json:"available,string,omitempty"`
	Balance   float32 `json:"balance,string,omitempty"`
	Currency  string  `json:"currency,omitempty"`
}

NormalizedCard information

type Origin

type Origin struct {
	CardID      string     `json:"Cardid,omitempty"`
	Amount      float32    `json:"amount,string,omitempty"`
	Base        float32    `json:"base,string,omitempty"`
	Commission  float32    `json:"commission,string,omitempty"`
	Currency    string     `json:"currency,omitempty"`
	Description string     `json:"description,omitempty"`
	Fee         float32    `json:"fee,string,omitempty"`
	Rate        float32    `json:"rate,string,omitempty"`
	Type        OriginType `json:"type,omitempty"`
	Username    string     `json:"username,omitempty"`

	Sources []struct {
		ID     string  `json:"id,omitempty"`
		Amount float32 `json:"amount,string,omitempty"`
	} `json:"sources,omitempty"`
}

Origin object in Uphold

type OriginType

type OriginType string

OriginType is the origin type of a transaction

const (
	OriginTypeCard     OriginType = "card"
	OriginTypeExternal OriginType = "external"
)

Valid origin types

type Params

type Params struct {
	Currency string  `json:"currency,omitempty"`
	Margin   float32 `json:"margin,string,omitempty"`
	Rate     float32 `json:"rate,string,omitempty"`
	Progress int     `json:"progress,omitempty"`
	Pair     string  `json:"pair,omitempty"`
	TTL      string  `json:"ttl,omitempty"`
}

Params object in uphold

type Permission

type Permission string

Permission is the Uphold OAuth policy

func (Permission) String

func (p Permission) String() string

String implements Stringer interface and converts the Permission into a string

type Phone

type Phone struct {
	ID                  string `json:"id,omitempty"`
	Verified            bool   `json:"verified,omitempty"`
	Primary             bool   `json:"primary,omitempty"`
	E164Masked          string `json:"e164Masked,omitempty"`
	NationalMasked      string `json:"nationalMasked,omitempty"`
	InternationalMasked string `json:"internationalMasked,omitempty"`
}

Phone object in Uphold

type Quote

type Quote struct {
	Denomination *QuoteDenomination `json:"denomination"`
	Origin       string             `json:"origin,omitempty"`
	Destination  string             `json:"destination,omitempty"`
	Realtime     bool               `json:"-"`
}

Quote denotes the request to perform a transaction. If Realtime is set to true, the resulting transaction will be committed immediately.

type QuoteDenomination

type QuoteDenomination struct {
	Amount   float32      `json:"amount,string"`
	Currency CurrencyCode `json:"currency"`
}

QuoteDenomination is denomination available on Quote

type RateLimitError

type RateLimitError struct {
	ErrorResponse
	RequestRate
}

RateLimitError is returned when API rate limits are exhausted

func (RateLimitError) Error

func (e RateLimitError) Error() string

Error returns the string representation of the error

type RequestRate

type RequestRate struct {
	Limit      int
	Remaining  int
	ResetOn    time.Time
	RetryAfter int
}

RequestRate describes the API rate limit, available requests for current time frame, time at which the current frame will expire and number of seconds to wait before next try

type Response

type Response struct {
	*http.Response
	RequestRate
}

Response contains the API response and request rate information

type Terminals

type Terminals struct {
	// oauth2 endpoints for authentication
	// and token request
	oauth2.Endpoint

	// URL to the service which will handle
	// third leg of the oAuth process
	RedirectURL string
}

Terminals describes the endpoints on oAuth server and client

type TickerService

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

TickerService works with ticker API endpoints

func (*TickerService) List

func (t *TickerService) List(cur CurrencyCode) (*[]CurrencyPair, *Response, error)

List ticker for a currency

func (*TickerService) ListAll

func (t *TickerService) ListAll() (*[]CurrencyPair, *Response, error)

ListAll retrieces a list of tickers

type TransactionService

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

TransactionService works with Transaction API

func (*TransactionService) Cancel

func (t *TransactionService) Cancel(card Card, txn Txn) (*Txn, *Response, error)

Cancel an unclaimed transaction on a card

func (*TransactionService) Commit

func (t *TransactionService) Commit(card Card, txn Txn, msg string) (*Txn, *Response, error)

Commit a pending transaction on card

func (*TransactionService) Create

func (t *TransactionService) Create(card Card, q Quote) (*Txn, *Response, error)

Create a new transaction on provided quote

func (*TransactionService) ListForCard

func (t *TransactionService) ListForCard(card Card) (*[]Txn, *Response, error)

ListForCard lists all the transactions for a card

func (*TransactionService) ListForUser

func (t *TransactionService) ListForUser() (*[]Txn, *Response, error)

ListForUser lists all the transactions for current user

func (*TransactionService) Resend

func (t *TransactionService) Resend(card Card, txn Txn) (*Txn, *Response, error)

Resend a reminder on an unclaimed transaction

type Txn

type Txn struct {
	ID           string        `json:"id,omitempty"`
	Type         TxnType       `json:"type,omitempty"`
	Message      string        `json:"message,omitempty"`
	Denomination *Denomination `json:"denomination,omitempty"`
	Fees         []string      `json:"fees,omitempty"`
	Status       TxnStatus     `json:"status,omitempty"`
	Params       *Params       `json:"params,omitempty"`
	CreatedAt    *time.Time    `json:"createdAt,omitempty"`
	Normalized   []Normalized  `json:"normalized,omitempty"`
	Origin       Origin        `json:"origin,omitempty"`
	Destination  Destination   `json:"destination,omitempty"`
}

Txn is the Transaction object in Uphold

type TxnStatus

type TxnStatus string

TxnStatus is the status of the transaction

type TxnType

type TxnType string

TxnType is the type of transaction

Jump to

Keyboard shortcuts

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