incognia

package module
v1.17.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2025 License: MIT Imports: 14 Imported by: 0

README

Incognia API Go Client

test workflow

Go lightweight client library for Incognia APIs.

Installation

go get repo.incognia.com/go/incognia

Usage

Configuration

First, you need to obtain an instance of the API client using New. It receives a configuration object of IncogniaClientConfig that contains the following parameters:

Parameter Description Required Default
ClientID Your client ID Yes -
ClientSecret Your client secret Yes -
Timeout Request timeout No 10 seconds
HTTPClient Custom HTTP client No http.Client

For instance, if you need the default client:

client, err := incognia.New(&incognia.IncogniaClientConfig{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
})
if err != nil {
    log.Fatal("could not initialize Incognia client")
}

or if you need a client that uses a specific timeout:

client, err := incognia.New(&incognia.IncogniaClientConfig{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    Timeout:      time.Second * 2,
})
if err != nil {
    log.Fatal("could not initialize Incognia client")
}

or if you need a custom HTTP client:

transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConns = 1000
transport.MaxIdleConnsPerHost = 100
transport.MaxConnsPerHost = 200

httpClient := &http.Client{
    Timeout:   time.Second * 2,
    Transport: transport,
}

client, err := incognia.New(&incognia.IncogniaClientConfig{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    Timeout:      time.Second * 2,
    HTTPClient:   httpClient,
})
if err != nil {
    log.Fatal("could not initialize Incognia client")
}
Incognia API

The implementation is based on the Incognia API Reference.

Authentication

Authentication is done transparently, so you don't need to worry about it.

Registering Signup

This method registers a new signup for the given installation and address, returning a SignupAssessment, containing the risk assessment and supporting evidence:

assessment, err := client.RegisterSignup("installation-id", &incognia.Address{
    AddressLine: "20 W 34th St, New York, NY 10001, United States",
    StructuredAddress: &incognia.StructuredAddress{
        Locale:       "en-US",
        CountryName:  "United States of America",
        CountryCode:  "US",
        State:        "NY",
        City:         "New York City",
        Borough:      "Manhattan",
        Neighborhood: "Midtown",
        Street:       "W 34th St.",
        Number:       "20",
        Complements:  "Floor 2",
        PostalCode:   "10001",
    },
    Coordinates: &incognia.Coordinates{
        Lat: -23.561414,
        Lng: -46.6558819,
    },
})

To provide additional parameters like policy id (optional) and account id (optional), use the RegisterSignupWithParams method:

assessment, err := client.RegisterSignupWithParams(&incognia.Signup{
	InstallationID: "installation-id",//required
	Address: &incognia.Address{//optional, use nil if you don't have an address
        AddressLine: "20 W 34th St, New York, NY 10001, United States",
        StructuredAddress: &incognia.StructuredAddress{
            Locale:       "en-US",
            CountryName:  "United States of America",
            CountryCode:  "US",
            State:        "NY",
            City:         "New York City",
            Borough:      "Manhattan",
            Neighborhood: "Midtown",
            Street:       "W 34th St.",
            Number:       "20",
            Complements:  "Floor 2",
            PostalCode:   "10001",
        },
        Coordinates: &incognia.Coordinates{
            Lat: -23.561414,
            Lng: -46.6558819,
        },
    },
    AccountID: "account-id",//optional, use empty string if you don't have an account id
    PolicyID:  "policy-id",//optional, use empty string if you don't have a policy id
})
Getting a Signup

This method allows you to query the latest assessment for a given signup event, returning a SignupAssessment, containing the risk assessment and supporting evidence:

signupID := "c9ac2803-c868-4b7a-8323-8a6b96298ebe"
assessment, err := client.GetSignupAssessment(signupID)
Registering Payment

This method registers a new payment for the given installation and account, returning a TransactionAssessment, containing the risk assessment and supporting evidence.

