payment

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2021 License: MPL-2.0 Imports: 62 Imported by: 0

README

Brave SKUs Service

Getting Started
  1. Begin with development setup steps 1 through 4 from the bat-go readme

  2. Bring up the SKUs containers locally with make docker-refresh-payment

  3. View container logs with docker logs grant-payment-refresh

  4. SKUs API will be available at localhost:3335

  5. Commit code and refresh the containers with docker restart grant-payment-refresh!

SKU Tokens

SKU Tokens represent cookie-like objects with domain specific caveats, new tokens can be created following the instructions in this readme

This is an example of one possible SKU token:

tokens:
  - id: "brave-together-paid sku token v1"
    version: 1
    location: "together.bsg.brave.software"
    first_party_caveats:
      - sku: "brave-together-paid"
      - price: 5
      - currency: "USD"
      - description: "One month paid subscription for Brave Together"
      - credential_type: "time-limited"
      - credential_valid_duration: "P1M"
      - payment_methods: ["stripe"]
Creating a Free Trial

Given the knowledge of a free trial SKU unlimited numbers of trials can be created. Care must be taken to keep free trial SKUs secret.

Certain SKU tokens do not have a price, and once users have created an order for them they may redeem credentials to access the related service. In this example, we will create a free trial order for Brave Talk:

Construct a POST request to /v1/orders with the following metadata

{
	"items": [{
		"sku": "MDAyOWxvY2F0aW9uIHRvZ2V0aGVyLmJzZy5icmF2ZS5zb2Z0d2FyZQowMDMwaWRlbnRpZmllciBicmF2ZS10b2dldGhlci1mcmVlIHNrdSB0b2tlbiB2MQowMDIwY2lkIHNrdT1icmF2ZS10b2dldGhlci1mcmVlCjAwMTBjaWQgcHJpY2U9MAowMDE1Y2lkIGN1cnJlbmN5PUJBVAowMDNjY2lkIGRlc2NyaXB0aW9uPU9uZSBtb250aCBmcmVlIHRyaWFsIGZvciBCcmF2ZSBUb2dldGhlcgowMDI1Y2lkIGNyZWRlbnRpYWxfdHlwZT10aW1lLWxpbWl0ZWQKMDAyNmNpZCBjcmVkZW50aWFsX3ZhbGlkX2R1cmF0aW9uPVAxTQowMDJmc2lnbmF0dXJlIGebBXoPnj06tvlJkPEDLp9nfWo6Wfc1Txj6jTlgxjrQCg==",
		"quantity": 1
	}]
}

Upon GET request to /v1/orders/:orderId, server will respond with:

{
	"id": "92aafa4b-da7e-46b1-99c1-e8d30b26bc0f",
	"createdAt": "2021-04-12T00:11:51.954386Z",
	"currency": "BAT",
	"updatedAt": "2021-04-12T00:11:51.954386Z",
	"totalPrice": "0",
	"merchantId": "brave.com",
	"location": "together.bsg.brave.software",
	"status": "paid",
	"items": [{
		"id": "0b573a13-3c3d-40b7-bdac-879c531d31fb",
		"orderId": "92aafa4b-da7e-46b1-99c1-e8d30b26bc0f",
		"sku": "brave-together-free",
		"createdAt": "2021-04-12T00:11:51.954386Z",
		"updatedAt": "2021-04-12T00:11:51.954386Z",
		"currency": "BAT",
		"quantity": 1,
		"price": "0",
		"subtotal": "0",
		"location": "together.bsg.brave.software",
		"description": "One month free trial for Brave Together",
		"type": "time-limited"
	}]
}

Because the status on this order is paid we may create and request credentials

Construct a POST request to /v1/orders/:orderId/credentials with the following metadata

{
	"itemId": <itemId>,
	"blindedCreds": [<Base64 Encoded Blinded Credentials>]
}

Server will respond with status 200 OK. To retrieve these credentials construct a GET request to /v1/orders/:orderId/credentials

Server will respond with the following payload:

[
  {
    "id": "0b573a13-3c3d-40b7-bdac-879c531d31fb",
    "orderId": "92aafa4b-da7e-46b1-99c1-e8d30b26bc0f",
    "issuedAt": "2021-04-12",
    "expiresAt": "2021-05-17",
    "token": "ZCtG5A8lvArgJtBOR4I4tfHmDsM+pBrb9STaa1k1qbOhGHaYO2HFA2MUvoJ9edGX"
  }
]
Creating a Paid Order

Similarly to a free order, we will submit a creation request, however we will include an email which will be needed for management of subscriptions

Construct a POST request to /v1/orders with the following metadata

{"items": [
{"sku": "MDAyOWxvY2F0aW9uIHRvZ2V0aGVyLmJzZy5icmF2ZS5zb2Z0d2FyZQowMDMwaWRlbnRpZmllciBicmF2ZS10b2dldGhlci1wYWlkIHNrdSB0b2tlbiB2MQowMDIwY2lkIHNrdT1icmF2ZS10b2dldGhlci1wYWlkCjAwMTBjaWQgcHJpY2U9NQowMDE1Y2lkIGN1cnJlbmN5PVVTRAowMDQzY2lkIGRlc2NyaXB0aW9uPU9uZSBtb250aCBwYWlkIHN1YnNjcmlwdGlvbiBmb3IgQnJhdmUgVG9nZXRoZXIKMDAyNWNpZCBjcmVkZW50aWFsX3R5cGU9dGltZS1saW1pdGVkCjAwMjZjaWQgY3JlZGVudGlhbF92YWxpZF9kdXJhdGlvbj1QMU0KMDAyZnNpZ25hdHVyZSDKLJ7NuuzP3KdmTdVnn0dI3JmIfNblQKmY+WBJOqnQJAo=", "quantity": 1}],
 "email": "customeremail@gmail.com"
}

Upon GET request to /v1/orders/:orderId, server will respond with:

{
	"id": "89ded3d9-55e1-4e26-bc18-228e76cf03ca",
	"createdAt": "2021-04-12T00:51:44.61976Z",
	"currency": "USD",
	"updatedAt": "2021-04-12T00:51:45.515351Z",
	"totalPrice": "5",
	"merchantId": "brave.com",
	"location": "together.bsg.brave.software",
	"status": "pending",
	"items": [{
		"id": "355ae321-0ceb-4698-9fed-158190da6fa4",
		"orderId": "89ded3d9-55e1-4e26-bc18-228e76cf03ca",
		"sku": "brave-together-paid",
		"createdAt": "2021-04-12T00:51:44.61976Z",
		"updatedAt": "2021-04-12T00:51:44.61976Z",
		"currency": "USD",
		"quantity": 1,
		"price": "5",
		"subtotal": "5",
		"location": "together.bsg.brave.software",
		"description": "One month paid subscription for Brave Together",
		"type": "time-limited"
	}],
	"stripeCheckoutSessionId": "cs_test_a1g0n8FWNT3ClB2p9shKlpchGTw7cDKQCOqLJ1dSBcRd9ZsLssrtDLbZgM"
}

