coinpayments

package module
v0.0.0-...-35104b8 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2020 License: MIT Imports: 11 Imported by: 0

README

coinpayments

Coinpayments Golang wrapper. To use, instantiate a *coinpayments.Client by calling the coinpayments.NewClient function. You will need to pass in a valid instance of the *coinpayments.Config struct, consisting of your private and public keys, as well as an instance of your desired http client.

This looks like: client, err := coinpayments.NewClient(&coinpayments.Config{ PublicKey: "yourpublickey", PrivateKey: "yourprivatekey"}, &http.Client{ Timeout: 10 * time.Second}).

Once instantiated, you can use the client to make API calls. Each call has their own Request struct, and returns it's own Response struct.

An example of the create_transaction command being called:

client.CallCreateTransaction(&coinpayments.TransactionRequest{Amount: "1", Currency1: "USD", Currency2: "BTC", BuyerEmail: "test@email.com"), where the amount is the value of the fiat currency you wish to receive.
currency1 is the type of currency that amount is specified in (USD, CAD, JPY, etc).
currency2 is the type of currency in crypto that you wish to receive (BTC, ETC, LTC, etc).
buyerEmail is optional with the API but mandatory for our client.

Call

You can use Call to call any command directly. You just need to build out your own data with an url.Values, and create an instance of the responsestruct expected by your command. Then pass in the relevant command from the coinpayments package, ie, coinpayments.CmdCreateTransaction.

Here is an example of getting the deposit address:
ie:

data := url.Values{}
data.Add("currency", "USD")
resp := coinpayments.DepositAddressResponse{}
err := c.Call(coinpayments.CmdGetDepositAddress, data, &resp)

tests

You need to export two environment variables for the tests to run - your public key, and private key.

export COINPAYMENTS_PUBLIC_KEY=yourpublickeyhere
export COINPAYMENTS_PRIVATE_KEY=yourprivatekeyhere

go test ./...

If you want to run the PBN Tag tests and have purchased a PBN Tag, you can also export it, and those tests will run. Otherwise, they will be ignored.

export COINPAYMENTS_PBN_TAG=yourpbntaghere

Implemented Methods

Information Commands

[ x ] - Get Basic Account Info [ x ] - Get Exchange Rates / Supported Coins [ x ] - Get Coin Balances [ x ] - Get Deposit Address

Receiving Payments

[ x ] - Create Transaction [ x ] - Callback Addresses [ x ] - Get TX Info [ x ] - Get TX List

Withdrawals / Transfers

[ x ] - Create Transfer [ ] - Create Withdrawal / Mass Withdrawal [ ] - Convert Coins [ ] - Get Withdrawal History [ ] - Get Withdrawal Info [ ] - Get Conversion Info

$PayByName ( PBN )

[ ] - Get Profile Information [ ] - Get Tag List [ ] - Update Tag Profile [ ] - Claim Tag

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	CmdCreateTransaction   = "create_transaction"
	CmdGetBasicInfo        = "get_basic_info"
	CmdRates               = "rates"
	CmdBalances            = "balances"
	CmdGetCallbackAddress  = "get_callback_address"
	CmdGetDepositAddress   = "get_deposit_address"
	CmdGetTxInfo           = "get_tx_info"
	CmdGetTxInfoMulti      = "get_tx_info_multi"
	CmdGetTxList           = "get_tx_ids"
	CmdGetConversionLimits = "convert_limits"
	CmdCreateTransfer      = "create_transfer"
)

Commands supported by the API

View Source
var (
	ErrCommandDoesntExist = errors.New("command is not supported by api client")
)

Errors

Functions

func SupportedCommands

func SupportedCommands() []string

SupportedCommands returns a slice of strings with all the available commands

Types

type BalancesRequest

type BalancesRequest struct {
	All string `json:"all"`
}

BalancesRequest is what we sent to the API

type BalancesResponse

type BalancesResponse struct {
	ErrorResponse
	Result map[string]BalancesResult `json:"result"`
}

BalancesResponse is the response we expect from the API server.

type BalancesResult

type BalancesResult struct {
	Balance  int    `json:"balance"`  // balance as integer in satoshis
	Balancef string `json:"balancef"` // balance as floating point number
}