assessment, err := client.RegisterPayment(&incognia.Payment{
    InstallationID: "installation-id",
    AccountID:      "account-id",
    ExternalID:     "external-id",
    PolicyID:       "policy-id",
    Coupon:         &incognia.CouponType{
        Type:        "coupon-type", //it should be percent_off or fixed_value
        Value:       55.02,
        MaxDiscount: 30,
        Id:          "identifier",
        Name:        "coupon-name",
    },
    CustomProperties: myCustomPropertiesMap
    Addresses: []*incognia.TransactionAddress{
        {
            Type: incognia.Billing,
            AddressLine:    "20 W 34th St, New York, NY 10001, United States",
            StructuredAddress: &incognia.StructuredAddress{
                Locale:       "en-US",
                CountryName:  "United States of America",
                CountryCode:  "US",
                State:        "NY",
                City:         "New York City",
                Borough:      "Manhattan",
                Neighborhood: "Midtown",
                Street:       "W 34th St.",
                Number:       "20",
                Complements:  "Floor 2",
                PostalCode:   "10001",
            },
            Coordinates: &incognia.Coordinates{
                Lat: -23.561414,
                Lng: -46.6558819,
            },
        },
    },
    Value: &incognia.PaymentValue{
        Amount:   55.02,
        Currency: "BRL",
    },
    Methods: []*incognia.PaymentMethod{
        {
	    Type: incognia.GooglePay,
	},
        {
            Type: incognia.CreditCard,
            CreditCard: &incognia.CardInfo{
                Bin:            "292821",
                LastFourDigits: "2222",
                ExpiryYear:     "2020",
                ExpiryMonth:    "10",
            },
        },
    },
})

This method registers a new web payment for the given installation and account, returning a TransactionAssessment, containing the risk assessment and supporting evidence.

assessment, err := client.RegisterPayment(&incognia.Payment{
    RequestToken:   "request-token",
    AccountID:      "account-id",
    ExternalID:     "external-id",
    PolicyID:       "policy-id",
    ...
})
Registering Login

This method registers a new login for the given installation and account, returning a TransactionAssessment, containing the risk assessment and supporting evidence.

assessment, err := client.RegisterLogin(&incognia.Login{
    InstallationID:             "installation-id",
    AccountID:                  "account-id",
    ExternalID:                 "external-id",
    PolicyID:                   "policy-id",
    PaymentMethodIdentifier:    "payment-method-identifier",
    CustomProperties: myCustomPropertiesMap,
})

This method registers a new web login for the given account and request-token, returning a TransactionAssessment, containing the risk assessment and supporting evidence.

assessment, err := client.RegisterLogin(&incognia.Login{
    RequestToken:               "request-token",
    AccountID:                  "account-id",
    ...
})
Registering Payment or Login without evaluating its risk assessment

Turning off the risk assessment evaluation allows you to register a new transaction (Login or Payment), but the response (TransactionAssessment) will be empty. For instance, if you're using the risk assessment only for some payment transactions, you should still register all the other ones: this will avoid any bias on the risk assessment computation.

To register a login or a payment without evaluating its risk assessment, you should use the Eval *bool attribute as follows:

Login example:

shouldEval := false

assessment, err := client.RegisterLogin(&incognia.Login{
    Eval:           &shouldEval,
    InstallationID: "installation-id",
    AccountID:      "account-id",
    ExternalID:     "external-id",
    PolicyID:       "policy-id",
})

Payment example:

shouldEval := false