Because this order is Stripe payable, we will receive a Stripe Checkout Session Id, this identifier can be used to fulfill the order via a credit card. For example if we construct the following sample script:

<html>

<head>
    <title>Buy cool new product</title>
    <script src="https://js.stripe.com/v3/"></script>
</head>

<body>
    <button id="checkout-button">Checkout</button>
    <script type="text/javascript">
        // Create an instance of the Stripe object with your publishable API key
        var stripe = Stripe('pk_test_51HlmudHof20bphG64WGsYJhhJ3OsgZw5DyVx5mM7PdW4K7gLJS5KoMiA624HEJIWXImp0DEj7nKg2x8l7nGT6zhk00dtatBliN');
        var checkoutButton = document.getElementById('checkout-button');
        checkoutButton.addEventListener('click', function () {
            // Create a new Checkout Session using the server-side endpoint you
            // created in step 3.
            return stripe.redirectToCheckout({ sessionId: 'cs_test_a1g0n8FWNT3ClB2p9shKlpchGTw7cDKQCOqLJ1dSBcRd9ZsLssrtDLbZgM' });
        });
    </script>
</body>

</html>

And host locally, we can redirect to a page similar to this:

Screen Shot 2021-04-11 at 9 18 10 PM

A credit card can then be entered, and upon successful payment, the corresponding order will become paid. Once paid, credentials may be created and requested as in the free trial.

Architecture

Documentation above refers to a general use of the payment service. In the context of Brave Talk, the order of various calls and the service making the call is outlined in the diagram below:

Screen Shot 2021-04-30 at 1 58 22 PM

Documentation

Index

Constants

View Source
const (
	StripePaymentMethod               = "stripe"
	StripeInvoiceUpdated              = "invoice.updated"
	StripeInvoicePaid                 = "invoice.paid"
	StripeCustomerSubscriptionDeleted = "customer.subscription.deleted"
)

StripePaymentMethod - the label for stripe payment method

View Source
const (
	// OrderStatusCanceled - string literal used in db for canceled status
	OrderStatusCanceled = "canceled"
	// OrderStatusPaid - string literal used in db for canceled status
	OrderStatusPaid = "paid"
	// OrderStatusPending - string literal used in db for pending status
	OrderStatusPending = "pending"
)
View Source
const (
	// UserWalletVoteSKU - special vote sku to denote user wallet funding
	UserWalletVoteSKU string = "user-wallet-vote"
	// AnonCardVoteSKU - special vote sku to denote anon-card funding
	AnonCardVoteSKU = "anon-card-vote"
)

Variables

View Source
var (
	// ErrInvalidSKUToken - the sku was invalid
	ErrInvalidSKUToken = errors.New("failed to validate sku token")
	// ErrInvalidSKUTokenSKU - the sku was invalid
	ErrInvalidSKUTokenSKU = fmt.Errorf("invalid sku in sku token: %w", ErrInvalidSKUToken)
	// ErrInvalidSKUTokenBadMerchant - the merchant in the sku is invalid
	ErrInvalidSKUTokenBadMerchant = fmt.Errorf("invalid merchant id in sku token: %w", ErrInvalidSKUToken)
)
View Source
var EncryptionKey = os.Getenv("ENCRYPTION_KEY")

EncryptionKey for encrypting secrets

View Source
var (
	// ErrInvalidSKU - this sku is malformed or failed signature validation
	ErrInvalidSKU = errors.New("Invalid SKU Token provided in request")
)

Functions

func CancelOrder added in v0.5.0

func CancelOrder(service *Service) handlers.AppHandler

CancelOrder is the handler for cancelling an order

func CreateAnonCardTransaction

func CreateAnonCardTransaction(service *Service) handlers.AppHandler

CreateAnonCardTransaction creates a transaction against an order

func CreateGeminiTransaction added in v0.5.0

func CreateGeminiTransaction(service *Service) handlers.AppHandler

CreateGeminiTransaction creates a transaction against an order

func CreateKey

func CreateKey(service *Service) handlers.AppHandler

CreateKey is the handler for creating keys for a merchant

func CreateOrder

func CreateOrder(service *Service) handlers.AppHandler

CreateOrder is the handler for creating a new order

func CreateOrderCreds

func CreateOrderCreds(service *Service) handlers.AppHandler

CreateOrderCreds is the handler for creating order credentials

func CreateUpholdTransaction

func CreateUpholdTransaction(service *Service) handlers.AppHandler

CreateUpholdTransaction creates a transaction against an order

func CredentialRouter added in v0.4.0

func CredentialRouter(service *Service) chi.Router

CredentialRouter handles calls relating to credentials

func CredentialV2Router added in v0.5.1

func CredentialV2Router(service *Service) chi.Router

CredentialV2Router handles calls relating to credentials

func DeleteKey

func DeleteKey(service *Service) handlers.AppHandler

DeleteKey deletes a key

func DeleteOrderCreds added in v0.5.0

func DeleteOrderCreds(service *Service) handlers.AppHandler

DeleteOrderCreds is the handler for deleting order credentials

func GenerateSecret

func GenerateSecret() (secret string, nonce string, err error)

GenerateSecret creates a random key for merchants

func GetCaveats added in v0.5.0

func GetCaveats(ctx context.Context) map[string]string

GetCaveats returns any authorized caveats that have been stored in the context

func GetKeys

func GetKeys(service *Service) handlers.AppHandler

GetKeys returns all keys for a specified merchant

func GetMerchant added in v0.5.0

func GetMerchant(ctx context.Context) (string, error)

GetMerchant returns any authorized merchant that has been stored in the context

func GetOrder

func GetOrder(service *Service) handlers.AppHandler

GetOrder is the handler for getting an order

func GetOrderCreds

func GetOrderCreds(service *Service) handlers.AppHandler

GetOrderCreds is the handler for fetching order credentials

func GetOrderCredsByID

func GetOrderCredsByID(service *Service) handlers.AppHandler

GetOrderCredsByID is the handler for fetching order credentials by an item id

func GetTransactions

func GetTransactions(service *Service) handlers.AppHandler

GetTransactions is the handler for listing the transactions for an order

func HandleStripeWebhook added in v0.5.0

func HandleStripeWebhook(service *Service) handlers.AppHandler

HandleStripeWebhook is the handler for stripe checkout session webhooks

func InitEncryptionKeys

func InitEncryptionKeys()

InitEncryptionKeys copies the specified encryption key into memory once

func MakeVote

func MakeVote(service *Service) handlers.AppHandler

MakeVote is the handler for making a vote using credentials

func MerchantRouter

func MerchantRouter(service *Service) chi.Router

MerchantRouter handles calls made for the merchant

func MerchantTransactions

func MerchantTransactions(service *Service) handlers.AppHandler

MerchantTransactions is the handler for getting paginated merchant transactions

func Router

func Router(service *Service) chi.Router

Router for order endpoints

func SetOrderTrialDays added in v0.5.0