BalancesResult is a result from the API for a balances command

type BasicInfoResponse

type BasicInfoResponse struct {
	ErrorResponse
	Result *BasicInfoResult `json:"result"`
}

BasicInfoResponse is a response we get back from the basic info command

func (*BasicInfoResponse) GetError

func (resp *BasicInfoResponse) GetError() string

GetError implements the Response interface

type BasicInfoResult

type BasicInfoResult struct {
	Username   string `json:"username"`
	MerchantID string `json:"merchant_id"`
	Email      string `json:"email"`
	PublicName string `json:"public_name"`
}

BasicInfoResult is the result we receive back as part of the basic info command response

type CallbackAddressRequest

type CallbackAddressRequest struct {
	Currency string `json:"currency"`
	IPNURL   string `json:"ipn_url"`
}

CallbackAddressRequest is what the server expects for the get_callback_address command

type CallbackAddressResponse

type CallbackAddressResponse struct {
	ErrorResponse
	Result *CallbackAddressResult `json:"result"`
}

CallbackAddressResponse is the response given by the API to get_callback_address command

type CallbackAddressResult

type CallbackAddressResult struct {
	Address string `json:"address"`  // address to deposit selected coin into our wallet
	PubKey  string `json:"pubkey"`   // NXT only
	DestTag string `json:"dest_tag"` // for coins needing destination tag
}

CallbackAddressResult is a result from the API for a transaction command

type Client

type Client struct {
	IPNSecret            string
	IPNURL               string
	BTCForwardingAddress string
	ETHForwardingAddress string
	// contains filtered or unexported fields
}

Client represents our wrapper for the CoinPayments API

func NewClient

func NewClient(cfg *Config, httpClient HTTPClient) (*Client, error)

NewClient returns a new Client struct, initialized and ready to go

func (*Client) Call

func (c *Client) Call(cmd string, data url.Values, responseStruct interface{}) error

Call sends a request with the given cmd and data, and then unmarshals the response into the given responseStruct. If you don't want to pass a Reader to the individual functions, you can use Call to call any command directly. You just need to build out your own data with an url.Values, and create an instance of the responsestruct expected by your command. ie: data := url.Values{} data.Add("currency", "USD") resp := coinpayments.DepositAddressResponse{} err := c.Call(coinpayments.CmdGetDepositAddress, data, &resp)

func (*Client) CallBalances

func (c *Client) CallBalances(req *BalancesRequest) (map[string]BalancesResult, error)

CallBalances calls the balances command on the API

func (*Client) CallCreateTransaction

func (c *Client) CallCreateTransaction(req *TransactionRequest) (*TransactionResult, error)

CallCreateTransaction calls the create_transaction command on the API

func (*Client) CallCreateTransfer

func (c *Client) CallCreateTransfer(req *WithdrawalRequest) (*WithdrawalResult, error)

CallCreateTransfer calls the create_Withdrawal command on the API

func (*Client) CallGetBasicInfo

func (c *Client) CallGetBasicInfo() (*BasicInfoResult, error)

CallGetBasicInfo calls the get_basic_info command on the API, returning info about our merchant account via the API keys.

func (*Client) CallGetCallbackAddress

func (c *Client) CallGetCallbackAddress(req *CallbackAddressRequest) (*CallbackAddressResponse, error)

CallGetCallbackAddress calls the get_callback_address command on the api

func (*Client) CallGetConversionLimits

func (c *Client) CallGetConversionLimits(req *ConvertLimitRequest) (*ConvertLimitResponse, error)

CallGetConversionLimits calls the get conversion limits comand on the API

func (*Client) CallGetDepositAddress

func (c *Client) CallGetDepositAddress(req *DepositAddressRequest) (*CallbackAddressResponse, error)

CallGetDepositAddress calls the get_deposit_address command on the API, which has the same response as the get_callback_address command, and thus uses it's response to unmarshal.

func (*Client) CallGetTxInfo

func (c *Client) CallGetTxInfo(req *TxInfoRequest) (*TxInfoResponse, error)

CallGetTxInfo calls the get_tx_info command on the API

