sift

package module
v0.0.0-...-4161596 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2023 License: MIT Imports: 9 Imported by: 0

README

License Build Status

Go 1.3 Ready Go 1.4 Ready Go 1.5 Ready Go 1.6 Ready

sift-golang

Unofficial Sift Science API (Golang client)

Todo

Things that are done/supported and those that yet need to be supported

  • Events API
  • Label API
  • Score API
  • Device Fingerprinting API

Installation

Installation for this package should be straight forward.

go get github.com/0x19/sift-golang

Once it's installed you can import it as

import (
	"github.com/0x19/sift-golang"
)

Usage

Bellow you can find few examples on how to use sift-golang.

Track an event

Here's an example that sends a $transaction event to sift.

package main

import (
	"log"

	"github.com/0x19/sift-golang"
)

func main() {
	s := sift.New("your_api_key")

	// Name of the event. Can be pre-defined such as $transaction and custom
	// such as "my_custom_event"
	eventName := "$transaction"

	data := map[string]interface{}{
		"$user_id":          "[email protected]",
		"$transaction_id":   "1233456",
		"$currency_code":    "USD",
		"$amount":           15230000,
		"$time":             1327604222,
		"trip_time":         930,
		"distance_traveled": 5.26,
		"$order_id":         "ORDER-123124124",
	}

	extras := map[string]interface{}{
		"return_action": true,
	}

	r, err := s.Track(eventName, data, extras)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Got tracking record: %v", r)
}

Label a user as good or bad

package main

import (
	"log"

	"github.com/0x19/sift-golang"
)

func main() {
	s := sift.New("your_api_key")

	record, err := s.Label("some-user-id", map[string]interface{}{
		"$is_bad":      true,
		"$reasons":     []string{"$chargeback", "$fraud"},
		"$description": "Some description about this user...",
	})

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Got label record: %v", record)
}

Remove label from user

package main

import (
	"log"

	"github.com/0x19/sift-golang"
)

func main() {
	s := sift.New("your_api_key")

	response, err := s.UnLabel("some-user-id")

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Got un-label response: %v", response)
}

Get user's score

package main

import (
	"log"

	"github.com/0x19/sift-golang"
)

func main() {
	s := sift.New("your_api_key")

	record, err := s.Score("some-user-id")

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Got score response: %v", record.Score)
}

Contributions

Please make sure to read Contribution Guide if you are interested into code contributions :)

License

(The MIT License)

Copyright (c) 2016 Nevio Vesic, http://www.neviovesic.com

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 (
	API_URL        = "https://api.siftscience.com"
	TIMEOUT        = time.Duration(2) // In seconds
	VERSION        = "0.0.1"
	API_VERSION    = 203
	ENV_PRODUCTION = "production"
	ENV_SANDBOX    = "sandbox"
)

Variables

View Source
var (
	// NoContentStatusCodes - Here as helper to define if request was successful or not
	NoContentStatusCodes = map[int]string{204: "", 304: ""}

	// AvailableMethods - List of all methods that Sift Science API accepts
	AvailableMethods = map[string]string{"GET": "get", "POST": "post", "DELETE": "delete"}

	// ErrorCodes A successful API request will respond with an HTTP 200. An invalid API
	// request will respond with an HTTP 400. The response body will be a JSON
	// object describing why the request failed.
	// These are JSON error response codes in case you need them
	ErrorCodes = map[int]string{
		-4:  "Service currently unavailable. Please try again later.",
		-3:  "Server-side timeout processing request. Please try again later.",
		-2:  "Unexpected server-side error",
		-1:  "Unexpected server-side error",
		0:   "Success",
		51:  "Invalid API Key. Please check your credentials and try again.",
		52:  "Invalid characters in field name",
		53:  "Invalid characters in field value",
		54:  "Specified user_id has no scoreable events",
		55:  "Missing required field",
		56:  "Invalid JSON in request",
		57:  "Invalid HTTP body",
		60:  "Rate limited; too many events have been received in a short period of time",
		104: "Invalid API version",
		105: "Not a valid reserved field",
	}
)

Functions

This section is empty.

Types

type Action

type Action struct {
	ID     string `json:"id,omitempty"`
	Action struct {
		ID string `json:"id,omitempty"`
	} `json:"action,omitempty"`
	Entity struct {
		ID string `json:"id,omitempty"`
	}
	Time     time.Duration `json:"time,omitempty"`
	Triggers []Trigger     `json:"triggers,omitempty"`
}

Action -

type Client