func SetOrderTrialDays(service *Service) handlers.AppHandler

SetOrderTrialDays is the handler for cancelling an order

func VerifyCredentialV1 added in v0.5.1

func VerifyCredentialV1(service *Service) handlers.AppHandler

VerifyCredentialV1 is the handler for verifying subscription credentials

func VerifyCredentialV2 added in v0.5.1

func VerifyCredentialV2(service *Service) handlers.AppHandler

VerifyCredentialV2 - version 2 of verify credential

func VoteRouter

func VoteRouter(service *Service) chi.Router

VoteRouter for voting endpoint

func WebhookRouter added in v0.5.0

func WebhookRouter(service *Service) chi.Router

WebhookRouter - handles calls from various payment method webhooks informing payments of completion

Types

type CreateAnonCardTransactionRequest

type CreateAnonCardTransactionRequest struct {
	WalletID    uuid.UUID `json:"paymentId"`
	Transaction string    `json:"transaction"`
}

CreateAnonCardTransactionRequest includes information needed to create a anon card transaction

type CreateCheckoutSessionResponse added in v0.5.0

type CreateCheckoutSessionResponse struct {
	SessionID string `json:"checkoutSessionId"`
}

CreateCheckoutSessionResponse - the structure of a checkout session response

type CreateKeyRequest

type CreateKeyRequest struct {
	Name string `json:"name" valid:"required"`
}

CreateKeyRequest includes information needed to create a key

type CreateKeyResponse added in v0.5.0

type CreateKeyResponse struct {
	*Key
	SecretKey string `json:"secretKey"`
}

CreateKeyResponse includes information about the created key

type CreateOrderCredsRequest

type CreateOrderCredsRequest struct {
	ItemID       uuid.UUID `json:"itemId" valid:"-"`
	BlindedCreds []string  `json:"blindedCreds" valid:"base64"`
}

CreateOrderCredsRequest includes the item ID and blinded credentials which to be signed

type CreateOrderRequest

type CreateOrderRequest struct {
	Items []OrderItemRequest `json:"items" valid:"-"`
	Email string             `json:"email" valid:"-"`
}

CreateOrderRequest includes information needed to create an order

type CreateTransactionRequest

type CreateTransactionRequest struct {
	ExternalTransactionID uuid.UUID `json:"externalTransactionID" valid:"requiredUUID"`
}

CreateTransactionRequest includes information needed to create a transaction

type CredentialBinding

type CredentialBinding struct {
	PublicKey     string `json:"publicKey" valid:"base64"`
	TokenPreimage string `json:"t" valid:"base64"`
	Signature     string `json:"signature" valid:"base64"`
}

CredentialBinding includes info needed to redeem a single credential

func DeduplicateCredentialBindings

func DeduplicateCredentialBindings(tokens ...CredentialBinding) []CredentialBinding

DeduplicateCredentialBindings - given a list of tokens return a deduplicated list

type Datastore

type Datastore interface {
	grantserver.Datastore
	// CreateOrder is used to create an order for payments
	CreateOrder(totalPrice decimal.Decimal, merchantID string, status string, currency string, location string, validFor *time.Duration, orderItems []OrderItem, allowedPaymentMethods *Methods) (*Order, error)
	// SetOrderTrialDays - set the number of days of free trial for this order
	SetOrderTrialDays(ctx context.Context, orderID *uuid.UUID, days int64) (*Order, error)
	// GetOrder by ID
	GetOrder(orderID uuid.UUID) (*Order, error)
	// RenewOrder - renew the order with this id
	RenewOrder(ctx context.Context, orderID uuid.UUID) error
	// UpdateOrder updates an order when it has been paid
	UpdateOrder(orderID uuid.UUID, status string) error
	// UpdateOrderMetadata adds a key value pair to an order's metadata
	UpdateOrderMetadata(orderID uuid.UUID, key string, value string) error
	// CreateTransaction creates a transaction
	CreateTransaction(orderID uuid.UUID, externalTransactionID string, status string, currency string, kind string, amount decimal.Decimal) (*Transaction, error)
	// GetTransaction returns a transaction given an external transaction id
	GetTransaction(externalTransactionID string) (*Transaction, error)
	// GetTransactions returns all the transactions for a specific order
	GetTransactions(orderID uuid.UUID) (*[]Transaction, error)
	// GetPagedMerchantTransactions returns all the transactions for a specific order
	GetPagedMerchantTransactions(ctx context.Context, merchantID uuid.UUID, pagination *inputs.Pagination) (*[]Transaction, int, error)
	// GetSumForTransactions gets a decimal sum of for transactions for an order
	GetSumForTransactions(orderID uuid.UUID) (decimal.Decimal, error)
	// InsertIssuer
	InsertIssuer(issuer *Issuer) (*Issuer, error)
	// GetIssuer
	GetIssuer(merchantID string) (*Issuer, error)
	// GetIssuerByPublicKey
	GetIssuerByPublicKey(publicKey string) (*Issuer, error)
	// InsertOrderCreds
	InsertOrderCreds(creds *OrderCreds) error
	// GetOrderCreds
	GetOrderCreds(orderID uuid.UUID, isSigned bool) (*[]OrderCreds, error)
	// DeleteOrderCreds
	DeleteOrderCreds(orderID uuid.UUID, isSigned bool) error
	// GetOrderCredsByItemID retrieves an order credential by item id
	GetOrderCredsByItemID(orderID uuid.UUID, itemID uuid.UUID, isSigned bool) (*OrderCreds, error)
	// RunNextOrderJob
	RunNextOrderJob(ctx context.Context, worker OrderWorker) (bool, error)

	// GetKeysByMerchant
	GetKeysByMerchant(merchant string, showExpired bool) (*[]Key, error)
	// GetKey
	GetKey(id uuid.UUID, showExpired bool) (*Key, error)
	// CreateKey
	CreateKey(merchant string, name string, encryptedSecretKey string, nonce string) (*Key, error)
	// DeleteKey
	DeleteKey(id uuid.UUID, delaySeconds int) (*Key, error)

	// Votes
	GetUncommittedVotesForUpdate(ctx context.Context) (*sqlx.Tx, []*VoteRecord, error)
	CommitVote(ctx context.Context, vr VoteRecord, tx *sqlx.Tx) error
	MarkVoteErrored(ctx context.Context, vr VoteRecord, tx *sqlx.Tx) error
	InsertVote(ctx context.Context, vr VoteRecord) error

	CheckExpiredCheckoutSession(uuid.UUID) (bool, string, error)
	IsStripeSub(uuid.UUID) (bool, string, error)
}

Datastore abstracts over the underlying datastore

func NewPostgres

func NewPostgres(databaseURL string, performMigration bool, migrationTrack string, dbStatsPrefix ...string) (Datastore, error)

NewPostgres creates a new Postgres Datastore

type DatastoreWithPrometheus

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

DatastoreWithPrometheus implements Datastore interface with all methods wrapped with Prometheus metrics