func (*Client) CallGetTxList

func (c *Client) CallGetTxList(req *TxListRequest) (*TxListResponse, error)

CallGetTxList calls the get_tx_list command on the API

func (*Client) CallRates

func (c *Client) CallRates(req *RatesRequest) (map[string]RatesResult, error)

CallRates calls the get_basic_info command on the API, returning info about our merchant account via the API keys.

func (*Client) HandleIPNAPI

func (c *Client) HandleIPNAPI(reader io.Reader) (*IPNAPIResponse, error)

HandleIPNAPI handles the IPN API on input and gives a response

func (*Client) HandleIPNDeposit

func (c *Client) HandleIPNDeposit(reader io.Reader) (*IPNDepositResponse, error)

HandleIPNDeposit takes a http request and returns the post parameters. io.Reader is typically fulfilled by the `req.Body` if used in a HTTP request to handle the IPN methods. IE: cps.HandleIPNDeposit(req.Body)

type Config

type Config struct {
	PrivateKey           string `mapstructure:"private_key" json:"private_key"`
	PublicKey            string `mapstructure:"public_key" json:"public_key"`
	IPNSecret            string `mapstructure:"ipn_secret" json:"ipn_secret"`
	IPNURL               string `mapstructure:"ipn_url" json:"ipn_url"`
	BTCForwardingAddress string `mapstructure:"btc_forwarding_address" json:"btc_forwarding_address"`
	ETHForwardingAddress string `mapstructure:"eth_forwarding_address" json:"eth_forwarding_address"`
}

Config is used by Viper to parse our provided credentials

type ConvertLimitRequest

type ConvertLimitRequest struct {
	From string `json:"from"`
	To   string `json:"to"`
}

ConvertLimitRequest is used to hold our request parameters for getting conversion limits

type ConvertLimitResponse

type ConvertLimitResponse struct {
	Error  string `json:"error"`
	Result struct {
		Min string `json:"min"`
		Max string `json:"max"`
	} `json:"result"`
}

ConvertLimitResponse hold's a response to the Get Conversion Limits API call

type DepositAddressRequest

type DepositAddressRequest struct {
	Currency string `json:"currency"`
}

DepositAddressRequest is what the API expects on the get_deposit_address command

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse is an error we get back from coinpayments. All responses must have this implemented as well.

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient is an interface we rely on to send create requests

type IPNAPIResponse

type IPNAPIResponse struct {
	Status           string `json:"status"`
	StatusText       string `json:"status_text"`
	TxnID            string `json:"txn_id"`
	Currency1        string `json:"currency1"`
	Currency2        string `json:"currency2"`
	Amount1          string `json:"amount1"`
	Amount2          string `json:"amount2"`
	Fee              string `json:"fee"`
	BuyerName        string `json:"buyer_name"`
	Email            string `json:"email"`
	ItemName         string `json:"item_name"`
	ItemNumber       string `json:"item_number"`
	Invoice          string `json:"invoice"`
	Custom           string `json:"custom"`
	SendTX           string `json:"send_tx"` // the tx id of the payment to the merchant. only included when 'status' >= 100 and the payment mode is set to ASAP or nightly or if the payment is paypal passthru
	ReceivedAmount   string `json:"received_amount"`
	ReceivedConfirms string `json:"received_confirms"`
}

IPNAPIResponse is the response we expect back from the server when the command is "api"

type IPNDepositResponse

type IPNDepositResponse struct {
	Address    string `json:"address"`
	TxnID      string `json:"txn_id"`
	Status     string `json:"status"`
	StatusText string `json:"status_text"`
	Currency   string `json:"currency"`
	Confirms   string `json:"confirms"`
	Amount     string `json:"amount"`
	AmountI    string `json:"amounti"` // amount in satoshis
	Fee        string `json:"fee"`
	FeeI       string `json:"feei"` // fee in satoshis
	DestTag    string `json:"dest_tag"`
}

IPNDepositResponse is a representation of a response received when any update is happening on a deposit

type RatesRequest

type RatesRequest struct {
	Short    string `json:"short"`
	Accepted string `json:"accepted"`
}