assessment, err := client.RegisterPayment(&incognia.Payment{
    Eval:            &shouldEval,
    InstallationID: "installation-id",
    AccountID:      "account-id",
    ExternalID:     "external-id",
    PolicyID:       "policy-id",
    Addresses: []*incognia.TransactionAddress{
        {
            Type: incognia.Billing,
            AddressLine:    "20 W 34th St, New York, NY 10001, United States",
            StructuredAddress: &incognia.StructuredAddress{
                Locale:       "en-US",
                CountryName:  "United States of America",
    ...
Sending Feedback

This method registers a feedback event for the given identifiers (represented in FeedbackIdentifiers) related to a signup, login or payment.

occurredAt, err := time.Parse(time.RFC3339, "2024-07-22T15:20:00Z")
feedbackEvent := incognia.AccountTakeover
err := client.RegisterFeedback(feedbackEvent, &occurredAt, &incognia.FeedbackIdentifiers{
    InstallationID: "some-installation-id",
    AccountID:      "some-account-id",
})
Authentication

Our library authenticates clients automatically, but clients may want to authenticate manually because our token route has a long response time (to avoid brute force attacks). If that's your case, you can choose the moment which authentication occurs by leveraging ManualRefreshTokenProvider, as shown by the example:

tokenClient := incognia.NewTokenClient(&TokenClientConfig{clientID: clientID, clientSecret: clientSecret})
tokenProvider := incognia.NewManualRefreshTokenProvider(tokenClient)
c, err := incognia.New(&IncogniaClientConfig{TokenProvider: tokenProvider})
if err != nil {
    log.Fatal("could not initialize Incognia client")
}

go func(i *incognia.Client) {
  for {
      accessToken, err := tokenProvider.Refresh()
      if (err != nil) {
          log.PrintLn("could not refresh incognia token")
          continue
      }
      time.Sleep(time.Until(accessToken.GetExpiresAt()))
   }
}(c)

You can also keep the default automatic authentication but increase the token route timeout by changing the TokenRouteTimeout parameter of your IncogniaClientConfig.

Evidences

Every assessment response (TransactionAssessment and SignupAssessment) includes supporting evidence in the type Evidence, which provides methods GetEvidence and GetEvidenceAsInt64 to help you getting and parsing values. You can see usage examples below:

var deviceModel string

err := assessment.Evidence.GetEvidence("device_model", &deviceModel)
if err != nil {
    return err
}

fmt.Println(deviceModel)

You can also access specific evidences using their full path. For example, to get location_permission_enabled evidence from the following response:

{
    "evidence": {
        "location_services": {
            "location_permission_enabled": true
        }
    }
}

call any type of GetEvidence method using the evidence's full path:

var locationPermissionEnabled bool
err := assessment.Evidence.GetEvidence("location_services.location_permission_enabled", &locationPermissionEnabled)
if err != nil {
    return err
}

fmt.Println(locationPermissionEnabled)

You can find all available evidence here.

How to Contribute

If you have found a bug or if you have a feature request, please report them at this repository issues section.

What is Incognia?

Incognia is a location identity platform for mobile apps that enables:

  • Real-time address verification for onboarding
  • Frictionless authentication
  • Real-time transaction verification

License

Documentation

Index

Constants

View Source
const (
	CreditCard     paymentMethodType = "credit_card"
	DebitCard      paymentMethodType = "debit_card"
	GooglePay      paymentMethodType = "google_pay"
	ApplePay       paymentMethodType = "apple_pay"
	NuPay          paymentMethodType = "nu_pay"
	Pix            paymentMethodType = "pix"
	MealVoucher    paymentMethodType = "meal_voucher"
	AccountBalance paymentMethodType = "account_balance"
)

Variables

View Source
var (
	ErrMissingPayment                      = errors.New("missing payment parameters")
	ErrMissingLogin                        = errors.New("missing login parameters")
	ErrMissingSignup                       = errors.New("missing signup parameters")
	ErrMissingInstallationID               = errors.New("missing installation id")
	ErrMissingInstallationIDOrSessionToken = errors.New("missing installation id or session token")
	ErrMissingIdentifier                   = errors.New("missing installation id, request token or session token")
	ErrMissingAccountID                    = errors.New("missing account id")
	ErrMissingSignupID                     = errors.New("missing signup id")
	ErrMissingTimestamp                    = errors.New("missing timestamp")
	ErrInvalidFeedbackType                 = errors.New("invalid feedback type")
	ErrMissingClientIDOrClientSecret       = errors.New("client id and client secret are required")
	ErrConfigIsNil                         = errors.New("incognia client config is required")
)
View Source
var (
	ErrTokenNotFound = errors.New("token not found in memory")
	ErrTokenExpired  = errors.New("incognia token expired")
)
View Source
var (
	ErrEvidenceNotFound = errors.New("evidence not found")
)
View Source
var (
	ErrInvalidCredentials = errors.New("invalid credentials")
)

Functions

This section is empty.

Types

type Address

type Address struct {
	Coordinates       *Coordinates
	StructuredAddress *StructuredAddress
	AddressLine       string
}

type AddressType

type AddressType string
const (
	Shipping AddressType = "shipping"
	Billing  AddressType = "billing"
	Home     AddressType = "home"
)

type Assessment

type Assessment string
const (
	LowRisk     Assessment = "low_risk"
	HighRisk    Assessment = "high_risk"
	UnknownRisk Assessment = "unknown_risk"
)

type AutoRefreshTokenProvider added in v1.7.0

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

func NewAutoRefreshTokenProvider added in v1.7.0

func NewAutoRefreshTokenProvider(tokenClient *TokenClient) *AutoRefreshTokenProvider

func (*AutoRefreshTokenProvider) GetToken added in v1.7.0

func (t *AutoRefreshTokenProvider) GetToken() (Token, error)

type CardInfo

type CardInfo struct {
	Bin            string `json:"bin"`
	LastFourDigits string `json:"last_four_digits"`
	ExpiryYear     string `json:"expiry_year,omitempty"`
	ExpiryMonth    string `json:"expiry_month,omitempty"`
}

type Client

type Client struct {
	UserAgent string
	// contains filtered or unexported fields
}

func New

func New(config *IncogniaClientConfig) (*Client, error)

func (*Client) GetSignupAssessment

func (c *Client) GetSignupAssessment(signupID string) (ret *SignupAssessment, err error)

func (*Client) RegisterFeedback

func (c *Client) RegisterFeedback(feedbackEvent FeedbackType, occurredAt *time.Time, feedbackIdentifiers *FeedbackIdentifiers) (err error)

func (*Client) RegisterFeedbackWithExpiration added in v1.12.0

func (c *Client) RegisterFeedbackWithExpiration(feedbackEvent FeedbackType, occurredAt *time.Time, expiresAt *time.Time, feedbackIdentifiers *FeedbackIdentifiers) (err error)

func (*Client) RegisterLogin added in v1.2.0

func (c *Client) RegisterLogin(login *Login) (ret *TransactionAssessment, err error)

func (*Client) RegisterPayment

func (c *Client) RegisterPayment(payment *Payment) (ret *TransactionAssessment, err error)

func (*Client) RegisterSignup

func (c *Client) RegisterSignup(installationID string, address *Address) (ret *SignupAssessment, err error)

func (*Client) RegisterSignupWithParams added in v1.10.0

func (c *Client) RegisterSignupWithParams(params *Signup) (ret *SignupAssessment, err error)

type Coordinates

type Coordinates struct {
	Lat float64 `json:"lat"`
	Lng float64 `json:"lng"`
}

type CouponType added in v1.16.0

type CouponType struct {
	Type        string  `json:"type"`
	Value       float64 `json:"value"`
	MaxDiscount float64 `json:"max_discount"`
	Id          string  `json:"id"`
	Name        string  `json:"name"`
}

type Evidence added in v1.3.0

type Evidence map[string]interface{}

func (Evidence) GetEvidence added in v1.3.0

func (a Evidence) GetEvidence(evidenceName string, evidenceOut interface{}) error

func (Evidence) GetEvidenceAsInt64 added in v1.3.0

func (a Evidence) GetEvidenceAsInt64(evidenceName string) (int64, error)

type FeedbackIdentifiers

type FeedbackIdentifiers struct {
	InstallationID string
	SessionToken   string
	RequestToken   string
	LoginID        string
	PaymentID      string
	SignupID       string
	AccountID      string
	ExternalID     string
}

type FeedbackType

type FeedbackType string
const (
	PaymentAccepted               FeedbackType = "payment_accepted"
	PaymentDeclined               FeedbackType = "payment_declined"
	PaymentDeclinedByRiskAnalysis FeedbackType = "payment_declined_by_risk_analysis"
	PaymentDeclinedByAcquirer     FeedbackType = "payment_declined_by_acquirer"
	PaymentDeclinedByBusiness     FeedbackType = "payment_declined_by_business"
	PaymentDeclinedByManualReview FeedbackType = "payment_declined_by_manual_review"
	PaymentAcceptedByThirdParty   FeedbackType = "payment_accepted_by_third_party"
	LoginAccepted                 FeedbackType = "login_accepted"
	LoginDeclined                 FeedbackType = "login_declined"
	SignupAccepted                FeedbackType = "signup_accepted"
	SignupDeclined                FeedbackType = "signup_declined"
	ChallengePassed               FeedbackType = "challenge_passed"
	ChallengeFailed               FeedbackType = "challenge_failed"
	PasswordChangedSuccessfully   FeedbackType = "password_changed_successfully"
	PasswordChangeFailed          FeedbackType = "password_change_failed"
	Verified                      FeedbackType = "verified"
	NotVerified                   FeedbackType = "not_verified"
	Chargeback                    FeedbackType = "chargeback"
	PromotionAbuse                FeedbackType = "promotion_abuse"
	AccountTakeover               FeedbackType = "account_takeover"
	MposFraud                     FeedbackType = "mpos_fraud"
	ChargebackNotification        FeedbackType = "chargeback_notification"
)

type IncogniaClientConfig

type IncogniaClientConfig struct {
	ClientID          string
	ClientSecret      string
	TokenProvider     TokenProvider
	Timeout           time.Duration
	TokenRouteTimeout time.Duration
	HTTPClient        *http.Client
	// Deprecated: Region is no longer used to determine endpoints
	Region Region
}

type Login added in v1.2.0

type Login struct {
	InstallationID          *string
	SessionToken            *string
	RequestToken            string
	AccountID               string
	ExternalID              string
	PolicyID                string
	PaymentMethodIdentifier string
	Eval                    *bool
	AppVersion              string
	DeviceOs                string
	CustomProperties        map[string]interface{}
}

type ManualRefreshTokenProvider added in v1.7.0

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

func NewManualRefreshTokenProvider added in v1.7.0

func NewManualRefreshTokenProvider(tokenClient *TokenClient) *ManualRefreshTokenProvider

func (*ManualRefreshTokenProvider) GetToken added in v1.7.0

func (t *ManualRefreshTokenProvider) GetToken() (Token, error)

func (*ManualRefreshTokenProvider) Refresh added in v1.7.0

func (t *ManualRefreshTokenProvider) Refresh() (Token, error)

type Payment

type Payment struct {
	InstallationID   *string
	SessionToken     *string
	RequestToken     string
	AppVersion       string
	DeviceOs         string
	AccountID        string
	ExternalID       string
	PolicyID         string
	Coupon           *CouponType
	Addresses        []*TransactionAddress
	Value            *PaymentValue
	Methods          []*PaymentMethod
	Eval             *bool
	CustomProperties map[string]interface{}
}

type PaymentMethod

type PaymentMethod struct {
	Identifier string            `json:"identifier,omitempty"`
	Type       paymentMethodType `json:"type"`
	CreditCard *CardInfo         `json:"credit_card_info,omitempty"`
	DebitCard  *CardInfo         `json:"debit_card_info,omitempty"`
}

type PaymentValue

type PaymentValue struct {
	Amount   float64 `json:"amount"`
	Currency string  `json:"currency"`
}

type Reason added in v1.8.0

type Reason struct {
	Code   string
	Source string
}

type Region

type Region int64
const (
	US Region = iota
	BR
)

type Signup added in v1.10.0

type Signup struct {
	InstallationID string
	RequestToken   string
	SessionToken   string
	AppVersion     string
	DeviceOs       string
	Address        *Address
	AccountID      string
	PolicyID       string
	ExternalID     string
}

type SignupAssessment

type SignupAssessment struct {
	ID             string     `json:"id"`
	DeviceID       string     `json:"device_id"`
	RequestID      string     `json:"request_id"`
	RiskAssessment Assessment `json:"risk_assessment"`
	Evidence       Evidence   `json:"evidence"`
	Reasons        []Reason   `json:"reasons"`
}

type StructuredAddress

type StructuredAddress struct {
	Locale       string `json:"locale"`
	CountryName  string `json:"country_name"`
	CountryCode  string `json:"country_code"`
	State        string `json:"state"`
	City         string `json:"city"`
	Borough      string `json:"borough"`
	Neighborhood string `json:"neighborhood"`
	Street       string `json:"street"`
	Number       string `json:"number"`
	Complements  string `json:"complements"`
	PostalCode   string `json:"postal_code"`
}

type Token added in v1.7.0

type Token interface {
	IsExpired() bool
	GetExpiresAt() time.Time
	Type() string
	SetAuthHeader(*http.Request)
}

type TokenClient added in v1.7.0

type TokenClient struct {
	ClientID     string
	ClientSecret string

	UserAgent string
	// contains filtered or unexported fields
}

func NewTokenClient added in v1.7.0

func NewTokenClient(config *TokenClientConfig) *TokenClient

type TokenClientConfig added in v1.7.0

type TokenClientConfig struct {
	ClientID     string
	ClientSecret string
	Timeout      time.Duration
}

type TokenProvider added in v1.7.0

type TokenProvider interface {
	GetToken() (Token, error)
}

type TransactionAddress

type TransactionAddress struct {
	Type              AddressType        `json:"type"`
	Coordinates       *Coordinates       `json:"address_coordinates"`
	StructuredAddress *StructuredAddress `json:"structured_address"`
	AddressLine       string             `json:"address_line"`
}

type TransactionAssessment

type TransactionAssessment struct {
	ID             string     `json:"id"`
	RiskAssessment Assessment `json:"risk_assessment"`
	DeviceID       string     `json:"device_id"`
	Evidence       Evidence   `json:"evidence"`
	Reasons        []Reason   `json:"reasons"`
}

Jump to

Keyboard shortcuts

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