func NewDatastoreWithPrometheus

func NewDatastoreWithPrometheus(base Datastore, instanceName string) DatastoreWithPrometheus

NewDatastoreWithPrometheus returns an instance of the Datastore decorated with prometheus summary metric

func (DatastoreWithPrometheus) CheckExpiredCheckoutSession added in v0.5.0

func (_d DatastoreWithPrometheus) CheckExpiredCheckoutSession(u1 uuid.UUID) (b1 bool, s1 string, err error)

CheckExpiredCheckoutSession implements Datastore

func (DatastoreWithPrometheus) CommitVote

func (_d DatastoreWithPrometheus) CommitVote(ctx context.Context, vr VoteRecord, tx *sqlx.Tx) (err error)

CommitVote implements Datastore

func (DatastoreWithPrometheus) CreateKey

func (_d DatastoreWithPrometheus) CreateKey(merchant string, name string, encryptedSecretKey string, nonce string) (kp1 *Key, err error)

CreateKey implements Datastore

func (DatastoreWithPrometheus) CreateOrder

func (_d DatastoreWithPrometheus) CreateOrder(totalPrice decimal.Decimal, merchantID string, status string, currency string, location string, validFor *time.Duration, orderItems []OrderItem, allowedPaymentMethods *Methods) (op1 *Order, err error)

CreateOrder implements Datastore

func (DatastoreWithPrometheus) CreateTransaction

func (_d DatastoreWithPrometheus) CreateTransaction(orderID uuid.UUID, externalTransactionID string, status string, currency string, kind string, amount decimal.Decimal) (tp1 *Transaction, err error)

CreateTransaction implements Datastore

func (DatastoreWithPrometheus) DeleteKey

func (_d DatastoreWithPrometheus) DeleteKey(id uuid.UUID, delaySeconds int) (kp1 *Key, err error)

DeleteKey implements Datastore

func (DatastoreWithPrometheus) DeleteOrderCreds added in v0.5.0

func (_d DatastoreWithPrometheus) DeleteOrderCreds(orderID uuid.UUID, isSigned bool) (err error)

DeleteOrderCreds implements Datastore

func (DatastoreWithPrometheus) GetIssuer

func (_d DatastoreWithPrometheus) GetIssuer(merchantID string) (ip1 *Issuer, err error)

GetIssuer implements Datastore

func (DatastoreWithPrometheus) GetIssuerByPublicKey

func (_d DatastoreWithPrometheus) GetIssuerByPublicKey(publicKey string) (ip1 *Issuer, err error)

GetIssuerByPublicKey implements Datastore

func (DatastoreWithPrometheus) GetKey added in v0.5.0

func (_d DatastoreWithPrometheus) GetKey(id uuid.UUID, showExpired bool) (kp1 *Key, err error)

GetKey implements Datastore

func (DatastoreWithPrometheus) GetKeysByMerchant added in v0.5.0

func (_d DatastoreWithPrometheus) GetKeysByMerchant(merchant string, showExpired bool) (kap1 *[]Key, err error)

GetKeysByMerchant implements Datastore

func (DatastoreWithPrometheus) GetOrder

func (_d DatastoreWithPrometheus) GetOrder(orderID uuid.UUID) (op1 *Order, err error)

GetOrder implements Datastore

func (DatastoreWithPrometheus) GetOrderCreds

func (_d DatastoreWithPrometheus) GetOrderCreds(orderID uuid.UUID, isSigned bool) (oap1 *[]OrderCreds, err error)

GetOrderCreds implements Datastore

func (DatastoreWithPrometheus) GetOrderCredsByItemID

func (_d DatastoreWithPrometheus) GetOrderCredsByItemID(orderID uuid.UUID, itemID uuid.UUID, isSigned bool) (op1 *OrderCreds, err error)

GetOrderCredsByItemID implements Datastore

func (DatastoreWithPrometheus) GetPagedMerchantTransactions

func (_d DatastoreWithPrometheus) GetPagedMerchantTransactions(ctx context.Context, merchantID uuid.UUID, pagination *inputs.Pagination) (tap1 *[]Transaction, i1 int, err error)

GetPagedMerchantTransactions implements Datastore

func (DatastoreWithPrometheus) GetSumForTransactions

func (_d DatastoreWithPrometheus) GetSumForTransactions(orderID uuid.UUID) (d1 decimal.Decimal, err error)

GetSumForTransactions implements Datastore

func (DatastoreWithPrometheus) GetTransaction

func (_d DatastoreWithPrometheus) GetTransaction(externalTransactionID string) (tp1 *Transaction, err error)

GetTransaction implements Datastore

func (DatastoreWithPrometheus) GetTransactions

func (_d DatastoreWithPrometheus) GetTransactions(orderID uuid.UUID) (tap1 *[]Transaction, err error)

GetTransactions implements Datastore

func (DatastoreWithPrometheus) GetUncommittedVotesForUpdate

func (_d DatastoreWithPrometheus) GetUncommittedVotesForUpdate(ctx context.Context) (tp1 *sqlx.Tx, vpa1 []*VoteRecord, err error)

GetUncommittedVotesForUpdate implements Datastore

func (DatastoreWithPrometheus) InsertIssuer

func (_d DatastoreWithPrometheus) InsertIssuer(issuer *Issuer) (ip1 *Issuer, err error)

InsertIssuer implements Datastore

func (DatastoreWithPrometheus) InsertOrderCreds

func (_d DatastoreWithPrometheus) InsertOrderCreds(creds *OrderCreds) (err error)

InsertOrderCreds implements Datastore

func (DatastoreWithPrometheus) InsertVote

func (_d DatastoreWithPrometheus) InsertVote(ctx context.Context, vr VoteRecord) (err error)

InsertVote implements Datastore

func (DatastoreWithPrometheus) IsStripeSub added in v0.5.0

func (_d DatastoreWithPrometheus) IsStripeSub(u1 uuid.UUID) (b1 bool, s1 string, err error)

IsStripeSub implements Datastore

func (DatastoreWithPrometheus) MarkVoteErrored

func (_d DatastoreWithPrometheus) MarkVoteErrored(ctx context.Context, vr VoteRecord, tx *sqlx.Tx) (err error)

MarkVoteErrored implements Datastore

func (DatastoreWithPrometheus) Migrate

func (_d DatastoreWithPrometheus) Migrate(p1 ...uint) (err error)

Migrate implements Datastore

func (DatastoreWithPrometheus) NewMigrate

func (_d DatastoreWithPrometheus) NewMigrate() (mp1 *migrate.Migrate, err error)

NewMigrate implements Datastore

func (DatastoreWithPrometheus) RawDB

func (_d DatastoreWithPrometheus) RawDB() (dp1 *sqlx.DB)

RawDB implements Datastore

func (DatastoreWithPrometheus) RenewOrder added in v0.5.0

func (_d DatastoreWithPrometheus) RenewOrder(ctx context.Context, orderID uuid.UUID) (err error)

RenewOrder implements Datastore