type Client struct {
	Config `json:"config"`
}

Client - Designed to be as connection point between code and Sift Science API

func (*Client) GetEventsUrl

func (c *Client) GetEventsUrl() string

GetEventsUrl - Returning full url to sift science events API

func (*Client) GetLabelUrl

func (c *Client) GetLabelUrl(userId string) string

GetScoreUrl - Returning full url to sift science label API

func (*Client) GetScoreUrl

func (c *Client) GetScoreUrl(userId string) string

GetScoreUrl - Returning full url to sift science score API

func (*Client) HttpRequest

func (c *Client) HttpRequest(method string, url string, params map[string]interface{}) (*Response, error)

HttpRequest - Doing HTTP requests towards sift science API Should be used only if there's no other choice. There are helper methods defined in sift.go for tracking, labeling, etc...

func (*Client) SetApiKey

func (c *Client) SetApiKey(key string)

SetApiKey - Set Sift API key. You can find your keys at https://siftscience.com/console/developer/api-keys Pay closer attention to Production/Sandbox Mode as keys are different.

func (*Client) SetApiUrl

func (c *Client) SetApiUrl(url string)

SetApiUrl - Set Sift API Url. Should not be modified unless you know what you're doing. Default API Url can be seen in constants.go

func (*Client) SetApiVersion

func (c *Client) SetApiVersion(version int)

SetApiVersion - Set Sift API version. Default API Url can be seen in constants.go

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration)

SetTimeout - Set new API request timeout. Default API Timeout can be seen in constants.go

func (*Client) UserAgent

func (c *Client) UserAgent() string

UserAgent - Returns User Agent that will be used with request towards Sift Science

type Config

type Config struct {
	ApiUrl     string        `json:"api_url"`
	ApiVersion int           `json:"api_version"`
	ApiKey     string        `json:"api_key"`
	Timeout    time.Duration `json:"timeout"`
}

Config - Configuration struct used once per Sift Environment

type Label

type Label struct {
	IsBad       bool          `json:"is_bad,omitempty"`
	Time        time.Duration `json:"time,omitempty"`
	Reasons     []string      `json:"reasons,omitempty"`
	Description string        `json:"description,omitempty"`
}

Label -

type Reason

type Reason struct {
	Name    string `json:"name,omitempty"`
	Value   string `json:"value,omitempty"`
	Details struct {
		Users string `json:"users,omitempty"`
	} `json:"details,omitempty"`
}

Reason -

type Response

type Response struct {
	// Used for debugging purposes I guess....
	HTTPStatus       string      `json:"-"`
	HTTPStatusCode   int         `json:"-"`
	HTTPStatusHeader http.Header `json:"-"`
	HTTPResponseBody string      `json:"-"`

	Status       int           `json:"status,omitempty"`
	UserID       string        `json:"user_id,omitempty"`
	ErrorMessage string        `json:"error_message,omitempty"`
	Time         time.Duration `json:"time,omitempty"`
	Score        float64       `json:"score,omitempty"`
	Request      string        `json:"request,omitempty"`
	Actions      []Action      `json:"actions,omitempty"`
	LatestLabel  Label         `json:"latest_label,omitempty"`
	Reasons      []Reason      `json:"reasons,omitempty"`
}

Response -

func (*Response) IsOK

func (r *Response) IsOK() bool

IsOK - Check status of response. Is it error'ed or succeed?

type Sift

type Sift struct {
	Client
}

func New

func New(apiKey string) *Sift

New - Return Sift API client.

func NewFromJSON

func NewFromJSON(config []byte) (*Sift, error)

NewFromJSON - Decode JSON file into new Sift client.

func (*Sift) Label

func (s *Sift) Label(userID string, params map[string]interface{}) (*Response, error)

Label - Request labeling for specific user

func (*Sift) Score

func (s *Sift) Score(userID string) (*Response, error)

Score - Get out user score

func (*Sift) Track

func (s *Sift) Track(event string, params map[string]interface{}, args map[string]interface{}) (*Response, error)

Track - Send tracking event towards sift science

func (*Sift) UnLabel

func (s *Sift) UnLabel(userID string) (*Response, error)

UnLabel - Request unlabeling for specific user

type Trigger

type Trigger struct {
	Type    string `json:"type,omitempty"`
	Source  string `json:"source,omitempty"`
	Trigger struct {
		ID string `json:"id,omitempty"`
	} `json:"trigger,omitempty"`
}

Trigger -

Jump to

Keyboard shortcuts

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