RatesRequest holds the params the API expects for the rates command

type RatesResponse

type RatesResponse struct {
	ErrorResponse
	Result map[string]RatesResult `json:"result"`
}

RatesResponse is a response we get back from the rates command

type RatesResult

type RatesResult struct {
	IsFiat     int8   `json:"is_fiat"`
	RateBTC    string `json:"rate_btc"`
	LastUpdate string `json:"last_update"`
}

RatesResult is the result we receive back as part of the rates command response

type Reader

type Reader struct {
	Data []byte
	// contains filtered or unexported fields
}

Reader is our example implementation of a Reader. If you don't have a valid Reader to pass in to the various Call methods like a `req.Body`, you can create an instance of this Reader and pass in your data as a byte slice. ie: client.CallGetDepositAddress(&coinpayments.Reader{data: []byte("{\"currency\":\"USD\"}")}`

func (*Reader) Read

func (r *Reader) Read(p []byte) (n int, err error)

type TransactionRequest

type TransactionRequest struct {
	// required
	Amount     string `json:"amount"`
	Currency1  string `json:"currency1"`
	Currency2  string `json:"currency2"`
	BuyerEmail string `json:"buyer_email"`

	// optional
	Address    string `json:"address,omitempty"`
	BuyerName  string `json:"buyer_name,omitempty"`
	ItemName   string `json:"item_name,omitempty"`
	ItemNumber string `json:"item_number,omitempty"`
	Invoice    string `json:"invoice,omitempty"`
	Custom     string `json:"custom,omitempty"`
	IPNURL     string `json:"ipn_url,omitempty"`
	SuccessURL string `json:"success_url,omitempty"`
	CancelURL  string `json:"cancel_url,omitempty"`
}

TransactionRequest is what we sent to the API

type TransactionResponse

type TransactionResponse struct {
	ErrorResponse
	Result *TransactionResult `json:"result"`
}

TransactionResponse is the response we expect from the API server.

type TransactionResult

type TransactionResult struct {
	Amount         string `json:"amount"`
	Address        string `json:"address"`
	TxnID          string `json:"txn_id"`
	ConfirmsNeeded string `json:"confirms_needed"`
	Timeout        uint32 `json:"timeout"`
	StatusURL      string `json:"status_url"`
	CheckoutURL    string `json:"checkout_url"`
	QRCodeURL      string `json:"qrcode_url"`
}

TransactionResult is a result from the API for a transaction command

type TxInfoRequest

type TxInfoRequest struct {
	TxID string `json:"txid"`
	Full string `json:"full"`
}

TxInfoRequest is what the get_tx_info command expects

type TxInfoResponse

type TxInfoResponse struct {
	ErrorResponse
	Result map[string]interface{} `json:"result"`
}

TxInfoResponse is the response we receive from the API. The result field will not be populated on error.

type TxListRequest

type TxListRequest struct {
	Limit string `json:"limit"`
	Start string `json:"start"`
	Newer string `json:"newer"`
	All   string `json:"all"`
}

TxListRequest is what the get_tx_info command expects

type TxListResponse

type TxListResponse struct {
	ErrorResponse
	Result []string `json:"result"`
}

TxListResponse is the response we receive from the API. The result field will not be populated on error.

type WithdrawalRequest

type WithdrawalRequest struct {
	Amount      string `json:"amount"`
	Currency    string `json:"currency"`
	MerchantID  string `json:"merchant_id"`
	PBNTag      string `json:"pbntag"`
	AutoConfirm int    `json:"auto_confirm"`
}

WithdrawalRequest is what we sent to the API

type WithdrawalResponse

type WithdrawalResponse struct {
	ErrorResponse
	Result *WithdrawalResult `json:"result"`
}

WithdrawalResponse is the response we expect from the API server.

type WithdrawalResult

type WithdrawalResult struct {
	Amount string `json:"amount"`
	ID     string `json:"id"`
	Status int    `json:"status"` // 0 or 1. 0 = transfer created, waiting for email conf. 1 = transfer created with no email conf.
}

WithdrawalResult is a result from the API for a Withdrawal command

Jump to

Keyboard shortcuts

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