func (DatastoreWithPrometheus) RollbackTx

func (_d DatastoreWithPrometheus) RollbackTx(tx *sqlx.Tx)

RollbackTx implements Datastore

func (DatastoreWithPrometheus) RollbackTxAndHandle added in v0.4.0

func (_d DatastoreWithPrometheus) RollbackTxAndHandle(tx *sqlx.Tx) (err error)

RollbackTxAndHandle implements Datastore

func (DatastoreWithPrometheus) RunNextOrderJob

func (_d DatastoreWithPrometheus) RunNextOrderJob(ctx context.Context, worker OrderWorker) (b1 bool, err error)

RunNextOrderJob implements Datastore

func (DatastoreWithPrometheus) SetOrderTrialDays added in v0.5.0

func (_d DatastoreWithPrometheus) SetOrderTrialDays(ctx context.Context, orderID *uuid.UUID, days int64) (op1 *Order, err error)

SetOrderTrialDays implements Datastore

func (DatastoreWithPrometheus) UpdateOrder

func (_d DatastoreWithPrometheus) UpdateOrder(orderID uuid.UUID, status string) (err error)

UpdateOrder implements Datastore

func (DatastoreWithPrometheus) UpdateOrderMetadata added in v0.5.0

func (_d DatastoreWithPrometheus) UpdateOrderMetadata(orderID uuid.UUID, key string, value string) (err error)

UpdateOrderMetadata implements Datastore

type DeleteKeyRequest

type DeleteKeyRequest struct {
	DelaySeconds int `json:"delaySeconds" valid:"-"`
}

DeleteKeyRequest includes information needed to delete a key

type Issuer

type Issuer struct {
	ID         uuid.UUID `json:"id" db:"id"`
	CreatedAt  time.Time `json:"createdAt" db:"created_at"`
	MerchantID string    `json:"merchantId" db:"merchant_id"`
	PublicKey  string    `json:"publicKey" db:"public_key"`
}

Issuer includes information about a particular credential issuer

func (*Issuer) Name

func (issuer *Issuer) Name() string

Name returns the name of the issuer as known by the challenge bypass server

type Key

type Key struct {
	ID                 string     `json:"id" db:"id"`
	Name               string     `json:"name" db:"name"`
	Merchant           string     `json:"merchant" db:"merchant_id"`
	EncryptedSecretKey string     `json:"-" db:"encrypted_secret_key"`
	Nonce              string     `json:"-" db:"nonce"`
	CreatedAt          time.Time  `json:"createdAt" db:"created_at"`
	Expiry             *time.Time `json:"expiry" db:"expiry"`
}

Key represents a merchant's keys to validate skus

func (*Key) GetSecretKey added in v0.5.0

func (key *Key) GetSecretKey() (*string, error)

GetSecretKey decrypts the secret key from the database

type Methods added in v0.5.0

type Methods []string

Methods type is a string slice holding payments

func (*Methods) Equal added in v0.5.0

func (pm *Methods) Equal(b *Methods) bool

Equal - check equality

func (*Methods) Scan added in v0.5.0

func (pm *Methods) Scan(src interface{}) error

Scan the src sql type into the passed JSONStringArray

func (*Methods) Value added in v0.5.0

func (pm *Methods) Value() (driver.Value, error)

Value the driver.Value representation

type Order

type Order struct {
	ID                    uuid.UUID            `json:"id" db:"id"`
	CreatedAt             time.Time            `json:"createdAt" db:"created_at"`
	Currency              string               `json:"currency" db:"currency"`
	UpdatedAt             time.Time            `json:"updatedAt" db:"updated_at"`
	TotalPrice            decimal.Decimal      `json:"totalPrice" db:"total_price"`
	MerchantID            string               `json:"merchantId" db:"merchant_id"`
	Location              datastore.NullString `json:"location" db:"location"`
	Status                string               `json:"status" db:"status"`
	Items                 []OrderItem          `json:"items"`
	AllowedPaymentMethods Methods              `json:"allowedPaymentMethods" db:"allowed_payment_methods"`
	Metadata              datastore.Metadata   `json:"metadata" db:"metadata"`
	LastPaidAt            *time.Time           `json:"lastPaidAt" db:"last_paid_at"`
	ExpiresAt             *time.Time           `json:"expiresAt" db:"expires_at"`
	ValidFor              *time.Duration       `json:"validFor" db:"valid_for"`
	TrialDays             *int64               `json:"-" db:"trial_days"`
}

Order includes information about a particular order

func (Order) CreateStripeCheckoutSession added in v0.5.0

func (order Order) CreateStripeCheckoutSession(email, successURI, cancelURI string, freeTrialDays int64) (CreateCheckoutSessionResponse, error)

CreateStripeCheckoutSession - Create a Stripe Checkout Session for an Order

func (Order) CreateStripeLineItems added in v0.5.0

func (order Order) CreateStripeLineItems() []*stripe.CheckoutSessionLineItemParams

CreateStripeLineItems - create line items for a checkout session with stripe

func (Order) IsPaid

func (order Order) IsPaid() bool

IsPaid returns true if the order is paid

func (Order) IsStripePayable added in v0.5.0

func (order Order) IsStripePayable() bool

IsStripePayable returns true if every item is payable by Stripe

type OrderCreds

type OrderCreds struct {
	ID           uuid.UUID                  `json:"id" db:"item_id"`
	OrderID      uuid.UUID                  `json:"orderId" db:"order_id"`
	IssuerID     uuid.UUID                  `json:"issuerId" db:"issuer_id"`
	BlindedCreds jsonutils.JSONStringArray  `json:"blindedCreds" db:"blinded_creds"`
	SignedCreds  *jsonutils.JSONStringArray `json:"signedCreds" db:"signed_creds"`
	BatchProof   *string                    `json:"batchProof" db:"batch_proof"`
	PublicKey    *string                    `json:"publicKey" db:"public_key"`
}

OrderCreds encapsulates the credentials to be signed in response to a completed order

type OrderItem

type OrderItem struct {
	ID                  uuid.UUID            `json:"id" db:"id"`
	OrderID             uuid.UUID            `json:"orderId" db:"order_id"`
	SKU                 string               `json:"sku" db:"sku"`
	CreatedAt           *time.Time           `json:"createdAt" db:"created_at"`
	UpdatedAt           *time.Time           `json:"updatedAt" db:"updated_at"`
	Currency            string               `json:"currency" db:"currency"`
	Quantity            int                  `json:"quantity" db:"quantity"`
	Price               decimal.Decimal      `json:"price" db:"price"`
	Subtotal            decimal.Decimal      `json:"subtotal" db:"subtotal"`
	Location            datastore.NullString `json:"location" db:"location"`
	Description         datastore.NullString `json:"description" db:"description"`
	CredentialType      string               `json:"credentialType" db:"credential_type"`
	ValidFor            *time.Duration       `json:"validFor" db:"valid_for"`
	ValidForISO         *string              `json:"validForIso" db:"valid_for_iso"`
	Metadata            datastore.Metadata   `json:"metadata" db:"metadata"`
	IssuanceIntervalISO *string              `json:"issuanceInterval" db:"issuance_interval"`
}

OrderItem includes information about a particular order item

type OrderItemRequest

type OrderItemRequest struct {
	SKU      string `json:"sku" valid:"-"`
	Quantity int    `json:"quantity" valid:"int"`
}

OrderItemRequest is the body for creating new items

type OrderWorker

type OrderWorker interface {
	SignOrderCreds(ctx context.Context, orderID uuid.UUID, issuer Issuer, blindedCreds []string) (*OrderCreds, error)
}

OrderWorker attempts to work on an order job by signing the blinded credentials of the client

type Postgres

type Postgres struct {
	grantserver.Postgres
}

Postgres is a Datastore wrapper around a postgres database

func (*Postgres) CheckExpiredCheckoutSession added in v0.5.0

func (pg *Postgres) CheckExpiredCheckoutSession(orderID uuid.UUID) (bool, string, error)

CheckExpiredCheckoutSession - check order metadata for an expired checkout session id

func (*Postgres) CommitVote

func (pg *Postgres) CommitVote(ctx context.Context, vr VoteRecord, tx *sqlx.Tx) error

CommitVote - Update a vote to show it has been processed, designed to run on a transaction so a batch number of votes can be processed.

func (*Postgres) CreateKey

func (pg *Postgres) CreateKey(merchant string, name string, encryptedSecretKey string, nonce string) (*Key, error)

CreateKey creates an encrypted key in the database based on the merchant

func (*Postgres) CreateOrder

func (pg *Postgres) CreateOrder(totalPrice decimal.Decimal, merchantID, status, currency, location string, validFor *time.Duration, orderItems []OrderItem, allowedPaymentMethods *Methods) (*Order, error)

CreateOrder creates orders given the total price, merchant ID, status and items of the order

func (*Postgres) CreateTransaction

func (pg *Postgres) CreateTransaction(orderID uuid.UUID, externalTransactionID string, status string, currency string, kind string, amount decimal.Decimal) (*Transaction, error)

CreateTransaction creates a transaction given an orderID, externalTransactionID, currency, and a kind of transaction

func (*Postgres) DeleteKey

func (pg *Postgres) DeleteKey(id uuid.UUID, delaySeconds int) (*Key, error)

DeleteKey updates a key with an expiration time based on the id

func (*Postgres) DeleteOrderCreds added in v0.5.0

func (pg *Postgres) DeleteOrderCreds(orderID uuid.UUID, isSigned bool) error

DeleteOrderCreds deletes the order credentials for a OrderID

func (*Postgres) GetIssuer

func (pg *Postgres) GetIssuer(merchantID string) (*Issuer, error)

GetIssuer retrieves the given issuer

func (*Postgres) GetIssuerByPublicKey

func (pg *Postgres) GetIssuerByPublicKey(publicKey string) (*Issuer, error)

GetIssuerByPublicKey or return an error

func (*Postgres) GetKey added in v0.5.0

func (pg *Postgres) GetKey(id uuid.UUID, showExpired bool) (*Key, error)

GetKey returns the specified key, conditionally checking if it is expired

func (*Postgres) GetKeysByMerchant added in v0.5.0

func (pg *Postgres) GetKeysByMerchant(merchant string, showExpired bool) (*[]Key, error)

GetKeysByMerchant returns a list of active API keys

func (*Postgres) GetOrder

func (pg *Postgres) GetOrder(orderID uuid.UUID) (*Order, error)

GetOrder queries the database and returns an order

func (*Postgres) GetOrderCreds

func (pg *Postgres) GetOrderCreds(orderID uuid.UUID, isSigned bool) (*[]OrderCreds, error)

GetOrderCreds returns the order credentials for a OrderID

func (*Postgres) GetOrderCredsByItemID

func (pg *Postgres) GetOrderCredsByItemID(orderID uuid.UUID, itemID uuid.UUID, isSigned bool) (*OrderCreds, error)

GetOrderCredsByItemID returns the order credentials for a OrderID by the itemID

func (*Postgres) GetPagedMerchantTransactions

func (pg *Postgres) GetPagedMerchantTransactions(
	ctx context.Context, merchantID uuid.UUID, pagination *inputs.Pagination) (*[]Transaction, int, error)

GetPagedMerchantTransactions - get a paginated list of transactions for a merchant

func (*Postgres) GetSumForTransactions

func (pg *Postgres) GetSumForTransactions(orderID uuid.UUID) (decimal.Decimal, error)

GetSumForTransactions returns the calculated sum

func (*Postgres) GetTransaction

func (pg *Postgres) GetTransaction(externalTransactionID string) (*Transaction, error)

GetTransaction returns a single of transaction given an external transaction Id

func (*Postgres) GetTransactions

func (pg *Postgres) GetTransactions(orderID uuid.UUID) (*[]Transaction, error)

GetTransactions returns the list of transactions given an orderID

func (*Postgres) GetUncommittedVotesForUpdate

func (pg *Postgres) GetUncommittedVotesForUpdate(ctx context.Context) (*sqlx.Tx, []*VoteRecord, error)

GetUncommittedVotesForUpdate - row locking on number of votes we will be pulling returns a transaction to commit, the vote records, and an error

func (*Postgres) InsertIssuer

func (pg *Postgres) InsertIssuer(issuer *Issuer) (*Issuer, error)

InsertIssuer inserts the given issuer

func (*Postgres) InsertOrderCreds

func (pg *Postgres) InsertOrderCreds(creds *OrderCreds) error

InsertOrderCreds inserts the given order creds

func (*Postgres) InsertVote

func (pg *Postgres) InsertVote(ctx context.Context, vr VoteRecord) error

InsertVote - Add a vote to our "queue" to be processed

func (*Postgres) IsStripeSub added in v0.5.0

func (pg *Postgres) IsStripeSub(orderID uuid.UUID) (bool, string, error)

IsStripeSub - is this order related to a stripe subscription, if so, true, subscription id returned

func (*Postgres) MarkVoteErrored

func (pg *Postgres) MarkVoteErrored(ctx context.Context, vr VoteRecord, tx *sqlx.Tx) error

MarkVoteErrored - Update a vote to show it has errored, designed to run on a transaction so a batch number of votes can be processed.

func (*Postgres) RenewOrder added in v0.5.0

func (pg *Postgres) RenewOrder(ctx context.Context, orderID uuid.UUID) error

RenewOrder updates the orders status to paid and paid at time, inserts record of this order

Status should either be one of pending, paid, fulfilled, or canceled.

func (*Postgres) RunNextOrderJob

func (pg *Postgres) RunNextOrderJob(ctx context.Context, worker OrderWorker) (bool, error)

RunNextOrderJob to sign order credentials if there is a order waiting, returning true if a job was attempted

func (*Postgres) SetOrderTrialDays added in v0.5.0

func (pg *Postgres) SetOrderTrialDays(ctx context.Context, orderID *uuid.UUID, days int64) (*Order, error)

SetOrderTrialDays - set the number of days of free trial for this order

func (*Postgres) UpdateOrder

func (pg *Postgres) UpdateOrder(orderID uuid.UUID, status string) error

UpdateOrder updates the orders status.

Status should either be one of pending, paid, fulfilled, or canceled.

func (*Postgres) UpdateOrderMetadata added in v0.5.0

func (pg *Postgres) UpdateOrderMetadata(orderID uuid.UUID, key string, value string) error

UpdateOrderMetadata adds a key value pair to an order's metadata

type Service

type Service struct {
	Datastore Datastore
	// contains filtered or unexported fields
}

Service contains datastore

func InitService

func InitService(ctx context.Context, datastore Datastore, walletService *wallet.Service) (service *Service, err error)

InitService creates a service using the passed datastore and clients configured from the environment

func (*Service) CancelOrder added in v0.5.0

func (s *Service) CancelOrder(orderID uuid.UUID) error

CancelOrder - cancels an order, propogates to stripe if needed

func (*Service) CreateAnonCardTransaction

func (s *Service) CreateAnonCardTransaction(ctx context.Context, walletID uuid.UUID, transaction string, orderID uuid.UUID) (*Transaction, error)

CreateAnonCardTransaction takes a signed transaction and executes it on behalf of an anon card

func (*Service) CreateIssuer

func (service *Service) CreateIssuer(ctx context.Context, merchantID string) (*Issuer, error)

CreateIssuer creates a new challenge bypass credential issuer, saving it's information into the datastore

func (*Service) CreateOrderCreds

func (service *Service) CreateOrderCreds(ctx context.Context, orderID uuid.UUID, itemID uuid.UUID, blindedCreds []string) error

CreateOrderCreds if the order is complete

func (*Service) CreateOrderFromRequest

func (s *Service) CreateOrderFromRequest(ctx context.Context, req CreateOrderRequest) (*Order, error)

CreateOrderFromRequest creates an order from the request

func (*Service) CreateOrderItemFromMacaroon added in v0.5.0

func (s *Service) CreateOrderItemFromMacaroon(ctx context.Context, sku string, quantity int) (*OrderItem, *Methods, error)

CreateOrderItemFromMacaroon creates an order item from a macaroon

func (*Service) CreateTransactionFromRequest

func (s *Service) CreateTransactionFromRequest(ctx context.Context, req CreateTransactionRequest, orderID uuid.UUID, getCustodialTx getCustodialTxFn) (*Transaction, error)

CreateTransactionFromRequest queries the endpoints and creates a transaciton

func (*Service) GetActiveCredentialSigningKey added in v0.5.1

func (s *Service) GetActiveCredentialSigningKey(ctx context.Context, merchantID string) ([]byte, error)

GetActiveCredentialSigningKey get the current active signing key for this merchant

func (*Service) GetCredentialSigningKeys added in v0.5.1

func (s *Service) GetCredentialSigningKeys(ctx context.Context, merchantID string) ([][]byte, error)

GetCredentialSigningKeys get the current list of credential signing keys for this merchant

func (*Service) GetCredentials added in v0.5.0

func (s *Service) GetCredentials(ctx context.Context, orderID uuid.UUID) (interface{}, int, error)

GetCredentials - based on the order, get the associated credentials

func (*Service) GetOrCreateIssuer

func (service *Service) GetOrCreateIssuer(ctx context.Context, merchantID string) (*Issuer, error)

GetOrCreateIssuer gets a matching issuer if one exists and otherwise creates one

func (*Service) GetOrder added in v0.5.0

func (s *Service) GetOrder(orderID uuid.UUID) (*Order, error)

GetOrder - business logic for getting an order, needs to validate the checkout session is not expired

func (*Service) GetSingleUseCreds added in v0.5.0

func (s *Service) GetSingleUseCreds(ctx context.Context, order *Order) ([]OrderCreds, int, error)

GetSingleUseCreds get an order's single use creds

func (*Service) GetTimeLimitedCreds added in v0.5.0

func (s *Service) GetTimeLimitedCreds(ctx context.Context, order *Order) ([]TimeLimitedCreds, int, error)

GetTimeLimitedCreds get an order's time limited creds

func (*Service) InitKafka

func (s *Service) InitKafka(ctx context.Context) error

InitKafka by creating a kafka writer and creating local copies of codecs

func (*Service) IsOrderPaid

func (s *Service) IsOrderPaid(orderID uuid.UUID) (bool, error)

IsOrderPaid determines if the order has been paid

func (*Service) IsPaused added in v0.4.0

func (s *Service) IsPaused() bool

IsPaused - is the worker paused?

func (*Service) Jobs

func (s *Service) Jobs() []srv.Job

Jobs - Implement srv.JobService interface

func (*Service) LookupVerifier added in v0.5.0

func (service *Service) LookupVerifier(ctx context.Context, keyID string) (context.Context, *httpsignature.Verifier, error)

LookupVerifier returns the merchant key corresponding to the keyID used for verifying requests

func (*Service) MerchantSignedMiddleware added in v0.5.0

func (service *Service) MerchantSignedMiddleware() func(http.Handler) http.Handler

MerchantSignedMiddleware requires that requests are signed by valid merchant keys

func (*Service) PauseWorker added in v0.4.0

func (s *Service) PauseWorker(until time.Time)

PauseWorker - pause worker until time specified

func (*Service) RunNextOrderJob

func (s *Service) RunNextOrderJob(ctx context.Context) (bool, error)

RunNextOrderJob takes the next order job and completes it

func (*Service) RunNextVoteDrainJob

func (service *Service) RunNextVoteDrainJob(ctx context.Context) (bool, error)

RunNextVoteDrainJob - Attempt to drain the vote queue

func (*Service) SetOrderTrialDays added in v0.5.0

func (s *Service) SetOrderTrialDays(ctx context.Context, orderID *uuid.UUID, days int64) error

SetOrderTrialDays set the order's free trial days

func (*Service) SignOrderCreds

func (service *Service) SignOrderCreds(ctx context.Context, orderID uuid.UUID, issuer Issuer, blindedCreds []string) (*OrderCreds, error)

SignOrderCreds signs the blinded credentials

func (*Service) UpdateOrderMetadata added in v0.5.0

func (s *Service) UpdateOrderMetadata(orderID uuid.UUID, key string, value string) error

UpdateOrderMetadata updates the metadata on an order

func (*Service) UpdateOrderStatus

func (s *Service) UpdateOrderStatus(orderID uuid.UUID) error

UpdateOrderStatus checks to see if an order has been paid and updates it if so

func (*Service) ValidateOrderMerchantAndCaveats added in v0.5.0

func (service *Service) ValidateOrderMerchantAndCaveats(r *http.Request, orderID uuid.UUID) error

ValidateOrderMerchantAndCaveats checks that the current authentication of the request has permissions to this order by cross-checking the merchant and caveats in context

func (*Service) Vote

func (service *Service) Vote(
	ctx context.Context, credentials []CredentialBinding, voteText string) error

Vote based on the browser's attention

type SetOrderTrialDaysInput added in v0.5.0

type SetOrderTrialDaysInput struct {
	TrialDays int64 `json:"trialDays" valid:"int"`
}

SetOrderTrialDaysInput - SetOrderTrialDays handler input

type TimeLimitedCreds added in v0.5.0

type TimeLimitedCreds struct {
	ID        uuid.UUID `json:"id"`
	OrderID   uuid.UUID `json:"orderId"`
	IssuedAt  string    `json:"issuedAt"`
	ExpiresAt string    `json:"expiresAt"`
	Token     string    `json:"token"`
}

TimeLimitedCreds encapsulates time-limited credentials

type Transaction

type Transaction struct {
	ID                    uuid.UUID       `json:"id" db:"id"`
	OrderID               uuid.UUID       `json:"orderId" db:"order_id"`
	CreatedAt             time.Time       `json:"createdAt" db:"created_at"`
	UpdatedAt             time.Time       `json:"updatedAt" db:"updated_at"`
	ExternalTransactionID string          `json:"external_transaction_id" db:"external_transaction_id"`
	Status                string          `json:"status" db:"status"`
	Currency              string          `json:"currency" db:"currency"`
	Kind                  string          `json:"kind" db:"kind"`
	Amount                decimal.Decimal `json:"amount" db:"amount"`
}

Transaction includes information about a particular order. Status can be pending, failure, completed, or error.

type VerifyCredentialOpaque added in v0.5.1

type VerifyCredentialOpaque struct {
	Type         string  `json:"type" valid:"in(single-use|time-limited)"`
	Version      float64 `json:"version" valid:"-"`
	Presentation string  `json:"presentation" valid:"base64"`
}

VerifyCredentialOpaque includes an opaque presentation blob

type VerifyCredentialRequestV1 added in v0.5.1

type VerifyCredentialRequestV1 struct {
	Type         string  `json:"type" valid:"in(single-use|time-limited)"`
	Version      float64 `json:"version" valid:"-"`
	SKU          string  `json:"sku" valid:"-"`
	MerchantID   string  `json:"merchantId" valid:"-"`
	Presentation string  `json:"presentation" valid:"base64"`
}

VerifyCredentialRequestV1 includes an opaque subscription credential blob

func (*VerifyCredentialRequestV1) GetMerchantID added in v0.5.1

func (vcr *VerifyCredentialRequestV1) GetMerchantID(ctx context.Context) string

GetMerchantID - implement credential interface

func (*VerifyCredentialRequestV1) GetPresentation added in v0.5.1

func (vcr *VerifyCredentialRequestV1) GetPresentation(ctx context.Context) string

GetPresentation - implement credential interface

func (*VerifyCredentialRequestV1) GetSku added in v0.5.1

GetSku - implement credential interface

func (*VerifyCredentialRequestV1) GetType added in v0.5.1

func (vcr *VerifyCredentialRequestV1) GetType(ctx context.Context) string

GetType - implement credential interface

type VerifyCredentialRequestV2 added in v0.5.1

type VerifyCredentialRequestV2 struct {
	SKU              string                  `json:"sku" valid:"-"`
	MerchantID       string                  `json:"merchantId" valid:"-"`
	Credential       string                  `json:"credential" valid:"base64"`
	CredentialOpaque *VerifyCredentialOpaque `json:"-" valid:"-"`
}

VerifyCredentialRequestV2 includes an opaque subscription credential blob

func (*VerifyCredentialRequestV2) Decode added in v0.5.1

func (vcr *VerifyCredentialRequestV2) Decode(ctx context.Context, data []byte) error

Decode - implement Decodable interface

func (*VerifyCredentialRequestV2) GetMerchantID added in v0.5.1

func (vcr *VerifyCredentialRequestV2) GetMerchantID(ctx context.Context) string

GetMerchantID - implement credential interface

func (*VerifyCredentialRequestV2) GetPresentation added in v0.5.1

func (vcr *VerifyCredentialRequestV2) GetPresentation(ctx context.Context) string

GetPresentation - implement credential interface

func (*VerifyCredentialRequestV2) GetSku added in v0.5.1

GetSku - implement credential interface

func (*VerifyCredentialRequestV2) GetType added in v0.5.1

func (vcr *VerifyCredentialRequestV2) GetType(ctx context.Context) string

GetType - implement credential interface

func (*VerifyCredentialRequestV2) Validate added in v0.5.1

func (vcr *VerifyCredentialRequestV2) Validate(ctx context.Context) error

Validate - implement Validable interface

type Vote

type Vote struct {
	Type          string `json:"type" valid:"in(auto-contribute|oneoff-tip|recurring-tip)"`
	Channel       string `json:"channel" valid:"-"`
	VoteTally     int64  `json:"-" valid:"-"`
	FundingSource string `json:"-" valid:"-"`
}

Vote encapsulates information from the browser about attention

func (*Vote) Base64Decode

func (v *Vote) Base64Decode(text string) error

Base64Decode unmarshalls the vote from a string.

func (*Vote) Decode

func (v *Vote) Decode(ctx context.Context, input []byte) error

Decode - implement inputs.Decodable interface for input

func (*Vote) Validate

func (v *Vote) Validate(ctx context.Context) error

Validate - implement inputs.Validatable interface for input

type VoteEvent

type VoteEvent struct {
	Type          string          `json:"type"`
	Channel       string          `json:"channel"`
	ID            uuid.UUID       `json:"id"`
	CreatedAt     time.Time       `json:"createdAt"`
	BaseVoteValue decimal.Decimal `json:"baseVoteValue"`
	VoteTally     int64           `json:"voteTally"`
	FundingSource string          `json:"fundingSource"`
}

VoteEvent encapsulates user and server provided information about a request to contribute kafka event

func NewVoteEvent

func NewVoteEvent(v Vote) (*VoteEvent, error)

NewVoteEvent - Create a new VoteEvent given a Vote

func (*VoteEvent) CodecDecode

func (ve *VoteEvent) CodecDecode(codec *goavro.Codec, binary []byte) error

CodecDecode - Decode using avro vote codec

func (*VoteEvent) CodecEncode

func (ve *VoteEvent) CodecEncode(codec *goavro.Codec) ([]byte, error)

CodecEncode - encode using avro vote codec

type VoteRecord

type VoteRecord struct {
	ID                 uuid.UUID
	RequestCredentials string
	VoteText           string
	VoteEventBinary    []byte
	Erred              bool
	Processed          bool
}

VoteRecord - how the ac votes are stored in the queue

type VoteRequest

type VoteRequest struct {
	Vote        string              `json:"vote" valid:"base64"`
	Credentials []CredentialBinding `json:"credentials"`
}

VoteRequest includes a suggestion payload and credentials to be redeemed

Jump to

Keyboard shortcuts

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