heroku db

This commit is contained in:
Ruidy Nemausat 2020-03-20 00:19:27 +01:00
parent 5f3ff97661
commit 92005bf2ae
129 changed files with 22655 additions and 2 deletions

3
.env
View file

@ -1,3 +1,4 @@
PORT=8080
TMPLDIR=views/templates/
ConnectionString=user=nemausat dbname=godb sslmode=disable
ConnectionString=user=nemausat dbname=godb sslmode=disable
DATABASE_URL=postgres://oshiervtwfrqrr:f177bc7ff355c142931aeb3f39ca7a6cc1b9e37594892f0e64d152b7a6f76657@ec2-50-17-178-87.compute-1.amazonaws.com:5432/ddidqb9rq8ta6m

View file

@ -3,6 +3,7 @@ package main
import (
"log"
"net/http"
"os"
"github.com/rjNemo/go-wiki/controllers"
"github.com/rjNemo/go-wiki/data"
@ -13,7 +14,8 @@ func main() {
log.Println("*** Go-wiki v0.1 ©2020 ***")
// connect to db
db, err := data.NewDB(settings.ConnStr)
// db, err := data.NewDB(settings.ConnStr)
db, err := data.NewDB(os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}

8
vendor/github.com/joho/godotenv/.travis.yml generated vendored Normal file
View file

@ -0,0 +1,8 @@
language: go
go:
- 1.x
os:
- linux
- osx

23
vendor/github.com/joho/godotenv/LICENCE generated vendored Normal file
View file

@ -0,0 +1,23 @@
Copyright (c) 2013 John Barton
MIT License
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.

163
vendor/github.com/joho/godotenv/README.md generated vendored Normal file
View file

@ -0,0 +1,163 @@
# GoDotEnv [![Build Status](https://travis-ci.org/joho/godotenv.svg?branch=master)](https://travis-ci.org/joho/godotenv) [![Build status](https://ci.appveyor.com/api/projects/status/9v40vnfvvgde64u4?svg=true)](https://ci.appveyor.com/project/joho/godotenv) [![Go Report Card](https://goreportcard.com/badge/github.com/joho/godotenv)](https://goreportcard.com/report/github.com/joho/godotenv)
A Go (golang) port of the Ruby dotenv project (which loads env vars from a .env file)
From the original Library:
> Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environmentssuch as resource handles for databases or credentials for external servicesshould be extracted from the code into environment variables.
>
> But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. Dotenv load variables from a .env file into ENV when the environment is bootstrapped.
It can be used as a library (for loading in env for your own daemons etc) or as a bin command.
There is test coverage and CI for both linuxish and windows environments, but I make no guarantees about the bin version working on windows.
## Installation
As a library
```shell
go get github.com/joho/godotenv
```
or if you want to use it as a bin command
```shell
go get github.com/joho/godotenv/cmd/godotenv
```
## Usage
Add your application configuration to your `.env` file in the root of your project:
```shell
S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE
```
Then in your Go app you can do something like
```go
package main
import (
"github.com/joho/godotenv"
"log"
"os"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
s3Bucket := os.Getenv("S3_BUCKET")
secretKey := os.Getenv("SECRET_KEY")
// now do something with s3 or whatever
}
```
If you're even lazier than that, you can just take advantage of the autoload package which will read in `.env` on import
```go
import _ "github.com/joho/godotenv/autoload"
```
While `.env` in the project root is the default, you don't have to be constrained, both examples below are 100% legit
```go
_ = godotenv.Load("somerandomfile")
_ = godotenv.Load("filenumberone.env", "filenumbertwo.env")
```
If you want to be really fancy with your env file you can do comments and exports (below is a valid env file)
```shell
# I am a comment and that is OK
SOME_VAR=someval
FOO=BAR # comments at line end are OK too
export BAR=BAZ
```
Or finally you can do YAML(ish) style
```yaml
FOO: bar
BAR: baz
```
as a final aside, if you don't want godotenv munging your env you can just get a map back instead
```go
var myEnv map[string]string
myEnv, err := godotenv.Read()
s3Bucket := myEnv["S3_BUCKET"]
```
... or from an `io.Reader` instead of a local file
```go
reader := getRemoteFile()
myEnv, err := godotenv.Parse(reader)
```
... or from a `string` if you so desire
```go
content := getRemoteFileContent()
myEnv, err := godotenv.Unmarshal(content)
```
### Command Mode
Assuming you've installed the command as above and you've got `$GOPATH/bin` in your `$PATH`
```
godotenv -f /some/path/to/.env some_command with some args
```
If you don't specify `-f` it will fall back on the default of loading `.env` in `PWD`
### Writing Env Files
Godotenv can also write a map representing the environment to a correctly-formatted and escaped file
```go
env, err := godotenv.Unmarshal("KEY=value")
err := godotenv.Write(env, "./.env")
```
... or to a string
```go
env, err := godotenv.Unmarshal("KEY=value")
content, err := godotenv.Marshal(env)
```
## Contributing
Contributions are most welcome! The parser itself is pretty stupidly naive and I wouldn't be surprised if it breaks with edge cases.
*code changes without tests will not be accepted*
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
## Releases
Releases should follow [Semver](http://semver.org/) though the first couple of releases are `v1` and `v1.1`.
Use [annotated tags for all releases](https://github.com/joho/godotenv/issues/30). Example `git tag -a v1.2.1`
## CI
Linux: [![Build Status](https://travis-ci.org/joho/godotenv.svg?branch=master)](https://travis-ci.org/joho/godotenv) Windows: [![Build status](https://ci.appveyor.com/api/projects/status/9v40vnfvvgde64u4)](https://ci.appveyor.com/project/joho/godotenv)
## Who?
The original library [dotenv](https://github.com/bkeepers/dotenv) was written by [Brandon Keepers](http://opensoul.org/), and this port was done by [John Barton](https://johnbarton.co/) based off the tests/fixtures in the original library.

346
vendor/github.com/joho/godotenv/godotenv.go generated vendored Normal file
View file

@ -0,0 +1,346 @@
// Package godotenv is a go port of the ruby dotenv library (https://github.com/bkeepers/dotenv)
//
// Examples/readme can be found on the github page at https://github.com/joho/godotenv
//
// The TL;DR is that you make a .env file that looks something like
//
// SOME_ENV_VAR=somevalue
//
// and then in your go code you can call
//
// godotenv.Load()
//
// and all the env vars declared in .env will be available through os.Getenv("SOME_ENV_VAR")
package godotenv
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"sort"
"strings"
)
const doubleQuoteSpecialChars = "\\\n\r\"!$`"
// Load will read your env file(s) and load them into ENV for this process.
//
// Call this function as close as possible to the start of your program (ideally in main)
//
// If you call Load without any args it will default to loading .env in the current path
//
// You can otherwise tell it which files to load (there can be more than one) like
//
// godotenv.Load("fileone", "filetwo")
//
// It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults
func Load(filenames ...string) (err error) {
filenames = filenamesOrDefault(filenames)
for _, filename := range filenames {
err = loadFile(filename, false)
if err != nil {
return // return early on a spazout
}
}
return
}
// Overload will read your env file(s) and load them into ENV for this process.
//
// Call this function as close as possible to the start of your program (ideally in main)
//
// If you call Overload without any args it will default to loading .env in the current path
//
// You can otherwise tell it which files to load (there can be more than one) like
//
// godotenv.Overload("fileone", "filetwo")
//
// It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefilly set all vars.
func Overload(filenames ...string) (err error) {
filenames = filenamesOrDefault(filenames)
for _, filename := range filenames {
err = loadFile(filename, true)
if err != nil {
return // return early on a spazout
}
}
return
}
// Read all env (with same file loading semantics as Load) but return values as
// a map rather than automatically writing values into env
func Read(filenames ...string) (envMap map[string]string, err error) {
filenames = filenamesOrDefault(filenames)
envMap = make(map[string]string)
for _, filename := range filenames {
individualEnvMap, individualErr := readFile(filename)
if individualErr != nil {
err = individualErr
return // return early on a spazout
}
for key, value := range individualEnvMap {
envMap[key] = value
}
}
return
}
// Parse reads an env file from io.Reader, returning a map of keys and values.
func Parse(r io.Reader) (envMap map[string]string, err error) {
envMap = make(map[string]string)
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err = scanner.Err(); err != nil {
return
}
for _, fullLine := range lines {
if !isIgnoredLine(fullLine) {
var key, value string
key, value, err = parseLine(fullLine, envMap)
if err != nil {
return
}
envMap[key] = value
}
}
return
}
//Unmarshal reads an env file from a string, returning a map of keys and values.
func Unmarshal(str string) (envMap map[string]string, err error) {
return Parse(strings.NewReader(str))
}
// Exec loads env vars from the specified filenames (empty map falls back to default)
// then executes the cmd specified.
//
// Simply hooks up os.Stdin/err/out to the command and calls Run()
//
// If you want more fine grained control over your command it's recommended
// that you use `Load()` or `Read()` and the `os/exec` package yourself.
func Exec(filenames []string, cmd string, cmdArgs []string) error {
Load(filenames...)
command := exec.Command(cmd, cmdArgs...)
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
return command.Run()
}
// Write serializes the given environment and writes it to a file
func Write(envMap map[string]string, filename string) error {
content, error := Marshal(envMap)
if error != nil {
return error
}
file, error := os.Create(filename)
if error != nil {
return error
}
_, err := file.WriteString(content)
return err
}
// Marshal outputs the given environment as a dotenv-formatted environment file.
// Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped.
func Marshal(envMap map[string]string) (string, error) {
lines := make([]string, 0, len(envMap))
for k, v := range envMap {
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
}
sort.Strings(lines)
return strings.Join(lines, "\n"), nil
}
func filenamesOrDefault(filenames []string) []string {
if len(filenames) == 0 {
return []string{".env"}
}
return filenames
}
func loadFile(filename string, overload bool) error {
envMap, err := readFile(filename)
if err != nil {
return err
}
currentEnv := map[string]bool{}
rawEnv := os.Environ()
for _, rawEnvLine := range rawEnv {
key := strings.Split(rawEnvLine, "=")[0]
currentEnv[key] = true
}
for key, value := range envMap {
if !currentEnv[key] || overload {
os.Setenv(key, value)
}
}
return nil
}
func readFile(filename string) (envMap map[string]string, err error) {
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close()
return Parse(file)
}
func parseLine(line string, envMap map[string]string) (key string, value string, err error) {
if len(line) == 0 {
err = errors.New("zero length string")
return
}
// ditch the comments (but keep quoted hashes)
if strings.Contains(line, "#") {
segmentsBetweenHashes := strings.Split(line, "#")
quotesAreOpen := false
var segmentsToKeep []string
for _, segment := range segmentsBetweenHashes {
if strings.Count(segment, "\"") == 1 || strings.Count(segment, "'") == 1 {
if quotesAreOpen {
quotesAreOpen = false
segmentsToKeep = append(segmentsToKeep, segment)
} else {
quotesAreOpen = true
}
}
if len(segmentsToKeep) == 0 || quotesAreOpen {
segmentsToKeep = append(segmentsToKeep, segment)
}
}
line = strings.Join(segmentsToKeep, "#")
}
firstEquals := strings.Index(line, "=")
firstColon := strings.Index(line, ":")
splitString := strings.SplitN(line, "=", 2)
if firstColon != -1 && (firstColon < firstEquals || firstEquals == -1) {
//this is a yaml-style line
splitString = strings.SplitN(line, ":", 2)
}
if len(splitString) != 2 {
err = errors.New("Can't separate key from value")
return
}
// Parse the key
key = splitString[0]
if strings.HasPrefix(key, "export") {
key = strings.TrimPrefix(key, "export")
}
key = strings.Trim(key, " ")
// Parse the value
value = parseValue(splitString[1], envMap)
return
}
func parseValue(value string, envMap map[string]string) string {
// trim
value = strings.Trim(value, " ")
// check if we've got quoted values or possible escapes
if len(value) > 1 {
rs := regexp.MustCompile(`\A'(.*)'\z`)
singleQuotes := rs.FindStringSubmatch(value)
rd := regexp.MustCompile(`\A"(.*)"\z`)
doubleQuotes := rd.FindStringSubmatch(value)
if singleQuotes != nil || doubleQuotes != nil {
// pull the quotes off the edges
value = value[1 : len(value)-1]
}
if doubleQuotes != nil {
// expand newlines
escapeRegex := regexp.MustCompile(`\\.`)
value = escapeRegex.ReplaceAllStringFunc(value, func(match string) string {
c := strings.TrimPrefix(match, `\`)
switch c {
case "n":
return "\n"
case "r":
return "\r"
default:
return match
}
})
// unescape characters
e := regexp.MustCompile(`\\([^$])`)
value = e.ReplaceAllString(value, "$1")
}
if singleQuotes == nil {
value = expandVariables(value, envMap)
}
}
return value
}
func expandVariables(v string, m map[string]string) string {
r := regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Z0-9_]+)?\}?`)
return r.ReplaceAllStringFunc(v, func(s string) string {
submatch := r.FindStringSubmatch(s)
if submatch == nil {
return s
}
if submatch[1] == "\\" || submatch[2] == "(" {
return submatch[0][1:]
} else if submatch[4] != "" {
return m[submatch[4]]
}
return s
})
}
func isIgnoredLine(line string) bool {
trimmedLine := strings.Trim(line, " \n\t")
return len(trimmedLine) == 0 || strings.HasPrefix(trimmedLine, "#")
}
func doubleQuoteEscape(line string) string {
for _, c := range doubleQuoteSpecialChars {
toReplace := "\\" + string(c)
if c == '\n' {
toReplace = `\n`
}
if c == '\r' {
toReplace = `\r`
}
line = strings.Replace(line, string(c), toReplace, -1)
}
return line
}

73
vendor/github.com/lib/pq/.travis.sh generated vendored Normal file
View file

@ -0,0 +1,73 @@
#!/bin/bash
set -eu
client_configure() {
sudo chmod 600 $PQSSLCERTTEST_PATH/postgresql.key
}
pgdg_repository() {
local sourcelist='sources.list.d/postgresql.list'
curl -sS 'https://www.postgresql.org/media/keys/ACCC4CF8.asc' | sudo apt-key add -
echo deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main $PGVERSION | sudo tee "/etc/apt/$sourcelist"
sudo apt-get -o Dir::Etc::sourcelist="$sourcelist" -o Dir::Etc::sourceparts='-' -o APT::Get::List-Cleanup='0' update
}
postgresql_configure() {
sudo tee /etc/postgresql/$PGVERSION/main/pg_hba.conf > /dev/null <<-config
local all all trust
hostnossl all pqgossltest 127.0.0.1/32 reject
hostnossl all pqgosslcert 127.0.0.1/32 reject
hostssl all pqgossltest 127.0.0.1/32 trust
hostssl all pqgosslcert 127.0.0.1/32 cert
host all all 127.0.0.1/32 trust
hostnossl all pqgossltest ::1/128 reject
hostnossl all pqgosslcert ::1/128 reject
hostssl all pqgossltest ::1/128 trust
hostssl all pqgosslcert ::1/128 cert
host all all ::1/128 trust
config
xargs sudo install -o postgres -g postgres -m 600 -t /var/lib/postgresql/$PGVERSION/main/ <<-certificates
certs/root.crt
certs/server.crt
certs/server.key
certificates
sort -VCu <<-versions ||
$PGVERSION
9.2
versions
sudo tee -a /etc/postgresql/$PGVERSION/main/postgresql.conf > /dev/null <<-config
ssl_ca_file = 'root.crt'
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
config
echo 127.0.0.1 postgres | sudo tee -a /etc/hosts > /dev/null
sudo service postgresql restart
}
postgresql_install() {
xargs sudo apt-get -y -o Dpkg::Options::='--force-confdef' -o Dpkg::Options::='--force-confnew' install <<-packages
postgresql-$PGVERSION
postgresql-server-dev-$PGVERSION
postgresql-contrib-$PGVERSION
packages
}
postgresql_uninstall() {
sudo service postgresql stop
xargs sudo apt-get -y --purge remove <<-packages
libpq-dev
libpq5
postgresql
postgresql-client-common
postgresql-common
packages
sudo rm -rf /var/lib/postgresql
}
$1

44
vendor/github.com/lib/pq/.travis.yml generated vendored Normal file
View file

@ -0,0 +1,44 @@
language: go
go:
- 1.11.x
- 1.12.x
- master
sudo: true
env:
global:
- PGUSER=postgres
- PQGOSSLTESTS=1
- PQSSLCERTTEST_PATH=$PWD/certs
- PGHOST=127.0.0.1
matrix:
- PGVERSION=10
- PGVERSION=9.6
- PGVERSION=9.5
- PGVERSION=9.4
before_install:
- ./.travis.sh postgresql_uninstall
- ./.travis.sh pgdg_repository
- ./.travis.sh postgresql_install
- ./.travis.sh postgresql_configure
- ./.travis.sh client_configure
- go get golang.org/x/tools/cmd/goimports
- go get golang.org/x/lint/golint
- GO111MODULE=on go get honnef.co/go/tools/cmd/staticcheck@2019.2.1
before_script:
- createdb pqgotest
- createuser -DRS pqgossltest
- createuser -DRS pqgosslcert
script:
- >
goimports -d -e $(find -name '*.go') | awk '{ print } END { exit NR == 0 ? 0 : 1 }'
- go vet ./...
- staticcheck -go 1.11 ./...
- golint ./...
- PQTEST_BINARY_PARAMETERS=no go test -race -v ./...
- PQTEST_BINARY_PARAMETERS=yes go test -race -v ./...

29
vendor/github.com/lib/pq/CONTRIBUTING.md generated vendored Normal file
View file

@ -0,0 +1,29 @@
## Contributing to pq
`pq` has a backlog of pull requests, but contributions are still very
much welcome. You can help with patch review, submitting bug reports,
or adding new functionality. There is no formal style guide, but
please conform to the style of existing code and general Go formatting
conventions when submitting patches.
### Patch review
Help review existing open pull requests by commenting on the code or
proposed functionality.
### Bug reports
We appreciate any bug reports, but especially ones with self-contained
(doesn't depend on code outside of pq), minimal (can't be simplified
further) test cases. It's especially helpful if you can submit a pull
request with just the failing test case (you'll probably want to
pattern it after the tests in
[conn_test.go](https://github.com/lib/pq/blob/master/conn_test.go).
### New functionality
There are a number of pending patches for new functionality, so
additional feature patches will take a while to merge. Still, patches
are generally reviewed based on usefulness and complexity in addition
to time-in-queue, so if you have a knockout idea, take a shot. Feel
free to open an issue discussion your proposed patch beforehand.

8
vendor/github.com/lib/pq/LICENSE.md generated vendored Normal file
View file

@ -0,0 +1,8 @@
Copyright (c) 2011-2013, 'pq' Contributors
Portions Copyright (C) 2011 Blake Mizerany
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.

95
vendor/github.com/lib/pq/README.md generated vendored Normal file
View file

@ -0,0 +1,95 @@
# pq - A pure Go postgres driver for Go's database/sql package
[![GoDoc](https://godoc.org/github.com/lib/pq?status.svg)](https://godoc.org/github.com/lib/pq)
[![Build Status](https://travis-ci.org/lib/pq.svg?branch=master)](https://travis-ci.org/lib/pq)
## Install
go get github.com/lib/pq
## Docs
For detailed documentation and basic usage examples, please see the package
documentation at <https://godoc.org/github.com/lib/pq>.
## Tests
`go test` is used for testing. See [TESTS.md](TESTS.md) for more details.
## Features
* SSL
* Handles bad connections for `database/sql`
* Scan `time.Time` correctly (i.e. `timestamp[tz]`, `time[tz]`, `date`)
* Scan binary blobs correctly (i.e. `bytea`)
* Package for `hstore` support
* COPY FROM support
* pq.ParseURL for converting urls to connection strings for sql.Open.
* Many libpq compatible environment variables
* Unix socket support
* Notifications: `LISTEN`/`NOTIFY`
* pgpass support
## Future / Things you can help with
* Better COPY FROM / COPY TO (see discussion in #181)
## Thank you (alphabetical)
Some of these contributors are from the original library `bmizerany/pq.go` whose
code still exists in here.
* Andy Balholm (andybalholm)
* Ben Berkert (benburkert)
* Benjamin Heatwole (bheatwole)
* Bill Mill (llimllib)
* Bjørn Madsen (aeons)
* Blake Gentry (bgentry)
* Brad Fitzpatrick (bradfitz)
* Charlie Melbye (cmelbye)
* Chris Bandy (cbandy)
* Chris Gilling (cgilling)
* Chris Walsh (cwds)
* Dan Sosedoff (sosedoff)
* Daniel Farina (fdr)
* Eric Chlebek (echlebek)
* Eric Garrido (minusnine)
* Eric Urban (hydrogen18)
* Everyone at The Go Team
* Evan Shaw (edsrzf)
* Ewan Chou (coocood)
* Fazal Majid (fazalmajid)
* Federico Romero (federomero)
* Fumin (fumin)
* Gary Burd (garyburd)
* Heroku (heroku)
* James Pozdena (jpoz)
* Jason McVetta (jmcvetta)
* Jeremy Jay (pbnjay)
* Joakim Sernbrant (serbaut)
* John Gallagher (jgallagher)
* Jonathan Rudenberg (titanous)
* Joël Stemmer (jstemmer)
* Kamil Kisiel (kisielk)
* Kelly Dunn (kellydunn)
* Keith Rarick (kr)
* Kir Shatrov (kirs)
* Lann Martin (lann)
* Maciek Sakrejda (uhoh-itsmaciek)
* Marc Brinkmann (mbr)
* Marko Tiikkaja (johto)
* Matt Newberry (MattNewberry)
* Matt Robenolt (mattrobenolt)
* Martin Olsen (martinolsen)
* Mike Lewis (mikelikespie)
* Nicolas Patry (Narsil)
* Oliver Tonnhofer (olt)
* Patrick Hayes (phayes)
* Paul Hammond (paulhammond)
* Ryan Smith (ryandotsmith)
* Samuel Stauffer (samuel)
* Timothée Peignier (cyberdelia)
* Travis Cline (tmc)
* TruongSinh Tran-Nguyen (truongsinh)
* Yaismel Miranda (ympons)
* notedit (notedit)

33
vendor/github.com/lib/pq/TESTS.md generated vendored Normal file
View file

@ -0,0 +1,33 @@
# Tests
## Running Tests
`go test` is used for testing. A running PostgreSQL
server is required, with the ability to log in. The
database to connect to test with is "pqgotest," on
"localhost" but these can be overridden using [environment
variables](https://www.postgresql.org/docs/9.3/static/libpq-envars.html).
Example:
PGHOST=/run/postgresql go test
## Benchmarks
A benchmark suite can be run as part of the tests:
go test -bench .
## Example setup (Docker)
Run a postgres container:
```
docker run --expose 5432:5432 postgres
```
Run tests:
```
PGHOST=localhost PGPORT=5432 PGUSER=postgres PGSSLMODE=disable PGDATABASE=postgres go test
```

756
vendor/github.com/lib/pq/array.go generated vendored Normal file
View file

@ -0,0 +1,756 @@
package pq
import (
"bytes"
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"reflect"
"strconv"
"strings"
)
var typeByteSlice = reflect.TypeOf([]byte{})
var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
// Array returns the optimal driver.Valuer and sql.Scanner for an array or
// slice of any dimension.
//
// For example:
// db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))
//
// var x []sql.NullInt64
// db.QueryRow('SELECT ARRAY[235, 401]').Scan(pq.Array(&x))
//
// Scanning multi-dimensional arrays is not supported. Arrays where the lower
// bound is not one (such as `[0:0]={1}') are not supported.
func Array(a interface{}) interface {
driver.Valuer
sql.Scanner
} {
switch a := a.(type) {
case []bool:
return (*BoolArray)(&a)
case []float64:
return (*Float64Array)(&a)
case []int64:
return (*Int64Array)(&a)
case []string:
return (*StringArray)(&a)
case *[]bool:
return (*BoolArray)(a)
case *[]float64:
return (*Float64Array)(a)
case *[]int64:
return (*Int64Array)(a)
case *[]string:
return (*StringArray)(a)
}
return GenericArray{a}
}
// ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner
// to override the array delimiter used by GenericArray.
type ArrayDelimiter interface {
// ArrayDelimiter returns the delimiter character(s) for this element's type.
ArrayDelimiter() string
}
// BoolArray represents a one-dimensional array of the PostgreSQL boolean type.
type BoolArray []bool
// Scan implements the sql.Scanner interface.
func (a *BoolArray) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
return a.scanBytes(src)
case string:
return a.scanBytes([]byte(src))
case nil:
*a = nil
return nil
}
return fmt.Errorf("pq: cannot convert %T to BoolArray", src)
}
func (a *BoolArray) scanBytes(src []byte) error {
elems, err := scanLinearArray(src, []byte{','}, "BoolArray")
if err != nil {
return err
}
if *a != nil && len(elems) == 0 {
*a = (*a)[:0]
} else {
b := make(BoolArray, len(elems))
for i, v := range elems {
if len(v) != 1 {
return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v)
}
switch v[0] {
case 't':
b[i] = true
case 'f':
b[i] = false
default:
return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v)
}
}
*a = b
}
return nil
}
// Value implements the driver.Valuer interface.
func (a BoolArray) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// There will be exactly two curly brackets, N bytes of values,
// and N-1 bytes of delimiters.
b := make([]byte, 1+2*n)
for i := 0; i < n; i++ {
b[2*i] = ','
if a[i] {
b[1+2*i] = 't'
} else {
b[1+2*i] = 'f'
}
}
b[0] = '{'
b[2*n] = '}'
return string(b), nil
}
return "{}", nil
}
// ByteaArray represents a one-dimensional array of the PostgreSQL bytea type.
type ByteaArray [][]byte
// Scan implements the sql.Scanner interface.
func (a *ByteaArray) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
return a.scanBytes(src)
case string:
return a.scanBytes([]byte(src))
case nil:
*a = nil
return nil
}
return fmt.Errorf("pq: cannot convert %T to ByteaArray", src)
}
func (a *ByteaArray) scanBytes(src []byte) error {
elems, err := scanLinearArray(src, []byte{','}, "ByteaArray")
if err != nil {
return err
}
if *a != nil && len(elems) == 0 {
*a = (*a)[:0]
} else {
b := make(ByteaArray, len(elems))
for i, v := range elems {
b[i], err = parseBytea(v)
if err != nil {
return fmt.Errorf("could not parse bytea array index %d: %s", i, err.Error())
}
}
*a = b
}
return nil
}
// Value implements the driver.Valuer interface. It uses the "hex" format which
// is only supported on PostgreSQL 9.0 or newer.
func (a ByteaArray) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// There will be at least two curly brackets, 2*N bytes of quotes,
// 3*N bytes of hex formatting, and N-1 bytes of delimiters.
size := 1 + 6*n
for _, x := range a {
size += hex.EncodedLen(len(x))
}
b := make([]byte, size)
for i, s := 0, b; i < n; i++ {
o := copy(s, `,"\\x`)
o += hex.Encode(s[o:], a[i])
s[o] = '"'
s = s[o+1:]
}
b[0] = '{'
b[size-1] = '}'
return string(b), nil
}
return "{}", nil
}
// Float64Array represents a one-dimensional array of the PostgreSQL double
// precision type.
type Float64Array []float64
// Scan implements the sql.Scanner interface.
func (a *Float64Array) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
return a.scanBytes(src)
case string:
return a.scanBytes([]byte(src))
case nil:
*a = nil
return nil
}
return fmt.Errorf("pq: cannot convert %T to Float64Array", src)
}
func (a *Float64Array) scanBytes(src []byte) error {
elems, err := scanLinearArray(src, []byte{','}, "Float64Array")
if err != nil {
return err
}
if *a != nil && len(elems) == 0 {
*a = (*a)[:0]
} else {
b := make(Float64Array, len(elems))
for i, v := range elems {
if b[i], err = strconv.ParseFloat(string(v), 64); err != nil {
return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
}
}
*a = b
}
return nil
}
// Value implements the driver.Valuer interface.
func (a Float64Array) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// There will be at least two curly brackets, N bytes of values,
// and N-1 bytes of delimiters.
b := make([]byte, 1, 1+2*n)
b[0] = '{'
b = strconv.AppendFloat(b, a[0], 'f', -1, 64)
for i := 1; i < n; i++ {
b = append(b, ',')
b = strconv.AppendFloat(b, a[i], 'f', -1, 64)
}
return string(append(b, '}')), nil
}
return "{}", nil
}
// GenericArray implements the driver.Valuer and sql.Scanner interfaces for
// an array or slice of any dimension.
type GenericArray struct{ A interface{} }
func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) {
var assign func([]byte, reflect.Value) error
var del = ","
// TODO calculate the assign function for other types
// TODO repeat this section on the element type of arrays or slices (multidimensional)
{
if reflect.PtrTo(rt).Implements(typeSQLScanner) {
// dest is always addressable because it is an element of a slice.
assign = func(src []byte, dest reflect.Value) (err error) {
ss := dest.Addr().Interface().(sql.Scanner)
if src == nil {
err = ss.Scan(nil)
} else {
err = ss.Scan(src)
}
return
}
goto FoundType
}
assign = func([]byte, reflect.Value) error {
return fmt.Errorf("pq: scanning to %s is not implemented; only sql.Scanner", rt)
}
}
FoundType:
if ad, ok := reflect.Zero(rt).Interface().(ArrayDelimiter); ok {
del = ad.ArrayDelimiter()
}
return rt, assign, del
}
// Scan implements the sql.Scanner interface.
func (a GenericArray) Scan(src interface{}) error {
dpv := reflect.ValueOf(a.A)
switch {
case dpv.Kind() != reflect.Ptr:
return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A)
case dpv.IsNil():
return fmt.Errorf("pq: destination %T is nil", a.A)
}
dv := dpv.Elem()
switch dv.Kind() {
case reflect.Slice:
case reflect.Array:
default:
return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A)
}
switch src := src.(type) {
case []byte:
return a.scanBytes(src, dv)
case string:
return a.scanBytes([]byte(src), dv)
case nil:
if dv.Kind() == reflect.Slice {
dv.Set(reflect.Zero(dv.Type()))
return nil
}
}
return fmt.Errorf("pq: cannot convert %T to %s", src, dv.Type())
}
func (a GenericArray) scanBytes(src []byte, dv reflect.Value) error {
dtype, assign, del := a.evaluateDestination(dv.Type().Elem())
dims, elems, err := parseArray(src, []byte(del))
if err != nil {
return err
}
// TODO allow multidimensional
if len(dims) > 1 {
return fmt.Errorf("pq: scanning from multidimensional ARRAY%s is not implemented",
strings.Replace(fmt.Sprint(dims), " ", "][", -1))
}
// Treat a zero-dimensional array like an array with a single dimension of zero.
if len(dims) == 0 {
dims = append(dims, 0)
}
for i, rt := 0, dv.Type(); i < len(dims); i, rt = i+1, rt.Elem() {
switch rt.Kind() {
case reflect.Slice:
case reflect.Array:
if rt.Len() != dims[i] {
return fmt.Errorf("pq: cannot convert ARRAY%s to %s",
strings.Replace(fmt.Sprint(dims), " ", "][", -1), dv.Type())
}
default:
// TODO handle multidimensional
}
}
values := reflect.MakeSlice(reflect.SliceOf(dtype), len(elems), len(elems))
for i, e := range elems {
if err := assign(e, values.Index(i)); err != nil {
return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
}
}
// TODO handle multidimensional
switch dv.Kind() {
case reflect.Slice:
dv.Set(values.Slice(0, dims[0]))
case reflect.Array:
for i := 0; i < dims[0]; i++ {
dv.Index(i).Set(values.Index(i))
}
}
return nil
}
// Value implements the driver.Valuer interface.
func (a GenericArray) Value() (driver.Value, error) {
if a.A == nil {
return nil, nil
}
rv := reflect.ValueOf(a.A)
switch rv.Kind() {
case reflect.Slice:
if rv.IsNil() {
return nil, nil
}
case reflect.Array:
default:
return nil, fmt.Errorf("pq: Unable to convert %T to array", a.A)
}
if n := rv.Len(); n > 0 {
// There will be at least two curly brackets, N bytes of values,
// and N-1 bytes of delimiters.
b := make([]byte, 0, 1+2*n)
b, _, err := appendArray(b, rv, n)
return string(b), err
}
return "{}", nil
}
// Int64Array represents a one-dimensional array of the PostgreSQL integer types.
type Int64Array []int64
// Scan implements the sql.Scanner interface.
func (a *Int64Array) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
return a.scanBytes(src)
case string:
return a.scanBytes([]byte(src))
case nil:
*a = nil
return nil
}
return fmt.Errorf("pq: cannot convert %T to Int64Array", src)
}
func (a *Int64Array) scanBytes(src []byte) error {
elems, err := scanLinearArray(src, []byte{','}, "Int64Array")
if err != nil {
return err
}
if *a != nil && len(elems) == 0 {
*a = (*a)[:0]
} else {
b := make(Int64Array, len(elems))
for i, v := range elems {
if b[i], err = strconv.ParseInt(string(v), 10, 64); err != nil {
return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
}
}
*a = b
}
return nil
}
// Value implements the driver.Valuer interface.
func (a Int64Array) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// There will be at least two curly brackets, N bytes of values,
// and N-1 bytes of delimiters.
b := make([]byte, 1, 1+2*n)
b[0] = '{'
b = strconv.AppendInt(b, a[0], 10)
for i := 1; i < n; i++ {
b = append(b, ',')
b = strconv.AppendInt(b, a[i], 10)
}
return string(append(b, '}')), nil
}
return "{}", nil
}
// StringArray represents a one-dimensional array of the PostgreSQL character types.
type StringArray []string
// Scan implements the sql.Scanner interface.
func (a *StringArray) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
return a.scanBytes(src)
case string:
return a.scanBytes([]byte(src))
case nil:
*a = nil
return nil
}
return fmt.Errorf("pq: cannot convert %T to StringArray", src)
}
func (a *StringArray) scanBytes(src []byte) error {
elems, err := scanLinearArray(src, []byte{','}, "StringArray")
if err != nil {
return err
}
if *a != nil && len(elems) == 0 {
*a = (*a)[:0]
} else {
b := make(StringArray, len(elems))
for i, v := range elems {
if b[i] = string(v); v == nil {
return fmt.Errorf("pq: parsing array element index %d: cannot convert nil to string", i)
}
}
*a = b
}
return nil
}
// Value implements the driver.Valuer interface.
func (a StringArray) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// There will be at least two curly brackets, 2*N bytes of quotes,
// and N-1 bytes of delimiters.
b := make([]byte, 1, 1+3*n)
b[0] = '{'
b = appendArrayQuotedBytes(b, []byte(a[0]))
for i := 1; i < n; i++ {
b = append(b, ',')
b = appendArrayQuotedBytes(b, []byte(a[i]))
}
return string(append(b, '}')), nil
}
return "{}", nil
}
// appendArray appends rv to the buffer, returning the extended buffer and
// the delimiter used between elements.
//
// It panics when n <= 0 or rv's Kind is not reflect.Array nor reflect.Slice.
func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) {
var del string
var err error
b = append(b, '{')
if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil {
return b, del, err
}
for i := 1; i < n; i++ {
b = append(b, del...)
if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil {
return b, del, err
}
}
return append(b, '}'), del, nil
}
// appendArrayElement appends rv to the buffer, returning the extended buffer
// and the delimiter to use before the next element.
//
// When rv's Kind is neither reflect.Array nor reflect.Slice, it is converted
// using driver.DefaultParameterConverter and the resulting []byte or string
// is double-quoted.
//
// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO
func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) {
if k := rv.Kind(); k == reflect.Array || k == reflect.Slice {
if t := rv.Type(); t != typeByteSlice && !t.Implements(typeDriverValuer) {
if n := rv.Len(); n > 0 {
return appendArray(b, rv, n)
}
return b, "", nil
}
}
var del = ","
var err error
var iv interface{} = rv.Interface()
if ad, ok := iv.(ArrayDelimiter); ok {
del = ad.ArrayDelimiter()
}
if iv, err = driver.DefaultParameterConverter.ConvertValue(iv); err != nil {
return b, del, err
}
switch v := iv.(type) {
case nil:
return append(b, "NULL"...), del, nil
case []byte:
return appendArrayQuotedBytes(b, v), del, nil
case string:
return appendArrayQuotedBytes(b, []byte(v)), del, nil
}
b, err = appendValue(b, iv)
return b, del, err
}
func appendArrayQuotedBytes(b, v []byte) []byte {
b = append(b, '"')
for {
i := bytes.IndexAny(v, `"\`)
if i < 0 {
b = append(b, v...)
break
}
if i > 0 {
b = append(b, v[:i]...)
}
b = append(b, '\\', v[i])
v = v[i+1:]
}
return append(b, '"')
}
func appendValue(b []byte, v driver.Value) ([]byte, error) {
return append(b, encode(nil, v, 0)...), nil
}
// parseArray extracts the dimensions and elements of an array represented in
// text format. Only representations emitted by the backend are supported.
// Notably, whitespace around brackets and delimiters is significant, and NULL
// is case-sensitive.
//
// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO
func parseArray(src, del []byte) (dims []int, elems [][]byte, err error) {
var depth, i int
if len(src) < 1 || src[0] != '{' {
return nil, nil, fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '{', 0)
}
Open:
for i < len(src) {
switch src[i] {
case '{':
depth++
i++
case '}':
elems = make([][]byte, 0)
goto Close
default:
break Open
}
}
dims = make([]int, i)
Element:
for i < len(src) {
switch src[i] {
case '{':
if depth == len(dims) {
break Element
}
depth++
dims[depth-1] = 0
i++
case '"':
var elem = []byte{}
var escape bool
for i++; i < len(src); i++ {
if escape {
elem = append(elem, src[i])
escape = false
} else {
switch src[i] {
default:
elem = append(elem, src[i])
case '\\':
escape = true
case '"':
elems = append(elems, elem)
i++
break Element
}
}
}
default:
for start := i; i < len(src); i++ {
if bytes.HasPrefix(src[i:], del) || src[i] == '}' {
elem := src[start:i]
if len(elem) == 0 {
return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i)
}
if bytes.Equal(elem, []byte("NULL")) {
elem = nil
}
elems = append(elems, elem)
break Element
}
}
}
}
for i < len(src) {
if bytes.HasPrefix(src[i:], del) && depth > 0 {
dims[depth-1]++
i += len(del)
goto Element
} else if src[i] == '}' && depth > 0 {
dims[depth-1]++
depth--
i++
} else {
return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i)
}
}
Close:
for i < len(src) {
if src[i] == '}' && depth > 0 {
depth--
i++
} else {
return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i)
}
}
if depth > 0 {
err = fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '}', i)
}
if err == nil {
for _, d := range dims {
if (len(elems) % d) != 0 {
err = fmt.Errorf("pq: multidimensional arrays must have elements with matching dimensions")
}
}
}
return
}
func scanLinearArray(src, del []byte, typ string) (elems [][]byte, err error) {
dims, elems, err := parseArray(src, del)
if err != nil {
return nil, err
}
if len(dims) > 1 {
return nil, fmt.Errorf("pq: cannot convert ARRAY%s to %s", strings.Replace(fmt.Sprint(dims), " ", "][", -1), typ)
}
return elems, err
}

91
vendor/github.com/lib/pq/buf.go generated vendored Normal file
View file

@ -0,0 +1,91 @@
package pq
import (
"bytes"
"encoding/binary"
"github.com/lib/pq/oid"
)
type readBuf []byte
func (b *readBuf) int32() (n int) {
n = int(int32(binary.BigEndian.Uint32(*b)))
*b = (*b)[4:]
return
}
func (b *readBuf) oid() (n oid.Oid) {
n = oid.Oid(binary.BigEndian.Uint32(*b))
*b = (*b)[4:]
return
}
// N.B: this is actually an unsigned 16-bit integer, unlike int32
func (b *readBuf) int16() (n int) {
n = int(binary.BigEndian.Uint16(*b))
*b = (*b)[2:]
return
}
func (b *readBuf) string() string {
i := bytes.IndexByte(*b, 0)
if i < 0 {
errorf("invalid message format; expected string terminator")
}
s := (*b)[:i]
*b = (*b)[i+1:]
return string(s)
}
func (b *readBuf) next(n int) (v []byte) {
v = (*b)[:n]
*b = (*b)[n:]
return
}
func (b *readBuf) byte() byte {
return b.next(1)[0]
}
type writeBuf struct {
buf []byte
pos int
}
func (b *writeBuf) int32(n int) {
x := make([]byte, 4)
binary.BigEndian.PutUint32(x, uint32(n))
b.buf = append(b.buf, x...)
}
func (b *writeBuf) int16(n int) {
x := make([]byte, 2)
binary.BigEndian.PutUint16(x, uint16(n))
b.buf = append(b.buf, x...)
}
func (b *writeBuf) string(s string) {
b.buf = append(append(b.buf, s...), '\000')
}
func (b *writeBuf) byte(c byte) {
b.buf = append(b.buf, c)
}
func (b *writeBuf) bytes(v []byte) {
b.buf = append(b.buf, v...)
}
func (b *writeBuf) wrap() []byte {
p := b.buf[b.pos:]
binary.BigEndian.PutUint32(p, uint32(len(p)))
return b.buf
}
func (b *writeBuf) next(c byte) {
p := b.buf[b.pos:]
binary.BigEndian.PutUint32(p, uint32(len(p)))
b.pos = len(b.buf) + 1
b.buf = append(b.buf, c, 0, 0, 0, 0)
}

1923
vendor/github.com/lib/pq/conn.go generated vendored Normal file

File diff suppressed because it is too large Load diff

149
vendor/github.com/lib/pq/conn_go18.go generated vendored Normal file
View file

@ -0,0 +1,149 @@
package pq
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"io"
"io/ioutil"
"time"
)
// Implement the "QueryerContext" interface
func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
list := make([]driver.Value, len(args))
for i, nv := range args {
list[i] = nv.Value
}
finish := cn.watchCancel(ctx)
r, err := cn.query(query, list)
if err != nil {
if finish != nil {
finish()
}
return nil, err
}
r.finish = finish
return r, nil
}
// Implement the "ExecerContext" interface
func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
list := make([]driver.Value, len(args))
for i, nv := range args {
list[i] = nv.Value
}
if finish := cn.watchCancel(ctx); finish != nil {
defer finish()
}
return cn.Exec(query, list)
}
// Implement the "ConnBeginTx" interface
func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
var mode string
switch sql.IsolationLevel(opts.Isolation) {
case sql.LevelDefault:
// Don't touch mode: use the server's default
case sql.LevelReadUncommitted:
mode = " ISOLATION LEVEL READ UNCOMMITTED"
case sql.LevelReadCommitted:
mode = " ISOLATION LEVEL READ COMMITTED"
case sql.LevelRepeatableRead:
mode = " ISOLATION LEVEL REPEATABLE READ"
case sql.LevelSerializable:
mode = " ISOLATION LEVEL SERIALIZABLE"
default:
return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation)
}
if opts.ReadOnly {
mode += " READ ONLY"
} else {
mode += " READ WRITE"
}
tx, err := cn.begin(mode)
if err != nil {
return nil, err
}
cn.txnFinish = cn.watchCancel(ctx)
return tx, nil
}
func (cn *conn) Ping(ctx context.Context) error {
if finish := cn.watchCancel(ctx); finish != nil {
defer finish()
}
rows, err := cn.simpleQuery(";")
if err != nil {
return driver.ErrBadConn // https://golang.org/pkg/database/sql/driver/#Pinger
}
rows.Close()
return nil
}
func (cn *conn) watchCancel(ctx context.Context) func() {
if done := ctx.Done(); done != nil {
finished := make(chan struct{})
go func() {
select {
case <-done:
// At this point the function level context is canceled,
// so it must not be used for the additional network
// request to cancel the query.
// Create a new context to pass into the dial.
ctxCancel, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
_ = cn.cancel(ctxCancel)
finished <- struct{}{}
case <-finished:
}
}()
return func() {
select {
case <-finished:
case finished <- struct{}{}:
}
}
}
return nil
}
func (cn *conn) cancel(ctx context.Context) error {
c, err := dial(ctx, cn.dialer, cn.opts)
if err != nil {
return err
}
defer c.Close()
{
can := conn{
c: c,
}
err = can.ssl(cn.opts)
if err != nil {
return err
}
w := can.writeBuf(0)
w.int32(80877102) // cancel request code
w.int32(cn.processID)
w.int32(cn.secretKey)
if err := can.sendStartupPacket(w); err != nil {
return err
}
}
// Read until EOF to ensure that the server received the cancel.
{
_, err := io.Copy(ioutil.Discard, c)
return err
}
}

110
vendor/github.com/lib/pq/connector.go generated vendored Normal file
View file

@ -0,0 +1,110 @@
package pq
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"os"
"strings"
)
// Connector represents a fixed configuration for the pq driver with a given
// name. Connector satisfies the database/sql/driver Connector interface and
// can be used to create any number of DB Conn's via the database/sql OpenDB
// function.
//
// See https://golang.org/pkg/database/sql/driver/#Connector.
// See https://golang.org/pkg/database/sql/#OpenDB.
type Connector struct {
opts values
dialer Dialer
}
// Connect returns a connection to the database using the fixed configuration
// of this Connector. Context is not used.
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) {
return c.open(ctx)
}
// Driver returnst the underlying driver of this Connector.
func (c *Connector) Driver() driver.Driver {
return &Driver{}
}
// NewConnector returns a connector for the pq driver in a fixed configuration
// with the given dsn. The returned connector can be used to create any number
// of equivalent Conn's. The returned connector is intended to be used with
// database/sql.OpenDB.
//
// See https://golang.org/pkg/database/sql/driver/#Connector.
// See https://golang.org/pkg/database/sql/#OpenDB.
func NewConnector(dsn string) (*Connector, error) {
var err error
o := make(values)
// A number of defaults are applied here, in this order:
//
// * Very low precedence defaults applied in every situation
// * Environment variables
// * Explicitly passed connection information
o["host"] = "localhost"
o["port"] = "5432"
// N.B.: Extra float digits should be set to 3, but that breaks
// Postgres 8.4 and older, where the max is 2.
o["extra_float_digits"] = "2"
for k, v := range parseEnviron(os.Environ()) {
o[k] = v
}
if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
dsn, err = ParseURL(dsn)
if err != nil {
return nil, err
}
}
if err := parseOpts(dsn, o); err != nil {
return nil, err
}
// Use the "fallback" application name if necessary
if fallback, ok := o["fallback_application_name"]; ok {
if _, ok := o["application_name"]; !ok {
o["application_name"] = fallback
}
}
// We can't work with any client_encoding other than UTF-8 currently.
// However, we have historically allowed the user to set it to UTF-8
// explicitly, and there's no reason to break such programs, so allow that.
// Note that the "options" setting could also set client_encoding, but
// parsing its value is not worth it. Instead, we always explicitly send
// client_encoding as a separate run-time parameter, which should override
// anything set in options.
if enc, ok := o["client_encoding"]; ok && !isUTF8(enc) {
return nil, errors.New("client_encoding must be absent or 'UTF8'")
}
o["client_encoding"] = "UTF8"
// DateStyle needs a similar treatment.
if datestyle, ok := o["datestyle"]; ok {
if datestyle != "ISO, MDY" {
return nil, fmt.Errorf("setting datestyle must be absent or %v; got %v", "ISO, MDY", datestyle)
}
} else {
o["datestyle"] = "ISO, MDY"
}
// If a user is not provided by any other means, the last
// resort is to use the current operating system provided user
// name.
if _, ok := o["user"]; !ok {
u, err := userCurrent()
if err != nil {
return nil, err
}
o["user"] = u
}
return &Connector{opts: o, dialer: defaultDialer{}}, nil
}

282
vendor/github.com/lib/pq/copy.go generated vendored Normal file
View file

@ -0,0 +1,282 @@
package pq
import (
"database/sql/driver"
"encoding/binary"
"errors"
"fmt"
"sync"
)
var (
errCopyInClosed = errors.New("pq: copyin statement has already been closed")
errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY")
errCopyToNotSupported = errors.New("pq: COPY TO is not supported")
errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction")
errCopyInProgress = errors.New("pq: COPY in progress")
)
// CopyIn creates a COPY FROM statement which can be prepared with
// Tx.Prepare(). The target table should be visible in search_path.
func CopyIn(table string, columns ...string) string {
stmt := "COPY " + QuoteIdentifier(table) + " ("
for i, col := range columns {
if i != 0 {
stmt += ", "
}
stmt += QuoteIdentifier(col)
}
stmt += ") FROM STDIN"
return stmt
}
// CopyInSchema creates a COPY FROM statement which can be prepared with
// Tx.Prepare().
func CopyInSchema(schema, table string, columns ...string) string {
stmt := "COPY " + QuoteIdentifier(schema) + "." + QuoteIdentifier(table) + " ("
for i, col := range columns {
if i != 0 {
stmt += ", "
}
stmt += QuoteIdentifier(col)
}
stmt += ") FROM STDIN"
return stmt
}
type copyin struct {
cn *conn
buffer []byte
rowData chan []byte
done chan bool
closed bool
sync.Mutex // guards err
err error
}
const ciBufferSize = 64 * 1024
// flush buffer before the buffer is filled up and needs reallocation
const ciBufferFlushSize = 63 * 1024
func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, err error) {
if !cn.isInTransaction() {
return nil, errCopyNotSupportedOutsideTxn
}
ci := &copyin{
cn: cn,
buffer: make([]byte, 0, ciBufferSize),
rowData: make(chan []byte),
done: make(chan bool, 1),
}
// add CopyData identifier + 4 bytes for message length
ci.buffer = append(ci.buffer, 'd', 0, 0, 0, 0)
b := cn.writeBuf('Q')
b.string(q)
cn.send(b)
awaitCopyInResponse:
for {
t, r := cn.recv1()
switch t {
case 'G':
if r.byte() != 0 {
err = errBinaryCopyNotSupported
break awaitCopyInResponse
}
go ci.resploop()
return ci, nil
case 'H':
err = errCopyToNotSupported
break awaitCopyInResponse
case 'E':
err = parseError(r)
case 'Z':
if err == nil {
ci.setBad()
errorf("unexpected ReadyForQuery in response to COPY")
}
cn.processReadyForQuery(r)
return nil, err
default:
ci.setBad()
errorf("unknown response for copy query: %q", t)
}
}
// something went wrong, abort COPY before we return
b = cn.writeBuf('f')
b.string(err.Error())
cn.send(b)
for {
t, r := cn.recv1()
switch t {
case 'c', 'C', 'E':
case 'Z':
// correctly aborted, we're done
cn.processReadyForQuery(r)
return nil, err
default:
ci.setBad()
errorf("unknown response for CopyFail: %q", t)
}
}
}
func (ci *copyin) flush(buf []byte) {
// set message length (without message identifier)
binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1))
_, err := ci.cn.c.Write(buf)
if err != nil {
panic(err)
}
}
func (ci *copyin) resploop() {
for {
var r readBuf
t, err := ci.cn.recvMessage(&r)
if err != nil {
ci.setBad()
ci.setError(err)
ci.done <- true
return
}
switch t {
case 'C':
// complete
case 'N':
// NoticeResponse
case 'Z':
ci.cn.processReadyForQuery(&r)
ci.done <- true
return
case 'E':
err := parseError(&r)
ci.setError(err)
default:
ci.setBad()
ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t))
ci.done <- true
return
}
}
}
func (ci *copyin) setBad() {
ci.Lock()
ci.cn.bad = true
ci.Unlock()
}
func (ci *copyin) isBad() bool {
ci.Lock()
b := ci.cn.bad
ci.Unlock()
return b
}
func (ci *copyin) isErrorSet() bool {
ci.Lock()
isSet := (ci.err != nil)
ci.Unlock()
return isSet
}
// setError() sets ci.err if one has not been set already. Caller must not be
// holding ci.Mutex.
func (ci *copyin) setError(err error) {
ci.Lock()
if ci.err == nil {
ci.err = err
}
ci.Unlock()
}
func (ci *copyin) NumInput() int {
return -1
}
func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) {
return nil, ErrNotSupported
}
// Exec inserts values into the COPY stream. The insert is asynchronous
// and Exec can return errors from previous Exec calls to the same
// COPY stmt.
//
// You need to call Exec(nil) to sync the COPY stream and to get any
// errors from pending data, since Stmt.Close() doesn't return errors
// to the user.
func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) {
if ci.closed {
return nil, errCopyInClosed
}
if ci.isBad() {
return nil, driver.ErrBadConn
}
defer ci.cn.errRecover(&err)
if ci.isErrorSet() {
return nil, ci.err
}
if len(v) == 0 {
return driver.RowsAffected(0), ci.Close()
}
numValues := len(v)
for i, value := range v {
ci.buffer = appendEncodedText(&ci.cn.parameterStatus, ci.buffer, value)
if i < numValues-1 {
ci.buffer = append(ci.buffer, '\t')
}
}
ci.buffer = append(ci.buffer, '\n')
if len(ci.buffer) > ciBufferFlushSize {
ci.flush(ci.buffer)
// reset buffer, keep bytes for message identifier and length
ci.buffer = ci.buffer[:5]
}
return driver.RowsAffected(0), nil
}
func (ci *copyin) Close() (err error) {
if ci.closed { // Don't do anything, we're already closed
return nil
}
ci.closed = true
if ci.isBad() {
return driver.ErrBadConn
}
defer ci.cn.errRecover(&err)
if len(ci.buffer) > 0 {
ci.flush(ci.buffer)
}
// Avoid touching the scratch buffer as resploop could be using it.
err = ci.cn.sendSimpleMessage('c')
if err != nil {
return err
}
<-ci.done
ci.cn.inCopy = false
if ci.isErrorSet() {
err = ci.err
return err
}
return nil
}

245
vendor/github.com/lib/pq/doc.go generated vendored Normal file
View file

@ -0,0 +1,245 @@
/*
Package pq is a pure Go Postgres driver for the database/sql package.
In most cases clients will use the database/sql package instead of
using this package directly. For example:
import (
"database/sql"
_ "github.com/lib/pq"
)
func main() {
connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
age := 21
rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)
}
You can also connect to a database using a URL. For example:
connStr := "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full"
db, err := sql.Open("postgres", connStr)
Connection String Parameters
Similarly to libpq, when establishing a connection using pq you are expected to
supply a connection string containing zero or more parameters.
A subset of the connection parameters supported by libpq are also supported by pq.
Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem)
directly in the connection string. This is different from libpq, which does not allow
run-time parameters in the connection string, instead requiring you to supply
them in the options parameter.
For compatibility with libpq, the following special connection parameters are
supported:
* dbname - The name of the database to connect to
* user - The user to sign in as
* password - The user's password
* host - The host to connect to. Values that start with / are for unix
domain sockets. (default is localhost)
* port - The port to bind to. (default is 5432)
* sslmode - Whether or not to use SSL (default is require, this is not
the default for libpq)
* fallback_application_name - An application_name to fall back to if one isn't provided.
* connect_timeout - Maximum wait for connection, in seconds. Zero or
not specified means wait indefinitely.
* sslcert - Cert file location. The file must contain PEM encoded data.
* sslkey - Key file location. The file must contain PEM encoded data.
* sslrootcert - The location of the root certificate file. The file
must contain PEM encoded data.
Valid values for sslmode are:
* disable - No SSL
* require - Always SSL (skip verification)
* verify-ca - Always SSL (verify that the certificate presented by the
server was signed by a trusted CA)
* verify-full - Always SSL (verify that the certification presented by
the server was signed by a trusted CA and the server host name
matches the one in the certificate)
See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
for more information about connection string parameters.
Use single quotes for values that contain whitespace:
"user=pqgotest password='with spaces'"
A backslash will escape the next character in values:
"user=space\ man password='it\'s valid'"
Note that the connection parameter client_encoding (which sets the
text encoding for the connection) may be set but must be "UTF8",
matching with the same rules as Postgres. It is an error to provide
any other value.
In addition to the parameters listed above, any run-time parameter that can be
set at backend start time can be set in the connection string. For more
information, see
http://www.postgresql.org/docs/current/static/runtime-config.html.
Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html
supported by libpq are also supported by pq. If any of the environment
variables not supported by pq are set, pq will panic during connection
establishment. Environment variables have a lower precedence than explicitly
provided connection parameters.
The pgpass mechanism as described in http://www.postgresql.org/docs/current/static/libpq-pgpass.html
is supported, but on Windows PGPASSFILE must be specified explicitly.
Queries
database/sql does not dictate any specific format for parameter
markers in query strings, and pq uses the Postgres-native ordinal markers,
as shown above. The same marker can be reused for the same parameter:
rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1
OR age BETWEEN $2 AND $2 + 3`, "orange", 64)
pq does not support the LastInsertId() method of the Result type in database/sql.
To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres
RETURNING clause with a standard Query or QueryRow call:
var userid int
err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)
For more details on RETURNING, see the Postgres documentation:
http://www.postgresql.org/docs/current/static/sql-insert.html
http://www.postgresql.org/docs/current/static/sql-update.html
http://www.postgresql.org/docs/current/static/sql-delete.html
For additional instructions on querying see the documentation for the database/sql package.
Data Types
Parameters pass through driver.DefaultParameterConverter before they are handled
by this package. When the binary_parameters connection option is enabled,
[]byte values are sent directly to the backend as data in binary format.
This package returns the following types for values from the PostgreSQL backend:
- integer types smallint, integer, and bigint are returned as int64
- floating-point types real and double precision are returned as float64
- character types char, varchar, and text are returned as string
- temporal types date, time, timetz, timestamp, and timestamptz are
returned as time.Time
- the boolean type is returned as bool
- the bytea type is returned as []byte
All other types are returned directly from the backend as []byte values in text format.
Errors
pq may return errors of type *pq.Error which can be interrogated for error details:
if err, ok := err.(*pq.Error); ok {
fmt.Println("pq error:", err.Code.Name())
}
See the pq.Error type for details.
Bulk imports
You can perform bulk imports by preparing a statement returned by pq.CopyIn (or
pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement
handle can then be repeatedly "executed" to copy data into the target table.
After all data has been processed you should call Exec() once with no arguments
to flush all buffered data. Any call to Exec() might return an error which
should be handled appropriately, but because of the internal buffering an error
returned by Exec() might not be related to the data passed in the call that
failed.
CopyIn uses COPY FROM internally. It is not possible to COPY outside of an
explicit transaction in pq.
Usage example:
txn, err := db.Begin()
if err != nil {
log.Fatal(err)
}
stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age"))
if err != nil {
log.Fatal(err)
}
for _, user := range users {
_, err = stmt.Exec(user.Name, int64(user.Age))
if err != nil {
log.Fatal(err)
}
}
_, err = stmt.Exec()
if err != nil {
log.Fatal(err)
}
err = stmt.Close()
if err != nil {
log.Fatal(err)
}
err = txn.Commit()
if err != nil {
log.Fatal(err)
}
Notifications
PostgreSQL supports a simple publish/subscribe model over database
connections. See http://www.postgresql.org/docs/current/static/sql-notify.html
for more information about the general mechanism.
To start listening for notifications, you first have to open a new connection
to the database by calling NewListener. This connection can not be used for
anything other than LISTEN / NOTIFY. Calling Listen will open a "notification
channel"; once a notification channel is open, a notification generated on that
channel will effect a send on the Listener.Notify channel. A notification
channel will remain open until Unlisten is called, though connection loss might
result in some notifications being lost. To solve this problem, Listener sends
a nil pointer over the Notify channel any time the connection is re-established
following a connection loss. The application can get information about the
state of the underlying connection by setting an event callback in the call to
NewListener.
A single Listener can safely be used from concurrent goroutines, which means
that there is often no need to create more than one Listener in your
application. However, a Listener is always connected to a single database, so
you will need to create a new Listener instance for every database you want to
receive notifications in.
The channel name in both Listen and Unlisten is case sensitive, and can contain
any characters legal in an identifier (see
http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
for more information). Note that the channel name will be truncated to 63
bytes by the PostgreSQL server.
You can find a complete, working example of Listener usage at
https://godoc.org/github.com/lib/pq/example/listen.
*/
package pq

602
vendor/github.com/lib/pq/encode.go generated vendored Normal file
View file

@ -0,0 +1,602 @@
package pq
import (
"bytes"
"database/sql/driver"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"math"
"strconv"
"strings"
"sync"
"time"
"github.com/lib/pq/oid"
)
func binaryEncode(parameterStatus *parameterStatus, x interface{}) []byte {
switch v := x.(type) {
case []byte:
return v
default:
return encode(parameterStatus, x, oid.T_unknown)
}
}
func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte {
switch v := x.(type) {
case int64:
return strconv.AppendInt(nil, v, 10)
case float64:
return strconv.AppendFloat(nil, v, 'f', -1, 64)
case []byte:
if pgtypOid == oid.T_bytea {
return encodeBytea(parameterStatus.serverVersion, v)
}
return v
case string:
if pgtypOid == oid.T_bytea {
return encodeBytea(parameterStatus.serverVersion, []byte(v))
}
return []byte(v)
case bool:
return strconv.AppendBool(nil, v)
case time.Time:
return formatTs(v)
default:
errorf("encode: unknown type for %T", v)
}
panic("not reached")
}
func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} {
switch f {
case formatBinary:
return binaryDecode(parameterStatus, s, typ)
case formatText:
return textDecode(parameterStatus, s, typ)
default:
panic("not reached")
}
}
func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} {
switch typ {
case oid.T_bytea:
return s
case oid.T_int8:
return int64(binary.BigEndian.Uint64(s))
case oid.T_int4:
return int64(int32(binary.BigEndian.Uint32(s)))
case oid.T_int2:
return int64(int16(binary.BigEndian.Uint16(s)))
case oid.T_uuid:
b, err := decodeUUIDBinary(s)
if err != nil {
panic(err)
}
return b
default:
errorf("don't know how to decode binary parameter of type %d", uint32(typ))
}
panic("not reached")
}
func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} {
switch typ {
case oid.T_char, oid.T_varchar, oid.T_text:
return string(s)
case oid.T_bytea:
b, err := parseBytea(s)
if err != nil {
errorf("%s", err)
}
return b
case oid.T_timestamptz:
return parseTs(parameterStatus.currentLocation, string(s))
case oid.T_timestamp, oid.T_date:
return parseTs(nil, string(s))
case oid.T_time:
return mustParse("15:04:05", typ, s)
case oid.T_timetz:
return mustParse("15:04:05-07", typ, s)
case oid.T_bool:
return s[0] == 't'
case oid.T_int8, oid.T_int4, oid.T_int2:
i, err := strconv.ParseInt(string(s), 10, 64)
if err != nil {
errorf("%s", err)
}
return i
case oid.T_float4, oid.T_float8:
// We always use 64 bit parsing, regardless of whether the input text is for
// a float4 or float8, because clients expect float64s for all float datatypes
// and returning a 32-bit parsed float64 produces lossy results.
f, err := strconv.ParseFloat(string(s), 64)
if err != nil {
errorf("%s", err)
}
return f
}
return s
}
// appendEncodedText encodes item in text format as required by COPY
// and appends to buf
func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte {
switch v := x.(type) {
case int64:
return strconv.AppendInt(buf, v, 10)
case float64:
return strconv.AppendFloat(buf, v, 'f', -1, 64)
case []byte:
encodedBytea := encodeBytea(parameterStatus.serverVersion, v)
return appendEscapedText(buf, string(encodedBytea))
case string:
return appendEscapedText(buf, v)
case bool:
return strconv.AppendBool(buf, v)
case time.Time:
return append(buf, formatTs(v)...)
case nil:
return append(buf, "\\N"...)
default:
errorf("encode: unknown type for %T", v)
}
panic("not reached")
}
func appendEscapedText(buf []byte, text string) []byte {
escapeNeeded := false
startPos := 0
var c byte
// check if we need to escape
for i := 0; i < len(text); i++ {
c = text[i]
if c == '\\' || c == '\n' || c == '\r' || c == '\t' {
escapeNeeded = true
startPos = i
break
}
}
if !escapeNeeded {
return append(buf, text...)
}
// copy till first char to escape, iterate the rest
result := append(buf, text[:startPos]...)
for i := startPos; i < len(text); i++ {
c = text[i]
switch c {
case '\\':
result = append(result, '\\', '\\')
case '\n':
result = append(result, '\\', 'n')
case '\r':
result = append(result, '\\', 'r')
case '\t':
result = append(result, '\\', 't')
default:
result = append(result, c)
}
}
return result
}
func mustParse(f string, typ oid.Oid, s []byte) time.Time {
str := string(s)
// check for a 30-minute-offset timezone
if (typ == oid.T_timestamptz || typ == oid.T_timetz) &&
str[len(str)-3] == ':' {
f += ":00"
}
t, err := time.Parse(f, str)
if err != nil {
errorf("decode: %s", err)
}
return t
}
var errInvalidTimestamp = errors.New("invalid timestamp")
type timestampParser struct {
err error
}
func (p *timestampParser) expect(str string, char byte, pos int) {
if p.err != nil {
return
}
if pos+1 > len(str) {
p.err = errInvalidTimestamp
return
}
if c := str[pos]; c != char && p.err == nil {
p.err = fmt.Errorf("expected '%v' at position %v; got '%v'", char, pos, c)
}
}
func (p *timestampParser) mustAtoi(str string, begin int, end int) int {
if p.err != nil {
return 0
}
if begin < 0 || end < 0 || begin > end || end > len(str) {
p.err = errInvalidTimestamp
return 0
}
result, err := strconv.Atoi(str[begin:end])
if err != nil {
if p.err == nil {
p.err = fmt.Errorf("expected number; got '%v'", str)
}
return 0
}
return result
}
// The location cache caches the time zones typically used by the client.
type locationCache struct {
cache map[int]*time.Location
lock sync.Mutex
}
// All connections share the same list of timezones. Benchmarking shows that
// about 5% speed could be gained by putting the cache in the connection and
// losing the mutex, at the cost of a small amount of memory and a somewhat
// significant increase in code complexity.
var globalLocationCache = newLocationCache()
func newLocationCache() *locationCache {
return &locationCache{cache: make(map[int]*time.Location)}
}
// Returns the cached timezone for the specified offset, creating and caching
// it if necessary.
func (c *locationCache) getLocation(offset int) *time.Location {
c.lock.Lock()
defer c.lock.Unlock()
location, ok := c.cache[offset]
if !ok {
location = time.FixedZone("", offset)
c.cache[offset] = location
}
return location
}
var infinityTsEnabled = false
var infinityTsNegative time.Time
var infinityTsPositive time.Time
const (
infinityTsEnabledAlready = "pq: infinity timestamp enabled already"
infinityTsNegativeMustBeSmaller = "pq: infinity timestamp: negative value must be smaller (before) than positive"
)
// EnableInfinityTs controls the handling of Postgres' "-infinity" and
// "infinity" "timestamp"s.
//
// If EnableInfinityTs is not called, "-infinity" and "infinity" will return
// []byte("-infinity") and []byte("infinity") respectively, and potentially
// cause error "sql: Scan error on column index 0: unsupported driver -> Scan
// pair: []uint8 -> *time.Time", when scanning into a time.Time value.
//
// Once EnableInfinityTs has been called, all connections created using this
// driver will decode Postgres' "-infinity" and "infinity" for "timestamp",
// "timestamp with time zone" and "date" types to the predefined minimum and
// maximum times, respectively. When encoding time.Time values, any time which
// equals or precedes the predefined minimum time will be encoded to
// "-infinity". Any values at or past the maximum time will similarly be
// encoded to "infinity".
//
// If EnableInfinityTs is called with negative >= positive, it will panic.
// Calling EnableInfinityTs after a connection has been established results in
// undefined behavior. If EnableInfinityTs is called more than once, it will
// panic.
func EnableInfinityTs(negative time.Time, positive time.Time) {
if infinityTsEnabled {
panic(infinityTsEnabledAlready)
}
if !negative.Before(positive) {
panic(infinityTsNegativeMustBeSmaller)
}
infinityTsEnabled = true
infinityTsNegative = negative
infinityTsPositive = positive
}
/*
* Testing might want to toggle infinityTsEnabled
*/
func disableInfinityTs() {
infinityTsEnabled = false
}
// This is a time function specific to the Postgres default DateStyle
// setting ("ISO, MDY"), the only one we currently support. This
// accounts for the discrepancies between the parsing available with
// time.Parse and the Postgres date formatting quirks.
func parseTs(currentLocation *time.Location, str string) interface{} {
switch str {
case "-infinity":
if infinityTsEnabled {
return infinityTsNegative
}
return []byte(str)
case "infinity":
if infinityTsEnabled {
return infinityTsPositive
}
return []byte(str)
}
t, err := ParseTimestamp(currentLocation, str)
if err != nil {
panic(err)
}
return t
}
// ParseTimestamp parses Postgres' text format. It returns a time.Time in
// currentLocation iff that time's offset agrees with the offset sent from the
// Postgres server. Otherwise, ParseTimestamp returns a time.Time with the
// fixed offset offset provided by the Postgres server.
func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error) {
p := timestampParser{}
monSep := strings.IndexRune(str, '-')
// this is Gregorian year, not ISO Year
// In Gregorian system, the year 1 BC is followed by AD 1
year := p.mustAtoi(str, 0, monSep)
daySep := monSep + 3
month := p.mustAtoi(str, monSep+1, daySep)
p.expect(str, '-', daySep)
timeSep := daySep + 3
day := p.mustAtoi(str, daySep+1, timeSep)
minLen := monSep + len("01-01") + 1
isBC := strings.HasSuffix(str, " BC")
if isBC {
minLen += 3
}
var hour, minute, second int
if len(str) > minLen {
p.expect(str, ' ', timeSep)
minSep := timeSep + 3
p.expect(str, ':', minSep)
hour = p.mustAtoi(str, timeSep+1, minSep)
secSep := minSep + 3
p.expect(str, ':', secSep)
minute = p.mustAtoi(str, minSep+1, secSep)
secEnd := secSep + 3
second = p.mustAtoi(str, secSep+1, secEnd)
}
remainderIdx := monSep + len("01-01 00:00:00") + 1
// Three optional (but ordered) sections follow: the
// fractional seconds, the time zone offset, and the BC
// designation. We set them up here and adjust the other
// offsets if the preceding sections exist.
nanoSec := 0
tzOff := 0
if remainderIdx < len(str) && str[remainderIdx] == '.' {
fracStart := remainderIdx + 1
fracOff := strings.IndexAny(str[fracStart:], "-+ ")
if fracOff < 0 {
fracOff = len(str) - fracStart
}
fracSec := p.mustAtoi(str, fracStart, fracStart+fracOff)
nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff))))
remainderIdx += fracOff + 1
}
if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart] == '-' || str[tzStart] == '+') {
// time zone separator is always '-' or '+' (UTC is +00)
var tzSign int
switch c := str[tzStart]; c {
case '-':
tzSign = -1
case '+':
tzSign = +1
default:
return time.Time{}, fmt.Errorf("expected '-' or '+' at position %v; got %v", tzStart, c)
}
tzHours := p.mustAtoi(str, tzStart+1, tzStart+3)
remainderIdx += 3
var tzMin, tzSec int
if remainderIdx < len(str) && str[remainderIdx] == ':' {
tzMin = p.mustAtoi(str, remainderIdx+1, remainderIdx+3)
remainderIdx += 3
}
if remainderIdx < len(str) && str[remainderIdx] == ':' {
tzSec = p.mustAtoi(str, remainderIdx+1, remainderIdx+3)
remainderIdx += 3
}
tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec)
}
var isoYear int
if isBC {
isoYear = 1 - year
remainderIdx += 3
} else {
isoYear = year
}
if remainderIdx < len(str) {
return time.Time{}, fmt.Errorf("expected end of input, got %v", str[remainderIdx:])
}
t := time.Date(isoYear, time.Month(month), day,
hour, minute, second, nanoSec,
globalLocationCache.getLocation(tzOff))
if currentLocation != nil {
// Set the location of the returned Time based on the session's
// TimeZone value, but only if the local time zone database agrees with
// the remote database on the offset.
lt := t.In(currentLocation)
_, newOff := lt.Zone()
if newOff == tzOff {
t = lt
}
}
return t, p.err
}
// formatTs formats t into a format postgres understands.
func formatTs(t time.Time) []byte {
if infinityTsEnabled {
// t <= -infinity : ! (t > -infinity)
if !t.After(infinityTsNegative) {
return []byte("-infinity")
}
// t >= infinity : ! (!t < infinity)
if !t.Before(infinityTsPositive) {
return []byte("infinity")
}
}
return FormatTimestamp(t)
}
// FormatTimestamp formats t into Postgres' text format for timestamps.
func FormatTimestamp(t time.Time) []byte {
// Need to send dates before 0001 A.D. with " BC" suffix, instead of the
// minus sign preferred by Go.
// Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on
bc := false
if t.Year() <= 0 {
// flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11"
t = t.AddDate((-t.Year())*2+1, 0, 0)
bc = true
}
b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00"))
_, offset := t.Zone()
offset %= 60
if offset != 0 {
// RFC3339Nano already printed the minus sign
if offset < 0 {
offset = -offset
}
b = append(b, ':')
if offset < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(offset), 10)
}
if bc {
b = append(b, " BC"...)
}
return b
}
// Parse a bytea value received from the server. Both "hex" and the legacy
// "escape" format are supported.
func parseBytea(s []byte) (result []byte, err error) {
if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) {
// bytea_output = hex
s = s[2:] // trim off leading "\\x"
result = make([]byte, hex.DecodedLen(len(s)))
_, err := hex.Decode(result, s)
if err != nil {
return nil, err
}
} else {
// bytea_output = escape
for len(s) > 0 {
if s[0] == '\\' {
// escaped '\\'
if len(s) >= 2 && s[1] == '\\' {
result = append(result, '\\')
s = s[2:]
continue
}
// '\\' followed by an octal number
if len(s) < 4 {
return nil, fmt.Errorf("invalid bytea sequence %v", s)
}
r, err := strconv.ParseInt(string(s[1:4]), 8, 9)
if err != nil {
return nil, fmt.Errorf("could not parse bytea value: %s", err.Error())
}
result = append(result, byte(r))
s = s[4:]
} else {
// We hit an unescaped, raw byte. Try to read in as many as
// possible in one go.
i := bytes.IndexByte(s, '\\')
if i == -1 {
result = append(result, s...)
break
}
result = append(result, s[:i]...)
s = s[i:]
}
}
}
return result, nil
}
func encodeBytea(serverVersion int, v []byte) (result []byte) {
if serverVersion >= 90000 {
// Use the hex format if we know that the server supports it
result = make([]byte, 2+hex.EncodedLen(len(v)))
result[0] = '\\'
result[1] = 'x'
hex.Encode(result[2:], v)
} else {
// .. or resort to "escape"
for _, b := range v {
if b == '\\' {
result = append(result, '\\', '\\')
} else if b < 0x20 || b > 0x7e {
result = append(result, []byte(fmt.Sprintf("\\%03o", b))...)
} else {
result = append(result, b)
}
}
}
return result
}
// NullTime represents a time.Time that may be null. NullTime implements the
// sql.Scanner interface so it can be used as a scan destination, similar to
// sql.NullString.
type NullTime struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}

515
vendor/github.com/lib/pq/error.go generated vendored Normal file
View file

@ -0,0 +1,515 @@
package pq
import (
"database/sql/driver"
"fmt"
"io"
"net"
"runtime"
)
// Error severities
const (
Efatal = "FATAL"
Epanic = "PANIC"
Ewarning = "WARNING"
Enotice = "NOTICE"
Edebug = "DEBUG"
Einfo = "INFO"
Elog = "LOG"
)
// Error represents an error communicating with the server.
//
// See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields
type Error struct {
Severity string
Code ErrorCode
Message string
Detail string
Hint string
Position string
InternalPosition string
InternalQuery string
Where string
Schema string
Table string
Column string
DataTypeName string
Constraint string
File string
Line string
Routine string
}
// ErrorCode is a five-character error code.
type ErrorCode string
// Name returns a more human friendly rendering of the error code, namely the
// "condition name".
//
// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for
// details.
func (ec ErrorCode) Name() string {
return errorCodeNames[ec]
}
// ErrorClass is only the class part of an error code.
type ErrorClass string
// Name returns the condition name of an error class. It is equivalent to the
// condition name of the "standard" error code (i.e. the one having the last
// three characters "000").
func (ec ErrorClass) Name() string {
return errorCodeNames[ErrorCode(ec+"000")]
}
// Class returns the error class, e.g. "28".
//
// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for
// details.
func (ec ErrorCode) Class() ErrorClass {
return ErrorClass(ec[0:2])
}
// errorCodeNames is a mapping between the five-character error codes and the
// human readable "condition names". It is derived from the list at
// http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html
var errorCodeNames = map[ErrorCode]string{
// Class 00 - Successful Completion
"00000": "successful_completion",
// Class 01 - Warning
"01000": "warning",
"0100C": "dynamic_result_sets_returned",
"01008": "implicit_zero_bit_padding",
"01003": "null_value_eliminated_in_set_function",
"01007": "privilege_not_granted",
"01006": "privilege_not_revoked",
"01004": "string_data_right_truncation",
"01P01": "deprecated_feature",
// Class 02 - No Data (this is also a warning class per the SQL standard)
"02000": "no_data",
"02001": "no_additional_dynamic_result_sets_returned",
// Class 03 - SQL Statement Not Yet Complete
"03000": "sql_statement_not_yet_complete",
// Class 08 - Connection Exception
"08000": "connection_exception",
"08003": "connection_does_not_exist",
"08006": "connection_failure",
"08001": "sqlclient_unable_to_establish_sqlconnection",
"08004": "sqlserver_rejected_establishment_of_sqlconnection",
"08007": "transaction_resolution_unknown",
"08P01": "protocol_violation",
// Class 09 - Triggered Action Exception
"09000": "triggered_action_exception",
// Class 0A - Feature Not Supported
"0A000": "feature_not_supported",
// Class 0B - Invalid Transaction Initiation
"0B000": "invalid_transaction_initiation",
// Class 0F - Locator Exception
"0F000": "locator_exception",
"0F001": "invalid_locator_specification",
// Class 0L - Invalid Grantor
"0L000": "invalid_grantor",
"0LP01": "invalid_grant_operation",
// Class 0P - Invalid Role Specification
"0P000": "invalid_role_specification",
// Class 0Z - Diagnostics Exception
"0Z000": "diagnostics_exception",
"0Z002": "stacked_diagnostics_accessed_without_active_handler",
// Class 20 - Case Not Found
"20000": "case_not_found",
// Class 21 - Cardinality Violation
"21000": "cardinality_violation",
// Class 22 - Data Exception
"22000": "data_exception",
"2202E": "array_subscript_error",
"22021": "character_not_in_repertoire",
"22008": "datetime_field_overflow",
"22012": "division_by_zero",
"22005": "error_in_assignment",
"2200B": "escape_character_conflict",
"22022": "indicator_overflow",
"22015": "interval_field_overflow",
"2201E": "invalid_argument_for_logarithm",
"22014": "invalid_argument_for_ntile_function",
"22016": "invalid_argument_for_nth_value_function",
"2201F": "invalid_argument_for_power_function",
"2201G": "invalid_argument_for_width_bucket_function",
"22018": "invalid_character_value_for_cast",
"22007": "invalid_datetime_format",
"22019": "invalid_escape_character",
"2200D": "invalid_escape_octet",
"22025": "invalid_escape_sequence",
"22P06": "nonstandard_use_of_escape_character",
"22010": "invalid_indicator_parameter_value",
"22023": "invalid_parameter_value",
"2201B": "invalid_regular_expression",
"2201W": "invalid_row_count_in_limit_clause",
"2201X": "invalid_row_count_in_result_offset_clause",
"22009": "invalid_time_zone_displacement_value",
"2200C": "invalid_use_of_escape_character",
"2200G": "most_specific_type_mismatch",
"22004": "null_value_not_allowed",
"22002": "null_value_no_indicator_parameter",
"22003": "numeric_value_out_of_range",
"2200H": "sequence_generator_limit_exceeded",
"22026": "string_data_length_mismatch",
"22001": "string_data_right_truncation",
"22011": "substring_error",
"22027": "trim_error",
"22024": "unterminated_c_string",
"2200F": "zero_length_character_string",
"22P01": "floating_point_exception",
"22P02": "invalid_text_representation",
"22P03": "invalid_binary_representation",
"22P04": "bad_copy_file_format",
"22P05": "untranslatable_character",
"2200L": "not_an_xml_document",
"2200M": "invalid_xml_document",
"2200N": "invalid_xml_content",
"2200S": "invalid_xml_comment",
"2200T": "invalid_xml_processing_instruction",
// Class 23 - Integrity Constraint Violation
"23000": "integrity_constraint_violation",
"23001": "restrict_violation",
"23502": "not_null_violation",
"23503": "foreign_key_violation",
"23505": "unique_violation",
"23514": "check_violation",
"23P01": "exclusion_violation",
// Class 24 - Invalid Cursor State
"24000": "invalid_cursor_state",
// Class 25 - Invalid Transaction State
"25000": "invalid_transaction_state",
"25001": "active_sql_transaction",
"25002": "branch_transaction_already_active",
"25008": "held_cursor_requires_same_isolation_level",
"25003": "inappropriate_access_mode_for_branch_transaction",
"25004": "inappropriate_isolation_level_for_branch_transaction",
"25005": "no_active_sql_transaction_for_branch_transaction",
"25006": "read_only_sql_transaction",
"25007": "schema_and_data_statement_mixing_not_supported",
"25P01": "no_active_sql_transaction",
"25P02": "in_failed_sql_transaction",
// Class 26 - Invalid SQL Statement Name
"26000": "invalid_sql_statement_name",
// Class 27 - Triggered Data Change Violation
"27000": "triggered_data_change_violation",
// Class 28 - Invalid Authorization Specification
"28000": "invalid_authorization_specification",
"28P01": "invalid_password",
// Class 2B - Dependent Privilege Descriptors Still Exist
"2B000": "dependent_privilege_descriptors_still_exist",
"2BP01": "dependent_objects_still_exist",
// Class 2D - Invalid Transaction Termination
"2D000": "invalid_transaction_termination",
// Class 2F - SQL Routine Exception
"2F000": "sql_routine_exception",
"2F005": "function_executed_no_return_statement",
"2F002": "modifying_sql_data_not_permitted",
"2F003": "prohibited_sql_statement_attempted",
"2F004": "reading_sql_data_not_permitted",
// Class 34 - Invalid Cursor Name
"34000": "invalid_cursor_name",
// Class 38 - External Routine Exception
"38000": "external_routine_exception",
"38001": "containing_sql_not_permitted",
"38002": "modifying_sql_data_not_permitted",
"38003": "prohibited_sql_statement_attempted",
"38004": "reading_sql_data_not_permitted",
// Class 39 - External Routine Invocation Exception
"39000": "external_routine_invocation_exception",
"39001": "invalid_sqlstate_returned",
"39004": "null_value_not_allowed",
"39P01": "trigger_protocol_violated",
"39P02": "srf_protocol_violated",
// Class 3B - Savepoint Exception
"3B000": "savepoint_exception",
"3B001": "invalid_savepoint_specification",
// Class 3D - Invalid Catalog Name
"3D000": "invalid_catalog_name",
// Class 3F - Invalid Schema Name
"3F000": "invalid_schema_name",
// Class 40 - Transaction Rollback
"40000": "transaction_rollback",
"40002": "transaction_integrity_constraint_violation",
"40001": "serialization_failure",
"40003": "statement_completion_unknown",
"40P01": "deadlock_detected",
// Class 42 - Syntax Error or Access Rule Violation
"42000": "syntax_error_or_access_rule_violation",
"42601": "syntax_error",
"42501": "insufficient_privilege",
"42846": "cannot_coerce",
"42803": "grouping_error",
"42P20": "windowing_error",
"42P19": "invalid_recursion",
"42830": "invalid_foreign_key",
"42602": "invalid_name",
"42622": "name_too_long",
"42939": "reserved_name",
"42804": "datatype_mismatch",
"42P18": "indeterminate_datatype",
"42P21": "collation_mismatch",
"42P22": "indeterminate_collation",
"42809": "wrong_object_type",
"42703": "undefined_column",
"42883": "undefined_function",
"42P01": "undefined_table",
"42P02": "undefined_parameter",
"42704": "undefined_object",
"42701": "duplicate_column",
"42P03": "duplicate_cursor",
"42P04": "duplicate_database",
"42723": "duplicate_function",
"42P05": "duplicate_prepared_statement",
"42P06": "duplicate_schema",
"42P07": "duplicate_table",
"42712": "duplicate_alias",
"42710": "duplicate_object",
"42702": "ambiguous_column",
"42725": "ambiguous_function",
"42P08": "ambiguous_parameter",
"42P09": "ambiguous_alias",
"42P10": "invalid_column_reference",
"42611": "invalid_column_definition",
"42P11": "invalid_cursor_definition",
"42P12": "invalid_database_definition",
"42P13": "invalid_function_definition",
"42P14": "invalid_prepared_statement_definition",
"42P15": "invalid_schema_definition",
"42P16": "invalid_table_definition",
"42P17": "invalid_object_definition",
// Class 44 - WITH CHECK OPTION Violation
"44000": "with_check_option_violation",
// Class 53 - Insufficient Resources
"53000": "insufficient_resources",
"53100": "disk_full",
"53200": "out_of_memory",
"53300": "too_many_connections",
"53400": "configuration_limit_exceeded",
// Class 54 - Program Limit Exceeded
"54000": "program_limit_exceeded",
"54001": "statement_too_complex",
"54011": "too_many_columns",
"54023": "too_many_arguments",
// Class 55 - Object Not In Prerequisite State
"55000": "object_not_in_prerequisite_state",
"55006": "object_in_use",
"55P02": "cant_change_runtime_param",
"55P03": "lock_not_available",
// Class 57 - Operator Intervention
"57000": "operator_intervention",
"57014": "query_canceled",
"57P01": "admin_shutdown",
"57P02": "crash_shutdown",
"57P03": "cannot_connect_now",
"57P04": "database_dropped",
// Class 58 - System Error (errors external to PostgreSQL itself)
"58000": "system_error",
"58030": "io_error",
"58P01": "undefined_file",
"58P02": "duplicate_file",
// Class F0 - Configuration File Error
"F0000": "config_file_error",
"F0001": "lock_file_exists",
// Class HV - Foreign Data Wrapper Error (SQL/MED)
"HV000": "fdw_error",
"HV005": "fdw_column_name_not_found",
"HV002": "fdw_dynamic_parameter_value_needed",
"HV010": "fdw_function_sequence_error",
"HV021": "fdw_inconsistent_descriptor_information",
"HV024": "fdw_invalid_attribute_value",
"HV007": "fdw_invalid_column_name",
"HV008": "fdw_invalid_column_number",
"HV004": "fdw_invalid_data_type",
"HV006": "fdw_invalid_data_type_descriptors",
"HV091": "fdw_invalid_descriptor_field_identifier",
"HV00B": "fdw_invalid_handle",
"HV00C": "fdw_invalid_option_index",
"HV00D": "fdw_invalid_option_name",
"HV090": "fdw_invalid_string_length_or_buffer_length",
"HV00A": "fdw_invalid_string_format",
"HV009": "fdw_invalid_use_of_null_pointer",
"HV014": "fdw_too_many_handles",
"HV001": "fdw_out_of_memory",
"HV00P": "fdw_no_schemas",
"HV00J": "fdw_option_name_not_found",
"HV00K": "fdw_reply_handle",
"HV00Q": "fdw_schema_not_found",
"HV00R": "fdw_table_not_found",
"HV00L": "fdw_unable_to_create_execution",
"HV00M": "fdw_unable_to_create_reply",
"HV00N": "fdw_unable_to_establish_connection",
// Class P0 - PL/pgSQL Error
"P0000": "plpgsql_error",
"P0001": "raise_exception",
"P0002": "no_data_found",
"P0003": "too_many_rows",
// Class XX - Internal Error
"XX000": "internal_error",
"XX001": "data_corrupted",
"XX002": "index_corrupted",
}
func parseError(r *readBuf) *Error {
err := new(Error)
for t := r.byte(); t != 0; t = r.byte() {
msg := r.string()
switch t {
case 'S':
err.Severity = msg
case 'C':
err.Code = ErrorCode(msg)
case 'M':
err.Message = msg
case 'D':
err.Detail = msg
case 'H':
err.Hint = msg
case 'P':
err.Position = msg
case 'p':
err.InternalPosition = msg
case 'q':
err.InternalQuery = msg
case 'W':
err.Where = msg
case 's':
err.Schema = msg
case 't':
err.Table = msg
case 'c':
err.Column = msg
case 'd':
err.DataTypeName = msg
case 'n':
err.Constraint = msg
case 'F':
err.File = msg
case 'L':
err.Line = msg
case 'R':
err.Routine = msg
}
}
return err
}
// Fatal returns true if the Error Severity is fatal.
func (err *Error) Fatal() bool {
return err.Severity == Efatal
}
// Get implements the legacy PGError interface. New code should use the fields
// of the Error struct directly.
func (err *Error) Get(k byte) (v string) {
switch k {
case 'S':
return err.Severity
case 'C':
return string(err.Code)
case 'M':
return err.Message
case 'D':
return err.Detail
case 'H':
return err.Hint
case 'P':
return err.Position
case 'p':
return err.InternalPosition
case 'q':
return err.InternalQuery
case 'W':
return err.Where
case 's':
return err.Schema
case 't':
return err.Table
case 'c':
return err.Column
case 'd':
return err.DataTypeName
case 'n':
return err.Constraint
case 'F':
return err.File
case 'L':
return err.Line
case 'R':
return err.Routine
}
return ""
}
func (err Error) Error() string {
return "pq: " + err.Message
}
// PGError is an interface used by previous versions of pq. It is provided
// only to support legacy code. New code should use the Error type.
type PGError interface {
Error() string
Fatal() bool
Get(k byte) (v string)
}
func errorf(s string, args ...interface{}) {
panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...)))
}
// TODO(ainar-g) Rename to errorf after removing panics.
func fmterrorf(s string, args ...interface{}) error {
return fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))
}
func errRecoverNoErrBadConn(err *error) {
e := recover()
if e == nil {
// Do nothing
return
}
var ok bool
*err, ok = e.(error)
if !ok {
*err = fmt.Errorf("pq: unexpected error: %#v", e)
}
}
func (cn *conn) errRecover(err *error) {
e := recover()
switch v := e.(type) {
case nil:
// Do nothing
case runtime.Error:
cn.bad = true
panic(v)
case *Error:
if v.Fatal() {
*err = driver.ErrBadConn
} else {
*err = v
}
case *net.OpError:
cn.bad = true
*err = v
case error:
if v == io.EOF || v.(error).Error() == "remote error: handshake failure" {
*err = driver.ErrBadConn
} else {
*err = v
}
default:
cn.bad = true
panic(fmt.Sprintf("unknown error: %#v", e))
}
// Any time we return ErrBadConn, we need to remember it since *Tx doesn't
// mark the connection bad in database/sql.
if *err == driver.ErrBadConn {
cn.bad = true
}
}

1
vendor/github.com/lib/pq/go.mod generated vendored Normal file
View file

@ -0,0 +1 @@
module github.com/lib/pq

797
vendor/github.com/lib/pq/notify.go generated vendored Normal file
View file

@ -0,0 +1,797 @@
package pq
// Package pq is a pure Go Postgres driver for the database/sql package.
// This module contains support for Postgres LISTEN/NOTIFY.
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
// Notification represents a single notification from the database.
type Notification struct {
// Process ID (PID) of the notifying postgres backend.
BePid int
// Name of the channel the notification was sent on.
Channel string
// Payload, or the empty string if unspecified.
Extra string
}
func recvNotification(r *readBuf) *Notification {
bePid := r.int32()
channel := r.string()
extra := r.string()
return &Notification{bePid, channel, extra}
}
const (
connStateIdle int32 = iota
connStateExpectResponse
connStateExpectReadyForQuery
)
type message struct {
typ byte
err error
}
var errListenerConnClosed = errors.New("pq: ListenerConn has been closed")
// ListenerConn is a low-level interface for waiting for notifications. You
// should use Listener instead.
type ListenerConn struct {
// guards cn and err
connectionLock sync.Mutex
cn *conn
err error
connState int32
// the sending goroutine will be holding this lock
senderLock sync.Mutex
notificationChan chan<- *Notification
replyChan chan message
}
// NewListenerConn creates a new ListenerConn. Use NewListener instead.
func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) {
return newDialListenerConn(defaultDialer{}, name, notificationChan)
}
func newDialListenerConn(d Dialer, name string, c chan<- *Notification) (*ListenerConn, error) {
cn, err := DialOpen(d, name)
if err != nil {
return nil, err
}
l := &ListenerConn{
cn: cn.(*conn),
notificationChan: c,
connState: connStateIdle,
replyChan: make(chan message, 2),
}
go l.listenerConnMain()
return l, nil
}
// We can only allow one goroutine at a time to be running a query on the
// connection for various reasons, so the goroutine sending on the connection
// must be holding senderLock.
//
// Returns an error if an unrecoverable error has occurred and the ListenerConn
// should be abandoned.
func (l *ListenerConn) acquireSenderLock() error {
// we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery
l.senderLock.Lock()
l.connectionLock.Lock()
err := l.err
l.connectionLock.Unlock()
if err != nil {
l.senderLock.Unlock()
return err
}
return nil
}
func (l *ListenerConn) releaseSenderLock() {
l.senderLock.Unlock()
}
// setState advances the protocol state to newState. Returns false if moving
// to that state from the current state is not allowed.
func (l *ListenerConn) setState(newState int32) bool {
var expectedState int32
switch newState {
case connStateIdle:
expectedState = connStateExpectReadyForQuery
case connStateExpectResponse:
expectedState = connStateIdle
case connStateExpectReadyForQuery:
expectedState = connStateExpectResponse
default:
panic(fmt.Sprintf("unexpected listenerConnState %d", newState))
}
return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState)
}
// Main logic is here: receive messages from the postgres backend, forward
// notifications and query replies and keep the internal state in sync with the
// protocol state. Returns when the connection has been lost, is about to go
// away or should be discarded because we couldn't agree on the state with the
// server backend.
func (l *ListenerConn) listenerConnLoop() (err error) {
defer errRecoverNoErrBadConn(&err)
r := &readBuf{}
for {
t, err := l.cn.recvMessage(r)
if err != nil {
return err
}
switch t {
case 'A':
// recvNotification copies all the data so we don't need to worry
// about the scratch buffer being overwritten.
l.notificationChan <- recvNotification(r)
case 'T', 'D':
// only used by tests; ignore
case 'E':
// We might receive an ErrorResponse even when not in a query; it
// is expected that the server will close the connection after
// that, but we should make sure that the error we display is the
// one from the stray ErrorResponse, not io.ErrUnexpectedEOF.
if !l.setState(connStateExpectReadyForQuery) {
return parseError(r)
}
l.replyChan <- message{t, parseError(r)}
case 'C', 'I':
if !l.setState(connStateExpectReadyForQuery) {
// protocol out of sync
return fmt.Errorf("unexpected CommandComplete")
}
// ExecSimpleQuery doesn't need to know about this message
case 'Z':
if !l.setState(connStateIdle) {
// protocol out of sync
return fmt.Errorf("unexpected ReadyForQuery")
}
l.replyChan <- message{t, nil}
case 'N', 'S':
// ignore
default:
return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t)
}
}
}
// This is the main routine for the goroutine receiving on the database
// connection. Most of the main logic is in listenerConnLoop.
func (l *ListenerConn) listenerConnMain() {
err := l.listenerConnLoop()
// listenerConnLoop terminated; we're done, but we still have to clean up.
// Make sure nobody tries to start any new queries by making sure the err
// pointer is set. It is important that we do not overwrite its value; a
// connection could be closed by either this goroutine or one sending on
// the connection -- whoever closes the connection is assumed to have the
// more meaningful error message (as the other one will probably get
// net.errClosed), so that goroutine sets the error we expose while the
// other error is discarded. If the connection is lost while two
// goroutines are operating on the socket, it probably doesn't matter which
// error we expose so we don't try to do anything more complex.
l.connectionLock.Lock()
if l.err == nil {
l.err = err
}
l.cn.Close()
l.connectionLock.Unlock()
// There might be a query in-flight; make sure nobody's waiting for a
// response to it, since there's not going to be one.
close(l.replyChan)
// let the listener know we're done
close(l.notificationChan)
// this ListenerConn is done
}
// Listen sends a LISTEN query to the server. See ExecSimpleQuery.
func (l *ListenerConn) Listen(channel string) (bool, error) {
return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel))
}
// Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery.
func (l *ListenerConn) Unlisten(channel string) (bool, error) {
return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel))
}
// UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery.
func (l *ListenerConn) UnlistenAll() (bool, error) {
return l.ExecSimpleQuery("UNLISTEN *")
}
// Ping the remote server to make sure it's alive. Non-nil error means the
// connection has failed and should be abandoned.
func (l *ListenerConn) Ping() error {
sent, err := l.ExecSimpleQuery("")
if !sent {
return err
}
if err != nil {
// shouldn't happen
panic(err)
}
return nil
}
// Attempt to send a query on the connection. Returns an error if sending the
// query failed, and the caller should initiate closure of this connection.
// The caller must be holding senderLock (see acquireSenderLock and
// releaseSenderLock).
func (l *ListenerConn) sendSimpleQuery(q string) (err error) {
defer errRecoverNoErrBadConn(&err)
// must set connection state before sending the query
if !l.setState(connStateExpectResponse) {
panic("two queries running at the same time")
}
// Can't use l.cn.writeBuf here because it uses the scratch buffer which
// might get overwritten by listenerConnLoop.
b := &writeBuf{
buf: []byte("Q\x00\x00\x00\x00"),
pos: 1,
}
b.string(q)
l.cn.send(b)
return nil
}
// ExecSimpleQuery executes a "simple query" (i.e. one with no bindable
// parameters) on the connection. The possible return values are:
// 1) "executed" is true; the query was executed to completion on the
// database server. If the query failed, err will be set to the error
// returned by the database, otherwise err will be nil.
// 2) If "executed" is false, the query could not be executed on the remote
// server. err will be non-nil.
//
// After a call to ExecSimpleQuery has returned an executed=false value, the
// connection has either been closed or will be closed shortly thereafter, and
// all subsequently executed queries will return an error.
func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) {
if err = l.acquireSenderLock(); err != nil {
return false, err
}
defer l.releaseSenderLock()
err = l.sendSimpleQuery(q)
if err != nil {
// We can't know what state the protocol is in, so we need to abandon
// this connection.
l.connectionLock.Lock()
// Set the error pointer if it hasn't been set already; see
// listenerConnMain.
if l.err == nil {
l.err = err
}
l.connectionLock.Unlock()
l.cn.c.Close()
return false, err
}
// now we just wait for a reply..
for {
m, ok := <-l.replyChan
if !ok {
// We lost the connection to server, don't bother waiting for a
// a response. err should have been set already.
l.connectionLock.Lock()
err := l.err
l.connectionLock.Unlock()
return false, err
}
switch m.typ {
case 'Z':
// sanity check
if m.err != nil {
panic("m.err != nil")
}
// done; err might or might not be set
return true, err
case 'E':
// sanity check
if m.err == nil {
panic("m.err == nil")
}
// server responded with an error; ReadyForQuery to follow
err = m.err
default:
return false, fmt.Errorf("unknown response for simple query: %q", m.typ)
}
}
}
// Close closes the connection.
func (l *ListenerConn) Close() error {
l.connectionLock.Lock()
if l.err != nil {
l.connectionLock.Unlock()
return errListenerConnClosed
}
l.err = errListenerConnClosed
l.connectionLock.Unlock()
// We can't send anything on the connection without holding senderLock.
// Simply close the net.Conn to wake up everyone operating on it.
return l.cn.c.Close()
}
// Err returns the reason the connection was closed. It is not safe to call
// this function until l.Notify has been closed.
func (l *ListenerConn) Err() error {
return l.err
}
var errListenerClosed = errors.New("pq: Listener has been closed")
// ErrChannelAlreadyOpen is returned from Listen when a channel is already
// open.
var ErrChannelAlreadyOpen = errors.New("pq: channel is already open")
// ErrChannelNotOpen is returned from Unlisten when a channel is not open.
var ErrChannelNotOpen = errors.New("pq: channel is not open")
// ListenerEventType is an enumeration of listener event types.
type ListenerEventType int
const (
// ListenerEventConnected is emitted only when the database connection
// has been initially initialized. The err argument of the callback
// will always be nil.
ListenerEventConnected ListenerEventType = iota
// ListenerEventDisconnected is emitted after a database connection has
// been lost, either because of an error or because Close has been
// called. The err argument will be set to the reason the database
// connection was lost.
ListenerEventDisconnected
// ListenerEventReconnected is emitted after a database connection has
// been re-established after connection loss. The err argument of the
// callback will always be nil. After this event has been emitted, a
// nil pq.Notification is sent on the Listener.Notify channel.
ListenerEventReconnected
// ListenerEventConnectionAttemptFailed is emitted after a connection
// to the database was attempted, but failed. The err argument will be
// set to an error describing why the connection attempt did not
// succeed.
ListenerEventConnectionAttemptFailed
)
// EventCallbackType is the event callback type. See also ListenerEventType
// constants' documentation.
type EventCallbackType func(event ListenerEventType, err error)
// Listener provides an interface for listening to notifications from a
// PostgreSQL database. For general usage information, see section
// "Notifications".
//
// Listener can safely be used from concurrently running goroutines.
type Listener struct {
// Channel for receiving notifications from the database. In some cases a
// nil value will be sent. See section "Notifications" above.
Notify chan *Notification
name string
minReconnectInterval time.Duration
maxReconnectInterval time.Duration
dialer Dialer
eventCallback EventCallbackType
lock sync.Mutex
isClosed bool
reconnectCond *sync.Cond
cn *ListenerConn
connNotificationChan <-chan *Notification
channels map[string]struct{}
}
// NewListener creates a new database connection dedicated to LISTEN / NOTIFY.
//
// name should be set to a connection string to be used to establish the
// database connection (see section "Connection String Parameters" above).
//
// minReconnectInterval controls the duration to wait before trying to
// re-establish the database connection after connection loss. After each
// consecutive failure this interval is doubled, until maxReconnectInterval is
// reached. Successfully completing the connection establishment procedure
// resets the interval back to minReconnectInterval.
//
// The last parameter eventCallback can be set to a function which will be
// called by the Listener when the state of the underlying database connection
// changes. This callback will be called by the goroutine which dispatches the
// notifications over the Notify channel, so you should try to avoid doing
// potentially time-consuming operations from the callback.
func NewListener(name string,
minReconnectInterval time.Duration,
maxReconnectInterval time.Duration,
eventCallback EventCallbackType) *Listener {
return NewDialListener(defaultDialer{}, name, minReconnectInterval, maxReconnectInterval, eventCallback)
}
// NewDialListener is like NewListener but it takes a Dialer.
func NewDialListener(d Dialer,
name string,
minReconnectInterval time.Duration,
maxReconnectInterval time.Duration,
eventCallback EventCallbackType) *Listener {
l := &Listener{
name: name,
minReconnectInterval: minReconnectInterval,
maxReconnectInterval: maxReconnectInterval,
dialer: d,
eventCallback: eventCallback,
channels: make(map[string]struct{}),
Notify: make(chan *Notification, 32),
}
l.reconnectCond = sync.NewCond(&l.lock)
go l.listenerMain()
return l
}
// NotificationChannel returns the notification channel for this listener.
// This is the same channel as Notify, and will not be recreated during the
// life time of the Listener.
func (l *Listener) NotificationChannel() <-chan *Notification {
return l.Notify
}
// Listen starts listening for notifications on a channel. Calls to this
// function will block until an acknowledgement has been received from the
// server. Note that Listener automatically re-establishes the connection
// after connection loss, so this function may block indefinitely if the
// connection can not be re-established.
//
// Listen will only fail in three conditions:
// 1) The channel is already open. The returned error will be
// ErrChannelAlreadyOpen.
// 2) The query was executed on the remote server, but PostgreSQL returned an
// error message in response to the query. The returned error will be a
// pq.Error containing the information the server supplied.
// 3) Close is called on the Listener before the request could be completed.
//
// The channel name is case-sensitive.
func (l *Listener) Listen(channel string) error {
l.lock.Lock()
defer l.lock.Unlock()
if l.isClosed {
return errListenerClosed
}
// The server allows you to issue a LISTEN on a channel which is already
// open, but it seems useful to be able to detect this case to spot for
// mistakes in application logic. If the application genuinely does't
// care, it can check the exported error and ignore it.
_, exists := l.channels[channel]
if exists {
return ErrChannelAlreadyOpen
}
if l.cn != nil {
// If gotResponse is true but error is set, the query was executed on
// the remote server, but resulted in an error. This should be
// relatively rare, so it's fine if we just pass the error to our
// caller. However, if gotResponse is false, we could not complete the
// query on the remote server and our underlying connection is about
// to go away, so we only add relname to l.channels, and wait for
// resync() to take care of the rest.
gotResponse, err := l.cn.Listen(channel)
if gotResponse && err != nil {
return err
}
}
l.channels[channel] = struct{}{}
for l.cn == nil {
l.reconnectCond.Wait()
// we let go of the mutex for a while
if l.isClosed {
return errListenerClosed
}
}
return nil
}
// Unlisten removes a channel from the Listener's channel list. Returns
// ErrChannelNotOpen if the Listener is not listening on the specified channel.
// Returns immediately with no error if there is no connection. Note that you
// might still get notifications for this channel even after Unlisten has
// returned.
//
// The channel name is case-sensitive.
func (l *Listener) Unlisten(channel string) error {
l.lock.Lock()
defer l.lock.Unlock()
if l.isClosed {
return errListenerClosed
}
// Similarly to LISTEN, this is not an error in Postgres, but it seems
// useful to distinguish from the normal conditions.
_, exists := l.channels[channel]
if !exists {
return ErrChannelNotOpen
}
if l.cn != nil {
// Similarly to Listen (see comment in that function), the caller
// should only be bothered with an error if it came from the backend as
// a response to our query.
gotResponse, err := l.cn.Unlisten(channel)
if gotResponse && err != nil {
return err
}
}
// Don't bother waiting for resync if there's no connection.
delete(l.channels, channel)
return nil
}
// UnlistenAll removes all channels from the Listener's channel list. Returns
// immediately with no error if there is no connection. Note that you might
// still get notifications for any of the deleted channels even after
// UnlistenAll has returned.
func (l *Listener) UnlistenAll() error {
l.lock.Lock()
defer l.lock.Unlock()
if l.isClosed {
return errListenerClosed
}
if l.cn != nil {
// Similarly to Listen (see comment in that function), the caller
// should only be bothered with an error if it came from the backend as
// a response to our query.
gotResponse, err := l.cn.UnlistenAll()
if gotResponse && err != nil {
return err
}
}
// Don't bother waiting for resync if there's no connection.
l.channels = make(map[string]struct{})
return nil
}
// Ping the remote server to make sure it's alive. Non-nil return value means
// that there is no active connection.
func (l *Listener) Ping() error {
l.lock.Lock()
defer l.lock.Unlock()
if l.isClosed {
return errListenerClosed
}
if l.cn == nil {
return errors.New("no connection")
}
return l.cn.Ping()
}
// Clean up after losing the server connection. Returns l.cn.Err(), which
// should have the reason the connection was lost.
func (l *Listener) disconnectCleanup() error {
l.lock.Lock()
defer l.lock.Unlock()
// sanity check; can't look at Err() until the channel has been closed
select {
case _, ok := <-l.connNotificationChan:
if ok {
panic("connNotificationChan not closed")
}
default:
panic("connNotificationChan not closed")
}
err := l.cn.Err()
l.cn.Close()
l.cn = nil
return err
}
// Synchronize the list of channels we want to be listening on with the server
// after the connection has been established.
func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error {
doneChan := make(chan error)
go func(notificationChan <-chan *Notification) {
for channel := range l.channels {
// If we got a response, return that error to our caller as it's
// going to be more descriptive than cn.Err().
gotResponse, err := cn.Listen(channel)
if gotResponse && err != nil {
doneChan <- err
return
}
// If we couldn't reach the server, wait for notificationChan to
// close and then return the error message from the connection, as
// per ListenerConn's interface.
if err != nil {
for range notificationChan {
}
doneChan <- cn.Err()
return
}
}
doneChan <- nil
}(notificationChan)
// Ignore notifications while synchronization is going on to avoid
// deadlocks. We have to send a nil notification over Notify anyway as
// we can't possibly know which notifications (if any) were lost while
// the connection was down, so there's no reason to try and process
// these messages at all.
for {
select {
case _, ok := <-notificationChan:
if !ok {
notificationChan = nil
}
case err := <-doneChan:
return err
}
}
}
// caller should NOT be holding l.lock
func (l *Listener) closed() bool {
l.lock.Lock()
defer l.lock.Unlock()
return l.isClosed
}
func (l *Listener) connect() error {
notificationChan := make(chan *Notification, 32)
cn, err := newDialListenerConn(l.dialer, l.name, notificationChan)
if err != nil {
return err
}
l.lock.Lock()
defer l.lock.Unlock()
err = l.resync(cn, notificationChan)
if err != nil {
cn.Close()
return err
}
l.cn = cn
l.connNotificationChan = notificationChan
l.reconnectCond.Broadcast()
return nil
}
// Close disconnects the Listener from the database and shuts it down.
// Subsequent calls to its methods will return an error. Close returns an
// error if the connection has already been closed.
func (l *Listener) Close() error {
l.lock.Lock()
defer l.lock.Unlock()
if l.isClosed {
return errListenerClosed
}
if l.cn != nil {
l.cn.Close()
}
l.isClosed = true
// Unblock calls to Listen()
l.reconnectCond.Broadcast()
return nil
}
func (l *Listener) emitEvent(event ListenerEventType, err error) {
if l.eventCallback != nil {
l.eventCallback(event, err)
}
}
// Main logic here: maintain a connection to the server when possible, wait
// for notifications and emit events.
func (l *Listener) listenerConnLoop() {
var nextReconnect time.Time
reconnectInterval := l.minReconnectInterval
for {
for {
err := l.connect()
if err == nil {
break
}
if l.closed() {
return
}
l.emitEvent(ListenerEventConnectionAttemptFailed, err)
time.Sleep(reconnectInterval)
reconnectInterval *= 2
if reconnectInterval > l.maxReconnectInterval {
reconnectInterval = l.maxReconnectInterval
}
}
if nextReconnect.IsZero() {
l.emitEvent(ListenerEventConnected, nil)
} else {
l.emitEvent(ListenerEventReconnected, nil)
l.Notify <- nil
}
reconnectInterval = l.minReconnectInterval
nextReconnect = time.Now().Add(reconnectInterval)
for {
notification, ok := <-l.connNotificationChan
if !ok {
// lost connection, loop again
break
}
l.Notify <- notification
}
err := l.disconnectCleanup()
if l.closed() {
return
}
l.emitEvent(ListenerEventDisconnected, err)
time.Sleep(time.Until(nextReconnect))
}
}
func (l *Listener) listenerMain() {
l.listenerConnLoop()
close(l.Notify)
}

6
vendor/github.com/lib/pq/oid/doc.go generated vendored Normal file
View file

@ -0,0 +1,6 @@
// Package oid contains OID constants
// as defined by the Postgres server.
package oid
// Oid is a Postgres Object ID.
type Oid uint32

343
vendor/github.com/lib/pq/oid/types.go generated vendored Normal file
View file

@ -0,0 +1,343 @@
// Code generated by gen.go. DO NOT EDIT.
package oid
const (
T_bool Oid = 16
T_bytea Oid = 17
T_char Oid = 18
T_name Oid = 19
T_int8 Oid = 20
T_int2 Oid = 21
T_int2vector Oid = 22
T_int4 Oid = 23
T_regproc Oid = 24
T_text Oid = 25
T_oid Oid = 26
T_tid Oid = 27
T_xid Oid = 28
T_cid Oid = 29
T_oidvector Oid = 30
T_pg_ddl_command Oid = 32
T_pg_type Oid = 71
T_pg_attribute Oid = 75
T_pg_proc Oid = 81
T_pg_class Oid = 83
T_json Oid = 114
T_xml Oid = 142
T__xml Oid = 143
T_pg_node_tree Oid = 194
T__json Oid = 199
T_smgr Oid = 210
T_index_am_handler Oid = 325
T_point Oid = 600
T_lseg Oid = 601
T_path Oid = 602
T_box Oid = 603
T_polygon Oid = 604
T_line Oid = 628
T__line Oid = 629
T_cidr Oid = 650
T__cidr Oid = 651
T_float4 Oid = 700
T_float8 Oid = 701
T_abstime Oid = 702
T_reltime Oid = 703
T_tinterval Oid = 704
T_unknown Oid = 705
T_circle Oid = 718
T__circle Oid = 719
T_money Oid = 790
T__money Oid = 791
T_macaddr Oid = 829
T_inet Oid = 869
T__bool Oid = 1000
T__bytea Oid = 1001
T__char Oid = 1002
T__name Oid = 1003
T__int2 Oid = 1005
T__int2vector Oid = 1006
T__int4 Oid = 1007
T__regproc Oid = 1008
T__text Oid = 1009
T__tid Oid = 1010
T__xid Oid = 1011
T__cid Oid = 1012
T__oidvector Oid = 1013
T__bpchar Oid = 1014
T__varchar Oid = 1015
T__int8 Oid = 1016
T__point Oid = 1017
T__lseg Oid = 1018
T__path Oid = 1019
T__box Oid = 1020
T__float4 Oid = 1021
T__float8 Oid = 1022
T__abstime Oid = 1023
T__reltime Oid = 1024
T__tinterval Oid = 1025
T__polygon Oid = 1027
T__oid Oid = 1028
T_aclitem Oid = 1033
T__aclitem Oid = 1034
T__macaddr Oid = 1040
T__inet Oid = 1041
T_bpchar Oid = 1042
T_varchar Oid = 1043
T_date Oid = 1082
T_time Oid = 1083
T_timestamp Oid = 1114
T__timestamp Oid = 1115
T__date Oid = 1182
T__time Oid = 1183
T_timestamptz Oid = 1184
T__timestamptz Oid = 1185
T_interval Oid = 1186
T__interval Oid = 1187
T__numeric Oid = 1231
T_pg_database Oid = 1248
T__cstring Oid = 1263
T_timetz Oid = 1266
T__timetz Oid = 1270
T_bit Oid = 1560
T__bit Oid = 1561
T_varbit Oid = 1562
T__varbit Oid = 1563
T_numeric Oid = 1700
T_refcursor Oid = 1790
T__refcursor Oid = 2201
T_regprocedure Oid = 2202
T_regoper Oid = 2203
T_regoperator Oid = 2204
T_regclass Oid = 2205
T_regtype Oid = 2206
T__regprocedure Oid = 2207
T__regoper Oid = 2208
T__regoperator Oid = 2209
T__regclass Oid = 2210
T__regtype Oid = 2211
T_record Oid = 2249
T_cstring Oid = 2275
T_any Oid = 2276
T_anyarray Oid = 2277
T_void Oid = 2278
T_trigger Oid = 2279
T_language_handler Oid = 2280
T_internal Oid = 2281
T_opaque Oid = 2282
T_anyelement Oid = 2283
T__record Oid = 2287
T_anynonarray Oid = 2776
T_pg_authid Oid = 2842
T_pg_auth_members Oid = 2843
T__txid_snapshot Oid = 2949
T_uuid Oid = 2950
T__uuid Oid = 2951
T_txid_snapshot Oid = 2970
T_fdw_handler Oid = 3115
T_pg_lsn Oid = 3220
T__pg_lsn Oid = 3221
T_tsm_handler Oid = 3310
T_anyenum Oid = 3500
T_tsvector Oid = 3614
T_tsquery Oid = 3615
T_gtsvector Oid = 3642
T__tsvector Oid = 3643
T__gtsvector Oid = 3644
T__tsquery Oid = 3645
T_regconfig Oid = 3734
T__regconfig Oid = 3735
T_regdictionary Oid = 3769
T__regdictionary Oid = 3770
T_jsonb Oid = 3802
T__jsonb Oid = 3807
T_anyrange Oid = 3831
T_event_trigger Oid = 3838
T_int4range Oid = 3904
T__int4range Oid = 3905
T_numrange Oid = 3906
T__numrange Oid = 3907
T_tsrange Oid = 3908
T__tsrange Oid = 3909
T_tstzrange Oid = 3910
T__tstzrange Oid = 3911
T_daterange Oid = 3912
T__daterange Oid = 3913
T_int8range Oid = 3926
T__int8range Oid = 3927
T_pg_shseclabel Oid = 4066
T_regnamespace Oid = 4089
T__regnamespace Oid = 4090
T_regrole Oid = 4096
T__regrole Oid = 4097
)
var TypeName = map[Oid]string{
T_bool: "BOOL",
T_bytea: "BYTEA",
T_char: "CHAR",
T_name: "NAME",
T_int8: "INT8",
T_int2: "INT2",
T_int2vector: "INT2VECTOR",
T_int4: "INT4",
T_regproc: "REGPROC",
T_text: "TEXT",
T_oid: "OID",
T_tid: "TID",
T_xid: "XID",
T_cid: "CID",
T_oidvector: "OIDVECTOR",
T_pg_ddl_command: "PG_DDL_COMMAND",
T_pg_type: "PG_TYPE",
T_pg_attribute: "PG_ATTRIBUTE",
T_pg_proc: "PG_PROC",
T_pg_class: "PG_CLASS",
T_json: "JSON",
T_xml: "XML",
T__xml: "_XML",
T_pg_node_tree: "PG_NODE_TREE",
T__json: "_JSON",
T_smgr: "SMGR",
T_index_am_handler: "INDEX_AM_HANDLER",
T_point: "POINT",
T_lseg: "LSEG",
T_path: "PATH",
T_box: "BOX",
T_polygon: "POLYGON",
T_line: "LINE",
T__line: "_LINE",
T_cidr: "CIDR",
T__cidr: "_CIDR",
T_float4: "FLOAT4",
T_float8: "FLOAT8",
T_abstime: "ABSTIME",
T_reltime: "RELTIME",
T_tinterval: "TINTERVAL",
T_unknown: "UNKNOWN",
T_circle: "CIRCLE",
T__circle: "_CIRCLE",
T_money: "MONEY",
T__money: "_MONEY",
T_macaddr: "MACADDR",
T_inet: "INET",
T__bool: "_BOOL",
T__bytea: "_BYTEA",
T__char: "_CHAR",
T__name: "_NAME",
T__int2: "_INT2",
T__int2vector: "_INT2VECTOR",
T__int4: "_INT4",
T__regproc: "_REGPROC",
T__text: "_TEXT",
T__tid: "_TID",
T__xid: "_XID",
T__cid: "_CID",
T__oidvector: "_OIDVECTOR",
T__bpchar: "_BPCHAR",
T__varchar: "_VARCHAR",
T__int8: "_INT8",
T__point: "_POINT",
T__lseg: "_LSEG",
T__path: "_PATH",
T__box: "_BOX",
T__float4: "_FLOAT4",
T__float8: "_FLOAT8",
T__abstime: "_ABSTIME",
T__reltime: "_RELTIME",
T__tinterval: "_TINTERVAL",
T__polygon: "_POLYGON",
T__oid: "_OID",
T_aclitem: "ACLITEM",
T__aclitem: "_ACLITEM",
T__macaddr: "_MACADDR",
T__inet: "_INET",
T_bpchar: "BPCHAR",
T_varchar: "VARCHAR",
T_date: "DATE",
T_time: "TIME",
T_timestamp: "TIMESTAMP",
T__timestamp: "_TIMESTAMP",
T__date: "_DATE",
T__time: "_TIME",
T_timestamptz: "TIMESTAMPTZ",
T__timestamptz: "_TIMESTAMPTZ",
T_interval: "INTERVAL",
T__interval: "_INTERVAL",
T__numeric: "_NUMERIC",
T_pg_database: "PG_DATABASE",
T__cstring: "_CSTRING",
T_timetz: "TIMETZ",
T__timetz: "_TIMETZ",
T_bit: "BIT",
T__bit: "_BIT",
T_varbit: "VARBIT",
T__varbit: "_VARBIT",
T_numeric: "NUMERIC",
T_refcursor: "REFCURSOR",
T__refcursor: "_REFCURSOR",
T_regprocedure: "REGPROCEDURE",
T_regoper: "REGOPER",
T_regoperator: "REGOPERATOR",
T_regclass: "REGCLASS",
T_regtype: "REGTYPE",
T__regprocedure: "_REGPROCEDURE",
T__regoper: "_REGOPER",
T__regoperator: "_REGOPERATOR",
T__regclass: "_REGCLASS",
T__regtype: "_REGTYPE",
T_record: "RECORD",
T_cstring: "CSTRING",
T_any: "ANY",
T_anyarray: "ANYARRAY",
T_void: "VOID",
T_trigger: "TRIGGER",
T_language_handler: "LANGUAGE_HANDLER",
T_internal: "INTERNAL",
T_opaque: "OPAQUE",
T_anyelement: "ANYELEMENT",
T__record: "_RECORD",
T_anynonarray: "ANYNONARRAY",
T_pg_authid: "PG_AUTHID",
T_pg_auth_members: "PG_AUTH_MEMBERS",
T__txid_snapshot: "_TXID_SNAPSHOT",
T_uuid: "UUID",
T__uuid: "_UUID",
T_txid_snapshot: "TXID_SNAPSHOT",
T_fdw_handler: "FDW_HANDLER",
T_pg_lsn: "PG_LSN",
T__pg_lsn: "_PG_LSN",
T_tsm_handler: "TSM_HANDLER",
T_anyenum: "ANYENUM",
T_tsvector: "TSVECTOR",
T_tsquery: "TSQUERY",
T_gtsvector: "GTSVECTOR",
T__tsvector: "_TSVECTOR",
T__gtsvector: "_GTSVECTOR",
T__tsquery: "_TSQUERY",
T_regconfig: "REGCONFIG",
T__regconfig: "_REGCONFIG",
T_regdictionary: "REGDICTIONARY",
T__regdictionary: "_REGDICTIONARY",
T_jsonb: "JSONB",
T__jsonb: "_JSONB",
T_anyrange: "ANYRANGE",
T_event_trigger: "EVENT_TRIGGER",
T_int4range: "INT4RANGE",
T__int4range: "_INT4RANGE",
T_numrange: "NUMRANGE",
T__numrange: "_NUMRANGE",
T_tsrange: "TSRANGE",
T__tsrange: "_TSRANGE",
T_tstzrange: "TSTZRANGE",
T__tstzrange: "_TSTZRANGE",
T_daterange: "DATERANGE",
T__daterange: "_DATERANGE",
T_int8range: "INT8RANGE",
T__int8range: "_INT8RANGE",
T_pg_shseclabel: "PG_SHSECLABEL",
T_regnamespace: "REGNAMESPACE",
T__regnamespace: "_REGNAMESPACE",
T_regrole: "REGROLE",
T__regrole: "_REGROLE",
}

93
vendor/github.com/lib/pq/rows.go generated vendored Normal file
View file

@ -0,0 +1,93 @@
package pq
import (
"math"
"reflect"
"time"
"github.com/lib/pq/oid"
)
const headerSize = 4
type fieldDesc struct {
// The object ID of the data type.
OID oid.Oid
// The data type size (see pg_type.typlen).
// Note that negative values denote variable-width types.
Len int
// The type modifier (see pg_attribute.atttypmod).
// The meaning of the modifier is type-specific.
Mod int
}
func (fd fieldDesc) Type() reflect.Type {
switch fd.OID {
case oid.T_int8:
return reflect.TypeOf(int64(0))
case oid.T_int4:
return reflect.TypeOf(int32(0))
case oid.T_int2:
return reflect.TypeOf(int16(0))
case oid.T_varchar, oid.T_text:
return reflect.TypeOf("")
case oid.T_bool:
return reflect.TypeOf(false)
case oid.T_date, oid.T_time, oid.T_timetz, oid.T_timestamp, oid.T_timestamptz:
return reflect.TypeOf(time.Time{})
case oid.T_bytea:
return reflect.TypeOf([]byte(nil))
default:
return reflect.TypeOf(new(interface{})).Elem()
}
}
func (fd fieldDesc) Name() string {
return oid.TypeName[fd.OID]
}
func (fd fieldDesc) Length() (length int64, ok bool) {
switch fd.OID {
case oid.T_text, oid.T_bytea:
return math.MaxInt64, true
case oid.T_varchar, oid.T_bpchar:
return int64(fd.Mod - headerSize), true
default:
return 0, false
}
}
func (fd fieldDesc) PrecisionScale() (precision, scale int64, ok bool) {
switch fd.OID {
case oid.T_numeric, oid.T__numeric:
mod := fd.Mod - headerSize
precision = int64((mod >> 16) & 0xffff)
scale = int64(mod & 0xffff)
return precision, scale, true
default:
return 0, 0, false
}
}
// ColumnTypeScanType returns the value type that can be used to scan types into.
func (rs *rows) ColumnTypeScanType(index int) reflect.Type {
return rs.colTyps[index].Type()
}
// ColumnTypeDatabaseTypeName return the database system type name.
func (rs *rows) ColumnTypeDatabaseTypeName(index int) string {
return rs.colTyps[index].Name()
}
// ColumnTypeLength returns the length of the column type if the column is a
// variable length type. If the column is not a variable length type ok
// should return false.
func (rs *rows) ColumnTypeLength(index int) (length int64, ok bool) {
return rs.colTyps[index].Length()
}
// ColumnTypePrecisionScale should return the precision and scale for decimal
// types. If not applicable, ok should be false.
func (rs *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
return rs.colTyps[index].PrecisionScale()
}

264
vendor/github.com/lib/pq/scram/scram.go generated vendored Normal file
View file

@ -0,0 +1,264 @@
// Copyright (c) 2014 - Gustavo Niemeyer <gustavo@niemeyer.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802.
//
// http://tools.ietf.org/html/rfc5802
//
package scram
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"encoding/base64"
"fmt"
"hash"
"strconv"
"strings"
)
// Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc).
//
// A Client may be used within a SASL conversation with logic resembling:
//
// var in []byte
// var client = scram.NewClient(sha1.New, user, pass)
// for client.Step(in) {
// out := client.Out()
// // send out to server
// in := serverOut
// }
// if client.Err() != nil {
// // auth failed
// }
//
type Client struct {
newHash func() hash.Hash
user string
pass string
step int
out bytes.Buffer
err error
clientNonce []byte
serverNonce []byte
saltedPass []byte
authMsg bytes.Buffer
}
// NewClient returns a new SCRAM-* client with the provided hash algorithm.
//
// For SCRAM-SHA-256, for example, use:
//
// client := scram.NewClient(sha256.New, user, pass)
//
func NewClient(newHash func() hash.Hash, user, pass string) *Client {
c := &Client{
newHash: newHash,
user: user,
pass: pass,
}
c.out.Grow(256)
c.authMsg.Grow(256)
return c
}
// Out returns the data to be sent to the server in the current step.
func (c *Client) Out() []byte {
if c.out.Len() == 0 {
return nil
}
return c.out.Bytes()
}
// Err returns the error that occurred, or nil if there were no errors.
func (c *Client) Err() error {
return c.err
}
// SetNonce sets the client nonce to the provided value.
// If not set, the nonce is generated automatically out of crypto/rand on the first step.
func (c *Client) SetNonce(nonce []byte) {
c.clientNonce = nonce
}
var escaper = strings.NewReplacer("=", "=3D", ",", "=2C")
// Step processes the incoming data from the server and makes the
// next round of data for the server available via Client.Out.
// Step returns false if there are no errors and more data is
// still expected.
func (c *Client) Step(in []byte) bool {
c.out.Reset()
if c.step > 2 || c.err != nil {
return false
}
c.step++
switch c.step {
case 1:
c.err = c.step1(in)
case 2:
c.err = c.step2(in)
case 3:
c.err = c.step3(in)
}
return c.step > 2 || c.err != nil
}
func (c *Client) step1(in []byte) error {
if len(c.clientNonce) == 0 {
const nonceLen = 16
buf := make([]byte, nonceLen+b64.EncodedLen(nonceLen))
if _, err := rand.Read(buf[:nonceLen]); err != nil {
return fmt.Errorf("cannot read random SCRAM-SHA-256 nonce from operating system: %v", err)
}
c.clientNonce = buf[nonceLen:]
b64.Encode(c.clientNonce, buf[:nonceLen])
}
c.authMsg.WriteString("n=")
escaper.WriteString(&c.authMsg, c.user)
c.authMsg.WriteString(",r=")
c.authMsg.Write(c.clientNonce)
c.out.WriteString("n,,")
c.out.Write(c.authMsg.Bytes())
return nil
}
var b64 = base64.StdEncoding
func (c *Client) step2(in []byte) error {
c.authMsg.WriteByte(',')
c.authMsg.Write(in)
fields := bytes.Split(in, []byte(","))
if len(fields) != 3 {
return fmt.Errorf("expected 3 fields in first SCRAM-SHA-256 server message, got %d: %q", len(fields), in)
}
if !bytes.HasPrefix(fields[0], []byte("r=")) || len(fields[0]) < 2 {
return fmt.Errorf("server sent an invalid SCRAM-SHA-256 nonce: %q", fields[0])
}
if !bytes.HasPrefix(fields[1], []byte("s=")) || len(fields[1]) < 6 {
return fmt.Errorf("server sent an invalid SCRAM-SHA-256 salt: %q", fields[1])
}
if !bytes.HasPrefix(fields[2], []byte("i=")) || len(fields[2]) < 6 {
return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2])
}
c.serverNonce = fields[0][2:]
if !bytes.HasPrefix(c.serverNonce, c.clientNonce) {
return fmt.Errorf("server SCRAM-SHA-256 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", c.serverNonce, c.clientNonce)
}
salt := make([]byte, b64.DecodedLen(len(fields[1][2:])))
n, err := b64.Decode(salt, fields[1][2:])
if err != nil {
return fmt.Errorf("cannot decode SCRAM-SHA-256 salt sent by server: %q", fields[1])
}
salt = salt[:n]
iterCount, err := strconv.Atoi(string(fields[2][2:]))
if err != nil {
return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2])
}
c.saltPassword(salt, iterCount)
c.authMsg.WriteString(",c=biws,r=")
c.authMsg.Write(c.serverNonce)
c.out.WriteString("c=biws,r=")
c.out.Write(c.serverNonce)
c.out.WriteString(",p=")
c.out.Write(c.clientProof())
return nil
}
func (c *Client) step3(in []byte) error {
var isv, ise bool
var fields = bytes.Split(in, []byte(","))
if len(fields) == 1 {
isv = bytes.HasPrefix(fields[0], []byte("v="))
ise = bytes.HasPrefix(fields[0], []byte("e="))
}
if ise {
return fmt.Errorf("SCRAM-SHA-256 authentication error: %s", fields[0][2:])
} else if !isv {
return fmt.Errorf("unsupported SCRAM-SHA-256 final message from server: %q", in)
}
if !bytes.Equal(c.serverSignature(), fields[0][2:]) {
return fmt.Errorf("cannot authenticate SCRAM-SHA-256 server signature: %q", fields[0][2:])
}
return nil
}
func (c *Client) saltPassword(salt []byte, iterCount int) {
mac := hmac.New(c.newHash, []byte(c.pass))
mac.Write(salt)
mac.Write([]byte{0, 0, 0, 1})
ui := mac.Sum(nil)
hi := make([]byte, len(ui))
copy(hi, ui)
for i := 1; i < iterCount; i++ {
mac.Reset()
mac.Write(ui)
mac.Sum(ui[:0])
for j, b := range ui {
hi[j] ^= b
}
}
c.saltedPass = hi
}
func (c *Client) clientProof() []byte {
mac := hmac.New(c.newHash, c.saltedPass)
mac.Write([]byte("Client Key"))
clientKey := mac.Sum(nil)
hash := c.newHash()
hash.Write(clientKey)
storedKey := hash.Sum(nil)
mac = hmac.New(c.newHash, storedKey)
mac.Write(c.authMsg.Bytes())
clientProof := mac.Sum(nil)
for i, b := range clientKey {
clientProof[i] ^= b
}
clientProof64 := make([]byte, b64.EncodedLen(len(clientProof)))
b64.Encode(clientProof64, clientProof)
return clientProof64
}
func (c *Client) serverSignature() []byte {
mac := hmac.New(c.newHash, c.saltedPass)
mac.Write([]byte("Server Key"))
serverKey := mac.Sum(nil)
mac = hmac.New(c.newHash, serverKey)
mac.Write(c.authMsg.Bytes())
serverSignature := mac.Sum(nil)
encoded := make([]byte, b64.EncodedLen(len(serverSignature)))
b64.Encode(encoded, serverSignature)
return encoded
}

175
vendor/github.com/lib/pq/ssl.go generated vendored Normal file
View file

@ -0,0 +1,175 @@
package pq
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"net"
"os"
"os/user"
"path/filepath"
)
// ssl generates a function to upgrade a net.Conn based on the "sslmode" and
// related settings. The function is nil when no upgrade should take place.
func ssl(o values) (func(net.Conn) (net.Conn, error), error) {
verifyCaOnly := false
tlsConf := tls.Config{}
switch mode := o["sslmode"]; mode {
// "require" is the default.
case "", "require":
// We must skip TLS's own verification since it requires full
// verification since Go 1.3.
tlsConf.InsecureSkipVerify = true
// From http://www.postgresql.org/docs/current/static/libpq-ssl.html:
//
// Note: For backwards compatibility with earlier versions of
// PostgreSQL, if a root CA file exists, the behavior of
// sslmode=require will be the same as that of verify-ca, meaning the
// server certificate is validated against the CA. Relying on this
// behavior is discouraged, and applications that need certificate
// validation should always use verify-ca or verify-full.
if sslrootcert, ok := o["sslrootcert"]; ok {
if _, err := os.Stat(sslrootcert); err == nil {
verifyCaOnly = true
} else {
delete(o, "sslrootcert")
}
}
case "verify-ca":
// We must skip TLS's own verification since it requires full
// verification since Go 1.3.
tlsConf.InsecureSkipVerify = true
verifyCaOnly = true
case "verify-full":
tlsConf.ServerName = o["host"]
case "disable":
return nil, nil
default:
return nil, fmterrorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode)
}
err := sslClientCertificates(&tlsConf, o)
if err != nil {
return nil, err
}
err = sslCertificateAuthority(&tlsConf, o)
if err != nil {
return nil, err
}
// Accept renegotiation requests initiated by the backend.
//
// Renegotiation was deprecated then removed from PostgreSQL 9.5, but
// the default configuration of older versions has it enabled. Redshift
// also initiates renegotiations and cannot be reconfigured.
tlsConf.Renegotiation = tls.RenegotiateFreelyAsClient
return func(conn net.Conn) (net.Conn, error) {
client := tls.Client(conn, &tlsConf)
if verifyCaOnly {
err := sslVerifyCertificateAuthority(client, &tlsConf)
if err != nil {
return nil, err
}
}
return client, nil
}, nil
}
// sslClientCertificates adds the certificate specified in the "sslcert" and
// "sslkey" settings, or if they aren't set, from the .postgresql directory
// in the user's home directory. The configured files must exist and have
// the correct permissions.
func sslClientCertificates(tlsConf *tls.Config, o values) error {
// user.Current() might fail when cross-compiling. We have to ignore the
// error and continue without home directory defaults, since we wouldn't
// know from where to load them.
user, _ := user.Current()
// In libpq, the client certificate is only loaded if the setting is not blank.
//
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1036-L1037
sslcert := o["sslcert"]
if len(sslcert) == 0 && user != nil {
sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
}
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045
if len(sslcert) == 0 {
return nil
}
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054
if _, err := os.Stat(sslcert); os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
// In libpq, the ssl key is only loaded if the setting is not blank.
//
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1123-L1222
sslkey := o["sslkey"]
if len(sslkey) == 0 && user != nil {
sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
}
if len(sslkey) > 0 {
if err := sslKeyPermissions(sslkey); err != nil {
return err
}
}
cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
if err != nil {
return err
}
tlsConf.Certificates = []tls.Certificate{cert}
return nil
}
// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting.
func sslCertificateAuthority(tlsConf *tls.Config, o values) error {
// In libpq, the root certificate is only loaded if the setting is not blank.
//
// https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951
if sslrootcert := o["sslrootcert"]; len(sslrootcert) > 0 {
tlsConf.RootCAs = x509.NewCertPool()
cert, err := ioutil.ReadFile(sslrootcert)
if err != nil {
return err
}
if !tlsConf.RootCAs.AppendCertsFromPEM(cert) {
return fmterrorf("couldn't parse pem in sslrootcert")
}
}
return nil
}
// sslVerifyCertificateAuthority carries out a TLS handshake to the server and
// verifies the presented certificate against the CA, i.e. the one specified in
// sslrootcert or the system CA if sslrootcert was not specified.
func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) error {
err := client.Handshake()
if err != nil {
return err
}
certs := client.ConnectionState().PeerCertificates
opts := x509.VerifyOptions{
DNSName: client.ConnectionState().ServerName,
Intermediates: x509.NewCertPool(),
Roots: tlsConf.RootCAs,
}
for i, cert := range certs {
if i == 0 {
continue
}
opts.Intermediates.AddCert(cert)
}
_, err = certs[0].Verify(opts)
return err
}

20
vendor/github.com/lib/pq/ssl_permissions.go generated vendored Normal file
View file

@ -0,0 +1,20 @@
// +build !windows
package pq
import "os"
// sslKeyPermissions checks the permissions on user-supplied ssl key files.
// The key file should have very little access.
//
// libpq does not check key file permissions on Windows.
func sslKeyPermissions(sslkey string) error {
info, err := os.Stat(sslkey)
if err != nil {
return err
}
if info.Mode().Perm()&0077 != 0 {
return ErrSSLKeyHasWorldPermissions
}
return nil
}

9
vendor/github.com/lib/pq/ssl_windows.go generated vendored Normal file
View file

@ -0,0 +1,9 @@
// +build windows
package pq
// sslKeyPermissions checks the permissions on user-supplied ssl key files.
// The key file should have very little access.
//
// libpq does not check key file permissions on Windows.
func sslKeyPermissions(string) error { return nil }

76
vendor/github.com/lib/pq/url.go generated vendored Normal file
View file

@ -0,0 +1,76 @@
package pq
import (
"fmt"
"net"
nurl "net/url"
"sort"
"strings"
)
// ParseURL no longer needs to be used by clients of this library since supplying a URL as a
// connection string to sql.Open() is now supported:
//
// sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full")
//
// It remains exported here for backwards-compatibility.
//
// ParseURL converts a url to a connection string for driver.Open.
// Example:
//
// "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full"
//
// converts to:
//
// "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full"
//
// A minimal example:
//
// "postgres://"
//
// This will be blank, causing driver.Open to use all of the defaults
func ParseURL(url string) (string, error) {
u, err := nurl.Parse(url)
if err != nil {
return "", err
}
if u.Scheme != "postgres" && u.Scheme != "postgresql" {
return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme)
}
var kvs []string
escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
accrue := func(k, v string) {
if v != "" {
kvs = append(kvs, k+"="+escaper.Replace(v))
}
}
if u.User != nil {
v := u.User.Username()
accrue("user", v)
v, _ = u.User.Password()
accrue("password", v)
}
if host, port, err := net.SplitHostPort(u.Host); err != nil {
accrue("host", u.Host)
} else {
accrue("host", host)
accrue("port", port)
}
if u.Path != "" {
accrue("dbname", u.Path[1:])
}
q := u.Query()
for k := range q {
accrue(k, q.Get(k))
}
sort.Strings(kvs) // Makes testing easier (not a performance concern)
return strings.Join(kvs, " "), nil
}

24
vendor/github.com/lib/pq/user_posix.go generated vendored Normal file
View file

@ -0,0 +1,24 @@
// Package pq is a pure Go Postgres driver for the database/sql package.
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris rumprun
package pq
import (
"os"
"os/user"
)
func userCurrent() (string, error) {
u, err := user.Current()
if err == nil {
return u.Username, nil
}
name := os.Getenv("USER")
if name != "" {
return name, nil
}
return "", ErrCouldNotDetectUsername
}

27
vendor/github.com/lib/pq/user_windows.go generated vendored Normal file
View file

@ -0,0 +1,27 @@
// Package pq is a pure Go Postgres driver for the database/sql package.
package pq
import (
"path/filepath"
"syscall"
)
// Perform Windows user name lookup identically to libpq.
//
// The PostgreSQL code makes use of the legacy Win32 function
// GetUserName, and that function has not been imported into stock Go.
// GetUserNameEx is available though, the difference being that a
// wider range of names are available. To get the output to be the
// same as GetUserName, only the base (or last) component of the
// result is returned.
func userCurrent() (string, error) {
pw_name := make([]uint16, 128)
pwname_size := uint32(len(pw_name)) - 1
err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size)
if err != nil {
return "", ErrCouldNotDetectUsername
}
s := syscall.UTF16ToString(pw_name)
u := filepath.Base(s)
return u, nil
}

23
vendor/github.com/lib/pq/uuid.go generated vendored Normal file
View file

@ -0,0 +1,23 @@
package pq
import (
"encoding/hex"
"fmt"
)
// decodeUUIDBinary interprets the binary format of a uuid, returning it in text format.
func decodeUUIDBinary(src []byte) ([]byte, error) {
if len(src) != 16 {
return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src))
}
dst := make([]byte, 36)
dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-'
hex.Encode(dst[0:], src[0:4])
hex.Encode(dst[9:], src[4:6])
hex.Encode(dst[14:], src[6:8])
hex.Encode(dst[19:], src[8:10])
hex.Encode(dst[24:], src[10:16])
return dst, nil
}

62
vendor/github.com/stripe/stripe-go/.travis.yml generated vendored Normal file
View file

@ -0,0 +1,62 @@
before_install:
# Install various build dependencies. We use `travis_retry` because `go get`
# will occasionally fail intermittently.
# The testify require framework is used for assertions in the test suite
- travis_retry go get -u github.com/stretchr/testify/require
# Install lint / code coverage / coveralls tooling
- travis_retry go get -u golang.org/x/net/http2
- travis_retry go get -u golang.org/x/tools/cmd/cover
- travis_retry go get -u github.com/modocache/gover
- travis_retry go get -u github.com/mattn/goveralls
- travis_retry go get -u golang.org/x/lint/golint
# Unpack and start the Stripe API stub so that the test suite can talk to it
- |
if [ ! -d "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}" ]; then
mkdir -p stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}/
curl -L "https://github.com/stripe/stripe-mock/releases/download/v${STRIPE_MOCK_VERSION}/stripe-mock_${STRIPE_MOCK_VERSION}_linux_amd64.tar.gz" -o "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}_linux_amd64.tar.gz"
tar -zxf "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}_linux_amd64.tar.gz" -C "stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}/"
fi
- |
stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}/stripe-mock -https-port 12112 -strict-version-check > /dev/null &
STRIPE_MOCK_PID=$!
# stripe-mock must be in PATH for `scripts/test_with_stripe_mock.go` to work.
- export PATH="${PATH}:${PWD}/stripe-mock/stripe-mock_${STRIPE_MOCK_VERSION}"
cache:
directories:
- stripe-mock
env:
global:
# If changing this number, please also change it in `testing/testing.go`.
- STRIPE_MOCK_VERSION=0.83.0
go:
- "1.9.x"
- "1.10.x"
- "1.11.x"
- "1.12.x"
- tip
language: go
matrix:
allow_failures:
- go: tip
fast_finish: true
script:
- make
- make coverage
after_script:
# Merge all coverage reports located in subdirectories and put them under: gover.coverprofile
- gover
# Send code coverage report to coveralls.io
- goveralls -service=travis-ci -coverprofile=gover.coverprofile
sudo: false

1
vendor/github.com/stripe/stripe-go/CHANGELOG generated vendored Normal file
View file

@ -0,0 +1 @@
CHANGELOG has changed to be Markdown-formatted. Please see CHANGELOG.md.

1624
vendor/github.com/stripe/stripe-go/CHANGELOG.md generated vendored Normal file

File diff suppressed because it is too large Load diff

77
vendor/github.com/stripe/stripe-go/CODE_OF_CONDUCT.md generated vendored Normal file
View file

@ -0,0 +1,77 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at conduct@stripe.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

21
vendor/github.com/stripe/stripe-go/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014- Stripe, Inc. (https://stripe.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.

30
vendor/github.com/stripe/stripe-go/Makefile generated vendored Normal file
View file

@ -0,0 +1,30 @@
all: test bench vet lint check-api-clients check-gofmt
bench:
go test -race -bench . -run "Benchmark" ./form
build:
go build ./...
check-api-clients:
go run scripts/check_api_clients/main.go
check-gofmt:
scripts/check_gofmt.sh
lint:
golint -set_exit_status ./...
test:
go run scripts/test_with_stripe_mock/main.go -race ./...
vet:
go vet ./...
coverage:
# go currently cannot create coverage profiles when testing multiple packages, so we test each package
# independently. This issue should be fixed in Go 1.10 (https://github.com/golang/go/issues/6909).
go list ./... | xargs -n1 -I {} -P 4 go run scripts/test_with_stripe_mock/main.go -covermode=count -coverprofile=../../../{}/profile.coverprofile {}
clean:
find . -name \*.coverprofile -delete

428
vendor/github.com/stripe/stripe-go/README.md generated vendored Normal file
View file

@ -0,0 +1,428 @@
# Go Stripe
[![GoDoc](http://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/stripe/stripe-go)
[![Build Status](https://travis-ci.org/stripe/stripe-go.svg?branch=master)](https://travis-ci.org/stripe/stripe-go)
[![Coverage Status](https://coveralls.io/repos/github/stripe/stripe-go/badge.svg?branch=master)](https://coveralls.io/github/stripe/stripe-go?branch=master)
The official [Stripe][stripe] Go client library.
## Installation
Install stripe-go with:
```sh
go get -u github.com/stripe/stripe-go
```
Then, import it using:
``` go
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/customer"
)
```
### Go Module Support
The library currently *does not* ship with first-class support for Go
modules. We put in support for it before, but ran into compatibility problems
for existing installations using Dep (see discussion in [closer to the bottom
of this thread][gomodvsdep]), and [reverted support][gomodrevert]. Our current
plan is to wait for better module compatibility in Dep (see a [preliminary
patch here][depgomodsupport]), give the release a little grace time to become
more widely distributed, then bring support back.
For now, require stripe-go in `go.mod` with a version but without a *version
suffix* in the path like so:
``` go
module github.com/my/package
require (
github.com/stripe/stripe-go v70.5.0
)
```
And use the same style of import paths as above:
``` go
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/customer"
)
```
## Documentation
For a comprehensive list of examples, check out the [API
documentation][api-docs].
For details on all the functionality in this library, see the [GoDoc][godoc]
documentation.
Below are a few simple examples:
### Customers
```go
params := &stripe.CustomerParams{
Description: stripe.String("Stripe Developer"),
Email: stripe.String("gostripe@stripe.com"),
}
customer, err := customer.New(params)
```
### PaymentIntents
```go
params := &stripe.PaymentIntentListParams{
Customer: stripe.String(customer.ID),
}
// set this so you can easily retry your request in case of a timeout
params.Params.IdempotencyKey = stripe.NewIdempotencyKey()
i := paymentintent.List(params)
for i.Next() {
pi := i.PaymentIntent()
}
if err := i.Err(); err != nil {
// handle
}
```
### Events
```go
i := event.List(nil)
for i.Next() {
e := i.Event()
// access event data via e.GetObjectValue("resource_name_based_on_type", "resource_property_name")
// alternatively you can access values via e.Data.Object["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]
// access previous attributes via e.GetPreviousValue("resource_name_based_on_type", "resource_property_name")
// alternatively you can access values via e.Data.PrevPreviousAttributes["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]
}
```
Alternatively, you can use the `event.Data.Raw` property to unmarshal to the
appropriate struct.
### Authentication with Connect
There are two ways of authenticating requests when performing actions on behalf
of a connected account, one that uses the `Stripe-Account` header containing an
account's ID, and one that uses the account's keys. Usually the former is the
recommended approach. [See the documentation for more information][connect].
To use the `Stripe-Account` approach, use `SetStripeAccount()` on a `ListParams`
or `Params` class. For example:
```go
// For a list request
listParams := &stripe.CustomerListParams{}
listParams.SetStripeAccount("acct_123")
```
```go
// For any other kind of request
params := &stripe.CustomerParams{}
params.SetStripeAccount("acct_123")
```
To use a key, pass it to `API`'s `Init` function:
```go
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/client"
)
stripe := &client.API{}
stripe.Init("access_token", nil)
```
### Google AppEngine
If you're running the client in a Google AppEngine environment, you'll need to
create a per-request Stripe client since the `http.DefaultClient` is not
available. Here's a sample handler:
```go
import (
"fmt"
"net/http"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/client"
)
func handler(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
httpClient := urlfetch.Client(c)
sc := stripeClient.New("sk_test_123", stripe.NewBackends(httpClient))
params := &stripe.CustomerParams{
Description: stripe.String("Stripe Developer"),
Email: stripe.String("gostripe@stripe.com"),
}
customer, err := sc.Customers.New(params)
if err != nil {
fmt.Fprintf(w, "Could not create customer: %v", err)
}
fmt.Fprintf(w, "Customer created: %v", customer.ID)
}
```
## Usage
While some resources may contain more/less APIs, the following pattern is
applied throughout the library for a given `$resource$`:
### Without a Client
If you're only dealing with a single key, you can simply import the packages
required for the resources you're interacting with without the need to create a
client.
```go
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/$resource$"
)
// Setup
stripe.Key = "sk_key"
stripe.SetBackend("api", backend) // optional, useful for mocking
// Create
$resource$, err := $resource$.New(stripe.$Resource$Params)
// Get
$resource$, err := $resource$.Get(id, stripe.$Resource$Params)
// Update
$resource$, err := $resource$.Update(stripe.$Resource$Params)
// Delete
resourceDeleted, err := $resource$.Del(id, stripe.$Resource$Params)
// List
i := $resource$.List(stripe.$Resource$ListParams)
for i.Next() {
$resource$ := i.$Resource$()
}
if err := i.Err(); err != nil {
// handle
}
```
### With a Client
If you're dealing with multiple keys, it is recommended you use `client.API`.
This allows you to create as many clients as needed, each with their own
individual key.
```go
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/client"
)
// Setup
sc := &client.API{}
sc.Init("sk_key", nil) // the second parameter overrides the backends used if needed for mocking
// Create
$resource$, err := sc.$Resource$s.New(stripe.$Resource$Params)
// Get
$resource$, err := sc.$Resource$s.Get(id, stripe.$Resource$Params)
// Update
$resource$, err := sc.$Resource$s.Update(stripe.$Resource$Params)
// Delete
resourceDeleted, err := sc.$Resource$s.Del(id, stripe.$Resource$Params)
// List
i := sc.$Resource$s.List(stripe.$Resource$ListParams)
for i.Next() {
resource := i.$Resource$()
}
if err := i.Err(); err != nil {
// handle
}
```
### Configuring Automatic Retries
You can enable automatic retries on requests that fail due to a transient
problem by configuring the maximum number of retries:
```go
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/client"
)
config := &stripe.BackendConfig{
MaxNetworkRetries: 2,
}
sc := &client.API{}
sc.Init("sk_key", &stripe.Backends{
API: stripe.GetBackendWithConfig(stripe.APIBackend, config),
Uploads: stripe.GetBackendWithConfig(stripe.UploadsBackend, config),
})
coupon, err := sc.Coupons.New(...)
```
Various errors can trigger a retry, like a connection error or a timeout, and
also certain API responses like HTTP status `409 Conflict`.
[Idempotency keys][idempotency-keys] are added to requests to guarantee that
retries are safe.
### Configuring Logging
Configure logging using the global `DefaultLeveledLogger` variable:
```go
stripe.DefaultLeveledLogger = &stripe.LeveledLogger{
Level: stripe.LevelInfo,
}
```
Or on a per-backend basis:
```go
config := &stripe.BackendConfig{
LeveledLogger: &stripe.LeveledLogger{
Level: stripe.LevelInfo,
},
}
```
It's possible to use non-Stripe leveled loggers as well. Stripe expects loggers
to comply to the following interface:
```go
type LeveledLoggerInterface interface {
Debugf(format string, v ...interface{})
Errorf(format string, v ...interface{})
Infof(format string, v ...interface{})
Warnf(format string, v ...interface{})
}
```
Some loggers like [Logrus][logrus] and Zap's [SugaredLogger][zapsugaredlogger]
support this interface out-of-the-box so it's possible to set
`DefaultLeveledLogger` to a `*logrus.Logger` or `*zap.SugaredLogger` directly.
For others it may be necessary to write a thin shim layer to support them.
### Writing a Plugin
If you're writing a plugin that uses the library, we'd appreciate it if you
identified using `stripe.SetAppInfo`:
```go
stripe.SetAppInfo(&stripe.AppInfo{
Name: "MyAwesomePlugin",
URL: "https://myawesomeplugin.info",
Version: "1.2.34",
})
```
This information is passed along when the library makes calls to the Stripe
API. Note that while `Name` is always required, `URL` and `Version` are
optional.
### Request latency telemetry
By default, the library sends request latency telemetry to Stripe. These
numbers help Stripe improve the overall latency of its API for all users.
You can disable this behavior if you prefer:
```go
config := &stripe.BackendConfig{
EnableTelemetry: false,
}
```
## Development
Pull requests from the community are welcome. If you submit one, please keep
the following guidelines in mind:
1. Code must be `go fmt` compliant.
2. All types, structs and funcs should be documented.
3. Ensure that `make test` succeeds.
## Test
The test suite needs testify's `require` package to run:
github.com/stretchr/testify/require
Before running the tests, make sure to grab all of the package's dependencies:
go get -t -v
It also depends on [stripe-mock][stripe-mock], so make sure to fetch and run it from a
background terminal ([stripe-mock's README][stripe-mock-usage] also contains
instructions for installing via Homebrew and other methods):
go get -u github.com/stripe/stripe-mock
stripe-mock
Run all tests:
make test
Run tests for one package:
go test ./invoice
Run a single test:
go test ./invoice -run TestInvoiceGet
For any requests, bug or comments, please [open an issue][issues] or [submit a
pull request][pulls].
[api-docs]: https://stripe.com/docs/api/go
[api-changelog]: https://stripe.com/docs/upgrades
[connect]: https://stripe.com/docs/connect/authentication
[depgomodsupport]: https://github.com/golang/dep/pull/1963
[godoc]: http://godoc.org/github.com/stripe/stripe-go
[gomodrevert]: https://github.com/stripe/stripe-go/pull/774
[gomodvsdep]: https://github.com/stripe/stripe-go/pull/712
[idempotency-keys]: https://stripe.com/docs/api/ruby#idempotent_requests
[issues]: https://github.com/stripe/stripe-go/issues/new
[logrus]: https://github.com/sirupsen/logrus/
[modules]: https://github.com/golang/go/wiki/Modules
[package-management]: https://code.google.com/p/go-wiki/wiki/PackageManagementTools
[pulls]: https://github.com/stripe/stripe-go/pulls
[stripe]: https://stripe.com
[stripe-mock]: https://github.com/stripe/stripe-mock
[stripe-mock-usage]: https://github.com/stripe/stripe-mock#usage
[zapsugaredlogger]: https://godoc.org/go.uber.org/zap#SugaredLogger
<!--
# vim: set tw=79:
-->

1
vendor/github.com/stripe/stripe-go/VERSION generated vendored Normal file
View file

@ -0,0 +1 @@
70.5.0

562
vendor/github.com/stripe/stripe-go/account.go generated vendored Normal file
View file

@ -0,0 +1,562 @@
package stripe
import (
"encoding/json"
"github.com/stripe/stripe-go/form"
)
// AccountType is the type of an account.
type AccountType string
// List of values that AccountType can take.
const (
AccountTypeCustom AccountType = "custom"
AccountTypeExpress AccountType = "express"
AccountTypeStandard AccountType = "standard"
)
// AccountCapability maps to a given capability for an account.
type AccountCapability string
// List of values that AccountCapability can take.
const (
AccountCapabilityCardPayments AccountCapability = "card_payments"
AccountCapabilityLegacyPayments AccountCapability = "legacy_payments"
AccountCapabilityTransfers AccountCapability = "transfers"
)
// AccountCapabilityStatus is the status a given capability can have
type AccountCapabilityStatus string
// List of values that AccountCapabilityStatus can take.
const (
AccountCapabilityStatusActive AccountCapabilityStatus = "active"
AccountCapabilityStatusInactive AccountCapabilityStatus = "inactive"
AccountCapabilityStatusPending AccountCapabilityStatus = "pending"
)
// ExternalAccountType is the type of an external account.
type ExternalAccountType string
// List of values that ExternalAccountType can take.
const (
ExternalAccountTypeBankAccount ExternalAccountType = "bank_account"
ExternalAccountTypeCard ExternalAccountType = "card"
)
// AccountBusinessType describes the business type associated with an account.
type AccountBusinessType string
// List of values that AccountBusinessType can take.
const (
AccountBusinessTypeCompany AccountBusinessType = "company"
AccountBusinessTypeGovernmentEntity AccountBusinessType = "government_entity"
AccountBusinessTypeIndividual AccountBusinessType = "individual"
AccountBusinessTypeNonProfit AccountBusinessType = "non_profit"
)
// AccountCompanyStructure describes the structure associated with a company.
type AccountCompanyStructure string
// List of values that AccountCompanyStructure can take.
const (
AccountCompanyStructureGovernmentInstrumentality AccountCompanyStructure = "government_instrumentality"
AccountCompanyStructureGovernmentalUnit AccountCompanyStructure = "governmental_unit"
AccountCompanyStructureIncorporatedNonProfit AccountCompanyStructure = "incorporated_non_profit"
AccountCompanyStructureMultiMemberLLC AccountCompanyStructure = "multi_member_llc"
AccountCompanyStructurePrivateCorporation AccountCompanyStructure = "private_corporation"
AccountCompanyStructurePrivatePartnership AccountCompanyStructure = "private_partnership"
AccountCompanyStructurePublicCorporation AccountCompanyStructure = "public_corporation"
AccountCompanyStructurePublicPartnership AccountCompanyStructure = "public_partnership"
AccountCompanyStructureTaxExemptGovernmentInstrumentality AccountCompanyStructure = "tax_exempt_government_instrumentality"
AccountCompanyStructureUnincorporatedAssociation AccountCompanyStructure = "unincorporated_association"
AccountCompanyStructureUnincorporatedNonProfit AccountCompanyStructure = "unincorporated_non_profit"
)
// AccountRequirementsDisabledReason describes why an account is disabled.
type AccountRequirementsDisabledReason string
// List of values that AccountRequirementsDisabledReason can take.
const (
AccountRequirementsDisabledReasonFieldsNeeded AccountRequirementsDisabledReason = "fields_needed"
AccountRequirementsDisabledReasonListed AccountRequirementsDisabledReason = "listed"
AccountRequirementsDisabledReasonOther AccountRequirementsDisabledReason = "other"
AccountRequirementsDisabledReasonRejectedFraud AccountRequirementsDisabledReason = "rejected.fraud"
AccountRequirementsDisabledReasonRejectedListed AccountRequirementsDisabledReason = "rejected.listed"
AccountRequirementsDisabledReasonRejectedOther AccountRequirementsDisabledReason = "rejected.other"
AccountRequirementsDisabledReasonRejectedTermsOfService AccountRequirementsDisabledReason = "rejected.terms_of_service"
AccountRequirementsDisabledReasonUnderReview AccountRequirementsDisabledReason = "under_review"
)
// PayoutInterval describes the payout interval.
type PayoutInterval string
// List of values that PayoutInterval can take.
const (
PayoutIntervalDaily PayoutInterval = "daily"
PayoutIntervalManual PayoutInterval = "manual"
PayoutIntervalMonthly PayoutInterval = "monthly"
PayoutIntervalWeekly PayoutInterval = "weekly"
)
// AccountRejectReason describes the valid reason to reject an account
type AccountRejectReason string
// List of values that AccountRejectReason can take.
const (
AccountRejectReasonFraud AccountRejectReason = "fraud"
AccountRejectReasonOther AccountRejectReason = "other"
AccountRejectReasonTermsOfService AccountRejectReason = "terms_of_service"
)
// AccountCompanyVerificationDocumentDetailsCode is a machine-readable code specifying the
// verification state of a document associated with a company.
type AccountCompanyVerificationDocumentDetailsCode string
// List of values that AccountCompanyVerificationDocumentDetailsCode can take.
const (
AccountCompanyVerificationDocumentDetailsCodeDocumentCorrupt AccountCompanyVerificationDocumentDetailsCode = "document_corrupt"
AccountCompanyVerificationDocumentDetailsCodeDocumentFailedCopy AccountCompanyVerificationDocumentDetailsCode = "document_failed_copy"
AccountCompanyVerificationDocumentDetailsCodeDocumentFailedOther AccountCompanyVerificationDocumentDetailsCode = "document_failed_other"
AccountCompanyVerificationDocumentDetailsCodeDocumentFailedTestMode AccountCompanyVerificationDocumentDetailsCode = "document_failed_test_mode"
AccountCompanyVerificationDocumentDetailsCodeDocumentFraudulent AccountCompanyVerificationDocumentDetailsCode = "document_fraudulent"
AccountCompanyVerificationDocumentDetailsCodeDocumentInvalid AccountCompanyVerificationDocumentDetailsCode = "document_invalid"
AccountCompanyVerificationDocumentDetailsCodeDocumentManipulated AccountCompanyVerificationDocumentDetailsCode = "document_manipulated"
AccountCompanyVerificationDocumentDetailsCodeDocumentNotReadable AccountCompanyVerificationDocumentDetailsCode = "document_not_readable"
AccountCompanyVerificationDocumentDetailsCodeDocumentNotUploaded AccountCompanyVerificationDocumentDetailsCode = "document_not_uploaded"
AccountCompanyVerificationDocumentDetailsCodeDocumentTooLarge AccountCompanyVerificationDocumentDetailsCode = "document_too_large"
)
// AccountBusinessProfileParams are the parameters allowed for an account's business information
type AccountBusinessProfileParams struct {
MCC *string `form:"mcc"`
Name *string `form:"name"`
ProductDescription *string `form:"product_description"`
SupportEmail *string `form:"support_email"`
SupportPhone *string `form:"support_phone"`
SupportURL *string `form:"support_url"`
URL *string `form:"url"`
}
// AccountCompanyVerificationDocumentParams are the parameters allowed to pass for a document
// verifying a company.
type AccountCompanyVerificationDocumentParams struct {
Back *string `form:"back"`
Front *string `form:"front"`
}
// AccountCompanyVerificationParams are the parameters allowed to verify a company.
type AccountCompanyVerificationParams struct {
Document *AccountCompanyVerificationDocumentParams `form:"document"`
}
// AccountCompanyParams are the parameters describing the company associated with the account.
type AccountCompanyParams struct {
Address *AccountAddressParams `form:"address"`
AddressKana *AccountAddressParams `form:"address_kana"`
AddressKanji *AccountAddressParams `form:"address_kanji"`
DirectorsProvided *bool `form:"directors_provided"`
ExecutivesProvided *bool `form:"executives_provided"`
Name *string `form:"name"`
NameKana *string `form:"name_kana"`
NameKanji *string `form:"name_kanji"`
OwnersProvided *bool `form:"owners_provided"`
Structure *string `form:"structure"`
Phone *string `form:"phone"`
TaxID *string `form:"tax_id"`
TaxIDRegistrar *string `form:"tax_id_registrar"`
VATID *string `form:"vat_id"`
Verification *AccountCompanyVerificationParams `form:"verification"`
}
// AccountDeclineSettingsParams represents the parameters allowed for configuring
// card declines on connected accounts.
type AccountDeclineSettingsParams struct {
AVSFailure *bool `form:"avs_failure"`
CVCFailure *bool `form:"cvc_failure"`
}
// AccountSettingsBrandingParams represent allowed parameters to configure settings specific to the
// accounts branding.
type AccountSettingsBrandingParams struct {
Icon *string `form:"icon"`
Logo *string `form:"logo"`
PrimaryColor *string `form:"primary_color"`
}
// AccountSettingsCardPaymentsParams represent allowed parameters to configure settings specific to
// card charging on the account.
type AccountSettingsCardPaymentsParams struct {
DeclineOn *AccountDeclineSettingsParams `form:"decline_on"`
StatementDescriptorPrefix *string `form:"statement_descriptor_prefix"`
}
// AccountSettingsDashboardParams represent allowed parameters to configure settings for the
// account's Dashboard.
type AccountSettingsDashboardParams struct {
DisplayName *string `form:"display_name"`
Timezone *string `form:"timezone"`
}
// AccountSettingsPaymentsParams represent allowed parameters to configure settings across payment
// methods for charging on the account.
type AccountSettingsPaymentsParams struct {
StatementDescriptor *string `form:"statement_descriptor"`
StatementDescriptorKana *string `form:"statement_descriptor_kana"`
StatementDescriptorKanji *string `form:"statement_descriptor_kanji"`
}
// AccountSettingsPayoutsParams represent allowed parameters to configure settings specific to the
// accounts payouts.
type AccountSettingsPayoutsParams struct {
DebitNegativeBalances *bool `form:"debit_negative_balances"`
Schedule *PayoutScheduleParams `form:"schedule"`
StatementDescriptor *string `form:"statement_descriptor"`
}
// AccountSettingsParams are the parameters allowed for the account's settings.
type AccountSettingsParams struct {
Branding *AccountSettingsBrandingParams `form:"branding"`
CardPayments *AccountSettingsCardPaymentsParams `form:"card_payments"`
Dashboard *AccountSettingsDashboardParams `form:"dashboard"`
Payments *AccountSettingsPaymentsParams `form:"payments"`
Payouts *AccountSettingsPayoutsParams `form:"payouts"`
}
// PayoutScheduleParams are the parameters allowed for payout schedules.
type PayoutScheduleParams struct {
DelayDays *int64 `form:"delay_days"`
DelayDaysMinimum *bool `form:"-"` // See custom AppendTo
Interval *string `form:"interval"`
MonthlyAnchor *int64 `form:"monthly_anchor"`
WeeklyAnchor *string `form:"weekly_anchor"`
}
// AppendTo implements custom encoding logic for PayoutScheduleParams
// so that we can send a special value for `delay_days` field if needed.
func (p *PayoutScheduleParams) AppendTo(body *form.Values, keyParts []string) {
if BoolValue(p.DelayDaysMinimum) {
body.Add(form.FormatKey(append(keyParts, "delay_days")), "minimum")
}
}
// AccountParams are the parameters allowed during account creation/updates.
type AccountParams struct {
Params `form:"*"`
AccountToken *string `form:"account_token"`
BusinessProfile *AccountBusinessProfileParams `form:"business_profile"`
BusinessType *string `form:"business_type"`
Company *AccountCompanyParams `form:"company"`
Country *string `form:"country"`
DefaultCurrency *string `form:"default_currency"`
Email *string `form:"email"`
ExternalAccount *AccountExternalAccountParams `form:"external_account"`
Individual *PersonParams `form:"individual"`
RequestedCapabilities []*string `form:"requested_capabilities"`
Settings *AccountSettingsParams `form:"settings"`
TOSAcceptance *AccountTOSAcceptanceParams `form:"tos_acceptance"`
Type *string `form:"type"`
}
// AccountAddressParams represents an address during account creation/updates.
type AccountAddressParams struct {
City *string `form:"city"`
Country *string `form:"country"`
Line1 *string `form:"line1"`
Line2 *string `form:"line2"`
PostalCode *string `form:"postal_code"`
State *string `form:"state"`
// Town/cho-me. Note that this is only used for Kana/Kanji representations
// of an address.
Town *string `form:"town"`
}
// AccountTOSAcceptanceParams represents tos_acceptance during account creation/updates.
type AccountTOSAcceptanceParams struct {
Date *int64 `form:"date"`
IP *string `form:"ip"`
UserAgent *string `form:"user_agent"`
}
// AccountListParams are the parameters allowed during account listing.
type AccountListParams struct {
ListParams `form:"*"`
}
// AccountRejectParams is the structure for the Reject function.
type AccountRejectParams struct {
Params `form:"*"`
Reason *string `form:"reason"`
}
// AccountExternalAccountParams are the parameters allowed to reference an
// external account when creating an account. It should either have Token set
// or everything else.
type AccountExternalAccountParams struct {
Params `form:"*"`
AccountNumber *string `form:"account_number"`
AccountHolderName *string `form:"account_holder_name"`
AccountHolderType *string `form:"account_holder_type"`
Country *string `form:"country"`
Currency *string `form:"currency"`
RoutingNumber *string `form:"routing_number"`
Token *string `form:"token"`
}
// AppendTo implements custom encoding logic for AccountExternalAccountParams
// so that we can send the special required `object` field up along with the
// other specified parameters or the token value.
func (p *AccountExternalAccountParams) AppendTo(body *form.Values, keyParts []string) {
if p.Token != nil {
body.Add(form.FormatKey(keyParts), StringValue(p.Token))
} else {
body.Add(form.FormatKey(append(keyParts, "object")), "bank_account")
}
}
// AccountBusinessProfile represents optional information related to the business.
type AccountBusinessProfile struct {
MCC string `json:"mcc"`
Name string `json:"name"`
ProductDescription string `json:"product_description"`
SupportAddress *Address `json:"support_address"`
SupportEmail string `json:"support_email"`
SupportPhone string `json:"support_phone"`
SupportURL string `json:"support_url"`
URL string `json:"url"`
}
// AccountCapabilities is the resource representing the capabilities enabled on that account.
type AccountCapabilities struct {
CardPayments AccountCapabilityStatus `json:"card_payments"`
LegacyPayments AccountCapabilityStatus `json:"legacy_payments"`
Transfers AccountCapabilityStatus `json:"transfers"`
}
// AccountCompanyVerificationDocument represents details about a company's verification state.
type AccountCompanyVerificationDocument struct {
Back *File `json:"back"`
Details string `json:"details"`
DetailsCode AccountCompanyVerificationDocumentDetailsCode `json:"details_code"`
Front *File `json:"front"`
}
// AccountCompanyVerification represents details about a company's verification state.
type AccountCompanyVerification struct {
Document *AccountCompanyVerificationDocument `json:"document"`
}
// AccountCompany represents details about the company or business associated with the account.
type AccountCompany struct {
Address *AccountAddress `json:"address"`
AddressKana *AccountAddress `json:"address_kana"`
AddressKanji *AccountAddress `json:"address_kanji"`
DirectorsProvided bool `json:"directors_provided"`
ExecutivesProvided bool `json:"executives_provided"`
Name string `json:"name"`
NameKana string `json:"name_kana"`
NameKanji string `json:"name_kanji"`
OwnersProvided bool `json:"owners_provided"`
Phone string `json:"phone"`
Structure AccountCompanyStructure `json:"structure"`
TaxIDProvided bool `json:"tax_id_provided"`
TaxIDRegistrar string `json:"tax_id_registrar"`
VATIDProvided bool `json:"vat_id_provided"`
Verification *AccountCompanyVerification `json:"verification"`
}
// AccountDeclineOn represents card charges decline behavior for that account.
type AccountDeclineOn struct {
AVSFailure bool `json:"avs_failure"`
CVCFailure bool `json:"cvc_failure"`
}
// AccountPayoutSchedule is the structure for an account's payout schedule.
type AccountPayoutSchedule struct {
DelayDays int64 `json:"delay_days"`
Interval PayoutInterval `json:"interval"`
MonthlyAnchor int64 `json:"monthly_anchor"`
WeeklyAnchor string `json:"weekly_anchor"`
}
// AccountRequirementsError represents details about an error with a requirement.
type AccountRequirementsError struct {
Code string `json:"code"`
Reason string `json:"reason"`
Requirement string `json:"requirement"`
}
// AccountRequirements represents information that needs to be collected for an account.
type AccountRequirements struct {
CurrentDeadline int64 `json:"current_deadline"`
CurrentlyDue []string `json:"currently_due"`
DisabledReason AccountRequirementsDisabledReason `json:"disabled_reason"`
Errors []*AccountRequirementsError `json:"errors"`
EventuallyDue []string `json:"eventually_due"`
PastDue []string `json:"past_due"`
PendingVerification []string `json:"pending_verification"`
}
// AccountSettingsBranding represents settings specific to the account's branding.
type AccountSettingsBranding struct {
Icon *File `json:"icon"`
Logo *File `json:"logo"`
PrimaryColor string `json:"primary_color"`
}
// AccountSettingsCardPayments represents settings specific to card charging on the account.
type AccountSettingsCardPayments struct {
DeclineOn *AccountDeclineOn `json:"decline_on"`
StatementDescriptorPrefix string `json:"statement_descriptor_prefix"`
}
// AccountSettingsDashboard represents settings specific to the account's Dashboard.
type AccountSettingsDashboard struct {
DisplayName string `json:"display_name"`
Timezone string `json:"timezone"`
}
// AccountSettingsPayments represents settings that apply across payment methods for charging on
// the account.
type AccountSettingsPayments struct {
StatementDescriptor string `json:"statement_descriptor"`
StatementDescriptorKana string `json:"statement_descriptor_kana"`
StatementDescriptorKanji string `json:"statement_descriptor_kanji"`
}
// AccountSettingsPayouts represents settings specific to the accounts payouts.
type AccountSettingsPayouts struct {
DebitNegativeBalances bool `json:"debit_negative_balances"`
Schedule *AccountPayoutSchedule `json:"schedule"`
StatementDescriptor string `json:"statement_descriptor"`
}
// AccountSettings represents options for customizing how the account functions within Stripe.
type AccountSettings struct {
Branding *AccountSettingsBranding `json:"branding"`
CardPayments *AccountSettingsCardPayments `json:"card_payments"`
Dashboard *AccountSettingsDashboard `json:"dashboard"`
Payments *AccountSettingsPayments `json:"payments"`
Payouts *AccountSettingsPayouts `json:"payouts"`
}
// AccountTOSAcceptance represents status of acceptance of our terms of services for the account.
type AccountTOSAcceptance struct {
Date int64 `json:"date"`
IP string `json:"ip"`
UserAgent string `json:"user_agent"`
}
// Account is the resource representing your Stripe account.
// For more details see https://stripe.com/docs/api/#account.
type Account struct {
BusinessProfile *AccountBusinessProfile `json:"business_profile"`
BusinessType AccountBusinessType `json:"business_type"`
Capabilities *AccountCapabilities `json:"capabilities"`
ChargesEnabled bool `json:"charges_enabled"`
Company *AccountCompany `json:"company"`
Country string `json:"country"`
Created int64 `json:"created"`
DefaultCurrency Currency `json:"default_currency"`
Deleted bool `json:"deleted"`
DetailsSubmitted bool `json:"details_submitted"`
Email string `json:"email"`
ExternalAccounts *ExternalAccountList `json:"external_accounts"`
ID string `json:"id"`
Individual *Person `json:"individual"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
PayoutsEnabled bool `json:"payouts_enabled"`
Requirements *AccountRequirements `json:"requirements"`
Settings *AccountSettings `json:"settings"`
TOSAcceptance *AccountTOSAcceptance `json:"tos_acceptance"`
Type AccountType `json:"type"`
}
// UnmarshalJSON handles deserialization of an account.
// This custom unmarshaling is needed because the resulting
// property may be an ID or the full struct if it was expanded.
func (a *Account) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
a.ID = id
return nil
}
type account Account
var v account
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*a = Account(v)
return nil
}
// AccountList is a list of accounts as returned from a list endpoint.
type AccountList struct {
ListMeta
Data []*Account `json:"data"`
}
// ExternalAccountList is a list of external accounts that may be either bank
// accounts or cards.
type ExternalAccountList struct {
ListMeta
// Values contains any external accounts (bank accounts and/or cards)
// currently attached to this account.
Data []*ExternalAccount `json:"data"`
}
// ExternalAccount is an external account (a bank account or card) that's
// attached to an account. It contains fields that will be conditionally
// populated depending on its type.
type ExternalAccount struct {
// BankAccount is a bank account attached to an account. Populated only if
// the external account is a bank account.
BankAccount *BankAccount
// Card is a card attached to an account. Populated only if the external
// account is a card.
Card *Card
ID string `json:"id"`
Type ExternalAccountType `json:"object"`
}
// UnmarshalJSON implements Unmarshaler.UnmarshalJSON.
func (ea *ExternalAccount) UnmarshalJSON(data []byte) error {
type externalAccount ExternalAccount
var v externalAccount
if err := json.Unmarshal(data, &v); err != nil {
return err
}
var err error
*ea = ExternalAccount(v)
switch ea.Type {
case ExternalAccountTypeBankAccount:
err = json.Unmarshal(data, &ea.BankAccount)
case ExternalAccountTypeCard:
err = json.Unmarshal(data, &ea.Card)
}
return err
}
// AccountAddress is the structure for an account address.
type AccountAddress struct {
City string `json:"city"`
Country string `json:"country"`
Line1 string `json:"line1"`
Line2 string `json:"line2"`
PostalCode string `json:"postal_code"`
State string `json:"state"`
// Town/cho-me. Note that this is only used for Kana/Kanji representations
// of an address.
Town string `json:"town"`
}

38
vendor/github.com/stripe/stripe-go/accountlink.go generated vendored Normal file
View file

@ -0,0 +1,38 @@
package stripe
// AccountLinkType is the type of an account link.
type AccountLinkType string
// List of values that AccountLinkType can take.
const (
AccountLinkTypeCustomAccountUpdate AccountLinkType = "custom_account_update"
AccountLinkTypeCustomAccountVerification AccountLinkType = "custom_account_verification"
)
// AccountLinkCollect describes what information the platform wants to collect with the account link.
type AccountLinkCollect string
// List of values that AccountLinkCollect can take.
const (
AccountLinkCollectCurrentlyDue AccountLinkCollect = "currently_due"
AccountLinkCollectEventuallyDue AccountLinkCollect = "eventually_due"
)
// AccountLinkParams are the parameters allowed during an account link creation.
type AccountLinkParams struct {
Params `form:"*"`
Account *string `form:"account"`
Collect *string `form:"collect"`
FailureURL *string `form:"failure_url"`
SuccessURL *string `form:"success_url"`
Type *string `form:"type"`
}
// AccountLink is the resource representing an account link.
// For more details see https://stripe.com/docs/api/#account_links.
type AccountLink struct {
Created int64 `json:"created"`
ExpiresAt int64 `json:"expires_at"`
Object string `json:"object"`
URL string `json:"url"`
}

21
vendor/github.com/stripe/stripe-go/address.go generated vendored Normal file
View file

@ -0,0 +1,21 @@
package stripe
// AddressParams describes the common parameters for an Address.
type AddressParams struct {
City *string `form:"city"`
Country *string `form:"country"`
Line1 *string `form:"line1"`
Line2 *string `form:"line2"`
PostalCode *string `form:"postal_code"`
State *string `form:"state"`
}
// Address describes common properties for an Address hash.
type Address struct {
City string `json:"city"`
Country string `json:"country"`
Line1 string `json:"line1"`
Line2 string `json:"line2"`
PostalCode string `json:"postal_code"`
State string `json:"state"`
}

27
vendor/github.com/stripe/stripe-go/applepaydomain.go generated vendored Normal file
View file

@ -0,0 +1,27 @@
package stripe
// ApplePayDomainParams is the set of parameters that can be used when creating an ApplePayDomain object.
type ApplePayDomainParams struct {
Params `form:"*"`
DomainName *string `form:"domain_name"`
}
// ApplePayDomain is the resource representing a Stripe ApplePayDomain object
type ApplePayDomain struct {
Created int64 `json:"created"`
Deleted bool `json:"deleted"`
DomainName string `json:"domain_name"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
}
// ApplePayDomainListParams are the parameters allowed during ApplePayDomain listing.
type ApplePayDomainListParams struct {
ListParams `form:"*"`
}
// ApplePayDomainList is a list of ApplePayDomains as returned from a list endpoint.
type ApplePayDomainList struct {
ListMeta
Data []*ApplePayDomain `json:"data"`
}

28
vendor/github.com/stripe/stripe-go/application.go generated vendored Normal file
View file

@ -0,0 +1,28 @@
package stripe
import "encoding/json"
// Application describes the properties for an Application.
type Application struct {
ID string `json:"id"`
Name string `json:"name"`
}
// UnmarshalJSON handles deserialization of an Application.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (a *Application) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
a.ID = id
return nil
}
type application Application
var v application
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*a = Application(v)
return nil
}

38
vendor/github.com/stripe/stripe-go/balance.go generated vendored Normal file
View file

@ -0,0 +1,38 @@
package stripe
// BalanceSourceType is the list of allowed values for the balance amount's source_type field keys.
type BalanceSourceType string
// List of values that BalanceSourceType can take.
const (
BalanceSourceTypeAlipayAccount BalanceSourceType = "alipay_account"
BalanceSourceTypeBankAccount BalanceSourceType = "bank_account"
BalanceSourceTypeBitcoinReceiver BalanceSourceType = "bitcoin_receiver"
BalanceSourceTypeCard BalanceSourceType = "card"
BalanceSourceTypeFPX BalanceSourceType = "fpx"
)
// BalanceTransactionStatus is the list of allowed values for the balance transaction's status.
type BalanceTransactionStatus string
// BalanceParams is the set of parameters that can be used when retrieving a balance.
// For more details see https://stripe.com/docs/api#balance.
type BalanceParams struct {
Params `form:"*"`
}
// Balance is the resource representing your Stripe balance.
// For more details see https://stripe.com/docs/api/#balance.
type Balance struct {
Available []*Amount `json:"available"`
ConnectReserved []*Amount `json:"connect_reserved"`
Livemode bool `json:"livemode"`
Pending []*Amount `json:"pending"`
}
// Amount is a structure wrapping an amount value and its currency.
type Amount struct {
Currency Currency `json:"currency"`
SourceTypes map[BalanceSourceType]int64 `json:"source_types"`
Value int64 `json:"amount"`
}

View file

@ -0,0 +1,222 @@
package stripe
import "encoding/json"
// List of values that BalanceTransactionStatus can take.
const (
BalanceTransactionStatusAvailable BalanceTransactionStatus = "available"
BalanceTransactionStatusPending BalanceTransactionStatus = "pending"
)
// BalanceTransactionType is the list of allowed values for the balance transaction's type.
type BalanceTransactionType string
// List of values that BalanceTransactionType can take.
const (
BalanceTransactionTypeAdjustment BalanceTransactionType = "adjustment"
BalanceTransactionTypeApplicationFee BalanceTransactionType = "application_fee"
BalanceTransactionTypeApplicationFeeRefund BalanceTransactionType = "application_fee_refund"
BalanceTransactionTypeCharge BalanceTransactionType = "charge"
BalanceTransactionTypeIssuingAuthorizationHold BalanceTransactionType = "issuing_authorization_hold"
BalanceTransactionTypeIssuingAuthorizationRelease BalanceTransactionType = "issuing_authorization_release"
BalanceTransactionTypeIssuingAuthorizationTransaction BalanceTransactionType = "issuing_transaction"
BalanceTransactionTypePayment BalanceTransactionType = "payment"
BalanceTransactionTypePaymentFailureRefund BalanceTransactionType = "payment_failure_refund"
BalanceTransactionTypePaymentRefund BalanceTransactionType = "payment_refund"
BalanceTransactionTypePayout BalanceTransactionType = "payout"
BalanceTransactionTypePayoutCancel BalanceTransactionType = "payout_cancel"
BalanceTransactionTypePayoutFailure BalanceTransactionType = "payout_failure"
BalanceTransactionTypeRecipientTransfer BalanceTransactionType = "recipient_transfer"
BalanceTransactionTypeRecipientTransferCancel BalanceTransactionType = "recipient_transfer_cancel"
BalanceTransactionTypeRecipientTransferFailure BalanceTransactionType = "recipient_transfer_failure"
BalanceTransactionTypeRefund BalanceTransactionType = "refund"
BalanceTransactionTypeStripeFee BalanceTransactionType = "stripe_fee"
BalanceTransactionTypeTransfer BalanceTransactionType = "transfer"
BalanceTransactionTypeTransferRefund BalanceTransactionType = "transfer_refund"
)
// BalanceTransactionSourceType consts represent valid balance transaction sources.
type BalanceTransactionSourceType string
// List of values that BalanceTransactionSourceType can take.
const (
BalanceTransactionSourceTypeApplicationFee BalanceTransactionSourceType = "application_fee"
BalanceTransactionSourceTypeCharge BalanceTransactionSourceType = "charge"
BalanceTransactionSourceTypeDispute BalanceTransactionSourceType = "dispute"
BalanceTransactionSourceTypeIssuingAuthorization BalanceTransactionSourceType = "issuing.authorization"
BalanceTransactionSourceTypeIssuingTransaction BalanceTransactionSourceType = "issuing.transaction"
BalanceTransactionSourceTypePayout BalanceTransactionSourceType = "payout"
BalanceTransactionSourceTypeRecipientTransfer BalanceTransactionSourceType = "recipient_transfer"
BalanceTransactionSourceTypeRefund BalanceTransactionSourceType = "refund"
BalanceTransactionSourceTypeReversal BalanceTransactionSourceType = "reversal"
BalanceTransactionSourceTypeTransfer BalanceTransactionSourceType = "transfer"
)
// BalanceTransactionReportingCategory represents reporting categories for balance transactions.
type BalanceTransactionReportingCategory string
// List of values that BalanceTransactionReportingCategory can take.
const (
BalanceTransactionReportingCategoryAdvance BalanceTransactionReportingCategory = "advance"
BalanceTransactionReportingCategoryAdvanceFunding BalanceTransactionReportingCategory = "advance_funding"
BalanceTransactionReportingCategoryCharge BalanceTransactionReportingCategory = "charge"
BalanceTransactionReportingCategoryChargeFailure BalanceTransactionReportingCategory = "charge_failure"
BalanceTransactionReportingCategoryConnectCollectionTransfer BalanceTransactionReportingCategory = "connect_collection_transfer"
BalanceTransactionReportingCategoryConnectReservedFunds BalanceTransactionReportingCategory = "connect_reserved_funds"
BalanceTransactionReportingCategoryDispute BalanceTransactionReportingCategory = "dispute"
BalanceTransactionReportingCategoryDisputeReversal BalanceTransactionReportingCategory = "dispute_reversal"
BalanceTransactionReportingCategoryFee BalanceTransactionReportingCategory = "fee"
BalanceTransactionReportingCategoryIssuingAuthorizationHold BalanceTransactionReportingCategory = "issuing_authorization_hold"
BalanceTransactionReportingCategoryIssuingAuthorizationRelease BalanceTransactionReportingCategory = "issuing_authorization_release"
BalanceTransactionReportingCategoryIssuingTransaction BalanceTransactionReportingCategory = "issuing_transaction"
BalanceTransactionReportingCategoryOtherAdjustment BalanceTransactionReportingCategory = "other_adjustment"
BalanceTransactionReportingCategoryPartialCaptureReversal BalanceTransactionReportingCategory = "partial_capture_reversal"
BalanceTransactionReportingCategoryPayout BalanceTransactionReportingCategory = "payout"
BalanceTransactionReportingCategoryPayoutReversal BalanceTransactionReportingCategory = "payout_reversal"
BalanceTransactionReportingCategoryPlatformEarning BalanceTransactionReportingCategory = "platform_earning"
BalanceTransactionReportingCategoryPlatformEarningRefund BalanceTransactionReportingCategory = "platform_earning_refund"
BalanceTransactionReportingCategoryRefund BalanceTransactionReportingCategory = "refund"
BalanceTransactionReportingCategoryRefundFailure BalanceTransactionReportingCategory = "refund_failure"
BalanceTransactionReportingCategoryRiskReservedFunds BalanceTransactionReportingCategory = "risk_reserved_funds"
BalanceTransactionReportingCategoryTax BalanceTransactionReportingCategory = "tax"
BalanceTransactionReportingCategoryTopup BalanceTransactionReportingCategory = "topup"
BalanceTransactionReportingCategoryTopupReversal BalanceTransactionReportingCategory = "topup_reversal"
BalanceTransactionReportingCategoryTransfer BalanceTransactionReportingCategory = "transfer"
BalanceTransactionReportingCategoryTransferReversal BalanceTransactionReportingCategory = "transfer_reversal"
)
// BalanceTransactionSource describes the source of a balance Transaction.
// The Type should indicate which object is fleshed out.
// For more details see https://stripe.com/docs/api#retrieve_balance_transaction
type BalanceTransactionSource struct {
ApplicationFee *ApplicationFee `json:"-"`
Charge *Charge `json:"-"`
Dispute *Dispute `json:"-"`
ID string `json:"id"`
IssuingAuthorization *IssuingAuthorization `json:"-"`
IssuingTransaction *IssuingAuthorization `json:"-"`
Payout *Payout `json:"-"`
RecipientTransfer *RecipientTransfer `json:"-"`
Refund *Refund `json:"-"`
Reversal *Reversal `json:"-"`
Transfer *Transfer `json:"-"`
Type BalanceTransactionSourceType `json:"object"`
}
// BalanceTransactionParams is the set of parameters that can be used when retrieving a transaction.
// For more details see https://stripe.com/docs/api#retrieve_balance_transaction.
type BalanceTransactionParams struct {
Params `form:"*"`
}
// BalanceTransactionListParams is the set of parameters that can be used when listing balance transactions.
// For more details see https://stripe.com/docs/api/#balance_history.
type BalanceTransactionListParams struct {
ListParams `form:"*"`
AvailableOn *int64 `form:"available_on"`
AvailableOnRange *RangeQueryParams `form:"available_on"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Currency *string `form:"currency"`
Payout *string `form:"payout"`
Source *string `form:"source"`
Type *string `form:"type"`
}
// BalanceTransaction is the resource representing the balance transaction.
// For more details see https://stripe.com/docs/api/#balance.
type BalanceTransaction struct {
Amount int64 `json:"amount"`
AvailableOn int64 `json:"available_on"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Description string `json:"description"`
ExchangeRate float64 `json:"exchange_rate"`
ID string `json:"id"`
Fee int64 `json:"fee"`
FeeDetails []*BalanceTransactionFee `json:"fee_details"`
Net int64 `json:"net"`
Recipient string `json:"recipient"`
ReportingCategory BalanceTransactionReportingCategory `json:"reporting_category"`
Source *BalanceTransactionSource `json:"source"`
Status BalanceTransactionStatus `json:"status"`
Type BalanceTransactionType `json:"type"`
}
// BalanceTransactionList is a list of transactions as returned from a list endpoint.
type BalanceTransactionList struct {
ListMeta
Data []*BalanceTransaction `json:"data"`
}
// BalanceTransactionFee is a structure that breaks down the fees in a transaction.
type BalanceTransactionFee struct {
Amount int64 `json:"amount"`
Application string `json:"application"`
Currency Currency `json:"currency"`
Description string `json:"description"`
Type string `json:"type"`
}
// UnmarshalJSON handles deserialization of a Transaction.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (t *BalanceTransaction) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
t.ID = id
return nil
}
type balanceTransaction BalanceTransaction
var v balanceTransaction
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*t = BalanceTransaction(v)
return nil
}
// UnmarshalJSON handles deserialization of a BalanceTransactionSource.
// This custom unmarshaling is needed because the specific
// type of transaction source it refers to is specified in the JSON
func (s *BalanceTransactionSource) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
s.ID = id
return nil
}
type balanceTransactionSource BalanceTransactionSource
var v balanceTransactionSource
if err := json.Unmarshal(data, &v); err != nil {
return err
}
var err error
*s = BalanceTransactionSource(v)
switch s.Type {
case BalanceTransactionSourceTypeApplicationFee:
err = json.Unmarshal(data, &s.ApplicationFee)
case BalanceTransactionSourceTypeCharge:
err = json.Unmarshal(data, &s.Charge)
case BalanceTransactionSourceTypeDispute:
err = json.Unmarshal(data, &s.Dispute)
case BalanceTransactionSourceTypeIssuingAuthorization:
err = json.Unmarshal(data, &s.IssuingAuthorization)
case BalanceTransactionSourceTypeIssuingTransaction:
err = json.Unmarshal(data, &s.IssuingTransaction)
case BalanceTransactionSourceTypePayout:
err = json.Unmarshal(data, &s.Payout)
case BalanceTransactionSourceTypeRecipientTransfer:
err = json.Unmarshal(data, &s.RecipientTransfer)
case BalanceTransactionSourceTypeRefund:
err = json.Unmarshal(data, &s.Refund)
case BalanceTransactionSourceTypeReversal:
err = json.Unmarshal(data, &s.Reversal)
case BalanceTransactionSourceTypeTransfer:
err = json.Unmarshal(data, &s.Transfer)
}
return err
}

184
vendor/github.com/stripe/stripe-go/bankaccount.go generated vendored Normal file
View file

@ -0,0 +1,184 @@
package stripe
import (
"encoding/json"
"strconv"
"github.com/stripe/stripe-go/form"
)
// BankAccountStatus is the list of allowed values for the bank account's status.
type BankAccountStatus string
// List of values that BankAccountStatus can take.
const (
BankAccountStatusErrored BankAccountStatus = "errored"
BankAccountStatusNew BankAccountStatus = "new"
BankAccountStatusValidated BankAccountStatus = "validated"
BankAccountStatusVerificationFailed BankAccountStatus = "verification_failed"
BankAccountStatusVerified BankAccountStatus = "verified"
)
// BankAccountAccountHolderType is the list of allowed values for the bank account holder type.
type BankAccountAccountHolderType string
// List of values that BankAccountAccountHolderType can take.
const (
BankAccountAccountHolderTypeCompany BankAccountAccountHolderType = "company"
BankAccountAccountHolderTypeIndividual BankAccountAccountHolderType = "individual"
)
// BankAccountParams is the set of parameters that can be used when updating a
// bank account.
//
// Note that while form annotations are used for updates, bank accounts have
// some unusual logic on creates that necessitates manual handling of all
// parameters. See AppendToAsSourceOrExternalAccount.
type BankAccountParams struct {
Params `form:"*"`
// Account is the identifier of the parent account under which bank
// accounts are nested.
Account *string `form:"-"`
AccountHolderName *string `form:"account_holder_name"`
AccountHolderType *string `form:"account_holder_type"`
AccountNumber *string `form:"account_number"`
Country *string `form:"country"`
Currency *string `form:"currency"`
Customer *string `form:"-"`
DefaultForCurrency *bool `form:"default_for_currency"`
RoutingNumber *string `form:"routing_number"`
// Token is a token referencing an external account like one returned from
// Stripe.js.
Token *string `form:"-"`
// ID is used when tokenizing a bank account for shared customers
ID *string `form:"*"`
}
// AppendToAsSourceOrExternalAccount appends the given BankAccountParams as
// either a source or external account.
//
// It may look like an AppendTo from the form package, but it's not, and is
// only used in the special case where we use `bankaccount.New`. It's needed
// because we have some weird encoding logic here that can't be handled by the
// form package (and it's special enough that it wouldn't be desirable to have
// it do so).
//
// This is not a pattern that we want to push forward, and this largely exists
// because the bank accounts endpoint is a little unusual. There is one other
// resource like it, which is cards.
func (a *BankAccountParams) AppendToAsSourceOrExternalAccount(body *form.Values) {
// Rather than being called in addition to `AppendTo`, this function
// *replaces* `AppendTo`, so we must also make sure to handle the encoding
// of `Params` so metadata and the like is included in the encoded payload.
form.AppendTo(body, a.Params)
isCustomer := a.Customer != nil
var sourceType string
if isCustomer {
sourceType = "source"
} else {
sourceType = "external_account"
}
// Use token (if exists) or a dictionary containing a users bank account details.
if a.Token != nil {
body.Add(sourceType, StringValue(a.Token))
if a.DefaultForCurrency != nil {
body.Add("default_for_currency", strconv.FormatBool(BoolValue(a.DefaultForCurrency)))
}
} else {
body.Add(sourceType+"[object]", "bank_account")
body.Add(sourceType+"[country]", StringValue(a.Country))
body.Add(sourceType+"[account_number]", StringValue(a.AccountNumber))
body.Add(sourceType+"[currency]", StringValue(a.Currency))
// These are optional and the API will fail if we try to send empty
// values in for them, so make sure to check that they're actually set
// before encoding them.
if a.AccountHolderName != nil {
body.Add(sourceType+"[account_holder_name]", StringValue(a.AccountHolderName))
}
if a.AccountHolderType != nil {
body.Add(sourceType+"[account_holder_type]", StringValue(a.AccountHolderType))
}
if a.RoutingNumber != nil {
body.Add(sourceType+"[routing_number]", StringValue(a.RoutingNumber))
}
if a.DefaultForCurrency != nil {
body.Add(sourceType+"[default_for_currency]", strconv.FormatBool(BoolValue(a.DefaultForCurrency)))
}
}
}
// BankAccountListParams is the set of parameters that can be used when listing bank accounts.
type BankAccountListParams struct {
ListParams `form:"*"`
// The identifier of the parent account under which the bank accounts are
// nested. Either Account or Customer should be populated.
Account *string `form:"-"`
// The identifier of the parent customer under which the bank accounts are
// nested. Either Account or Customer should be populated.
Customer *string `form:"-"`
}
// AppendTo implements custom encoding logic for BankAccountListParams
// so that we can send the special required `object` field up along with the
// other specified parameters.
func (p *BankAccountListParams) AppendTo(body *form.Values, keyParts []string) {
body.Add(form.FormatKey(append(keyParts, "object")), "bank_account")
}
// BankAccount represents a Stripe bank account.
type BankAccount struct {
Account *Account `json:"account"`
AccountHolderName string `json:"account_holder_name"`
AccountHolderType BankAccountAccountHolderType `json:"account_holder_type"`
BankName string `json:"bank_name"`
Country string `json:"country"`
Currency Currency `json:"currency"`
Customer *Customer `json:"customer"`
DefaultForCurrency bool `json:"default_for_currency"`
Deleted bool `json:"deleted"`
Fingerprint string `json:"fingerprint"`
ID string `json:"id"`
Last4 string `json:"last4"`
Metadata map[string]string `json:"metadata"`
RoutingNumber string `json:"routing_number"`
Status BankAccountStatus `json:"status"`
}
// BankAccountList is a list object for bank accounts.
type BankAccountList struct {
ListMeta
Data []*BankAccount `json:"data"`
}
// UnmarshalJSON handles deserialization of a BankAccount.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (b *BankAccount) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
b.ID = id
return nil
}
type bankAccount BankAccount
var v bankAccount
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*b = BankAccount(v)
return nil
}

63
vendor/github.com/stripe/stripe-go/bitcoinreceiver.go generated vendored Normal file
View file

@ -0,0 +1,63 @@
package stripe
import (
"encoding/json"
)
// BitcoinReceiverListParams is the set of parameters that can be used when listing BitcoinReceivers.
// For more details see https://stripe.com/docs/api/#list_bitcoin_receivers.
type BitcoinReceiverListParams struct {
ListParams `form:"*"`
Active *bool `form:"active"`
Filled *bool `form:"filled"`
UncapturedFunds *bool `form:"uncaptured_funds"`
}
// BitcoinReceiver is the resource representing a Stripe bitcoin receiver.
// For more details see https://stripe.com/docs/api/#bitcoin_receivers
type BitcoinReceiver struct {
Active bool `json:"active"`
Amount int64 `json:"amount"`
AmountReceived int64 `json:"amount_received"`
BitcoinAmount int64 `json:"bitcoin_amount"`
BitcoinAmountReceived int64 `json:"bitcoin_amount_received"`
BitcoinURI string `json:"bitcoin_uri"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Customer string `json:"customer"`
Description string `json:"description"`
Email string `json:"email"`
Filled bool `json:"filled"`
ID string `json:"id"`
InboundAddress string `json:"inbound_address"`
Metadata map[string]string `json:"metadata"`
Payment string `json:"payment"`
RefundAddress string `json:"refund_address"`
RejectTransactions bool `json:"reject_transactions"`
Transactions *BitcoinTransactionList `json:"transactions"`
}
// BitcoinReceiverList is a list of bitcoin receivers as retrieved from a list endpoint.
type BitcoinReceiverList struct {
ListMeta
Data []*BitcoinReceiver `json:"data"`
}
// UnmarshalJSON handles deserialization of a BitcoinReceiver.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (r *BitcoinReceiver) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
r.ID = id
return nil
}
type bitcoinReceiver BitcoinReceiver
var v bitcoinReceiver
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*r = BitcoinReceiver(v)
return nil
}

View file

@ -0,0 +1,49 @@
package stripe
import "encoding/json"
// BitcoinTransactionListParams is the set of parameters that can be used when listing BitcoinTransactions.
type BitcoinTransactionListParams struct {
ListParams `form:"*"`
Customer *string `form:"customer"`
Receiver *string `form:"-"` // Sent in with the URL
}
// BitcoinTransactionList is a list object for BitcoinTransactions.
// It is a child object of BitcoinReceivers
// For more details see https://stripe.com/docs/api/#retrieve_bitcoin_receiver
type BitcoinTransactionList struct {
ListMeta
Data []*BitcoinTransaction `json:"data"`
}
// BitcoinTransaction is the resource representing a Stripe bitcoin transaction.
// For more details see https://stripe.com/docs/api/#bitcoin_receivers
type BitcoinTransaction struct {
Amount int64 `json:"amount"`
BitcoinAmount int64 `json:"bitcoin_amount"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Customer string `json:"customer"`
ID string `json:"id"`
Receiver string `json:"receiver"`
}
// UnmarshalJSON handles deserialization of a BitcoinTransaction.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (bt *BitcoinTransaction) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
bt.ID = id
return nil
}
type bitcoinTransaction BitcoinTransaction
var v bitcoinTransaction
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*bt = BitcoinTransaction(v)
return nil
}

90
vendor/github.com/stripe/stripe-go/capability.go generated vendored Normal file
View file

@ -0,0 +1,90 @@
package stripe
import "encoding/json"
// CapabilityDisabledReason describes why a capability is disabled.
type CapabilityDisabledReason string
// List of values that CapabilityDisabledReason can take.
const (
CapabilityDisabledReasonPendingOnboarding CapabilityDisabledReason = "pending.onboarding"
CapabilityDisabledReasonPendingReview CapabilityDisabledReason = "pending.review"
CapabilityDisabledReasonRejectedFraud CapabilityDisabledReason = "rejected_fraud"
CapabilityDisabledReasonRejectedListed CapabilityDisabledReason = "rejected.listed"
CapabilityDisabledReasonRejectedOther CapabilityDisabledReason = "rejected.other"
CapabilityDisabledReasonRequirementsFieldsNeeded CapabilityDisabledReason = "requirement.fields_needed"
)
// CapabilityStatus describes the different statuses for a capability's status.
type CapabilityStatus string
// List of values that CapabilityStatus can take.
const (
CapabilityStatusActive CapabilityStatus = "active"
CapabilityStatusInactive CapabilityStatus = "inactive"
CapabilityStatusPending CapabilityStatus = "pending"
CapabilityStatusUnrequested CapabilityStatus = "unrequested"
)
// CapabilityParams is the set of parameters that can be used when updating a capability.
// For more details see https://stripe.com/docs/api/capabilities/update
type CapabilityParams struct {
Params `form:"*"`
Account *string `form:"-"` // Included in URL
Requested *bool `form:"requested"`
}
// CapabilityListParams is the set of parameters that can be used when listing capabilities.
// For more detail see https://stripe.com/docs/api/capabilities/list
type CapabilityListParams struct {
ListParams `form:"*"`
Account *string `form:"-"` // Included in URL
}
// CapabilityRequirements represents information that needs to be collected for a capability.
type CapabilityRequirements struct {
CurrentDeadline int64 `json:"current_deadline"`
CurrentlyDue []string `json:"currently_due"`
DisabledReason CapabilityDisabledReason `json:"disabled_reason"`
Errors []*AccountRequirementsError `json:"errors"`
EventuallyDue []string `json:"eventually_due"`
PastDue []string `json:"past_due"`
PendingVerification []string `json:"pending_verification"`
}
// Capability is the resource representing a Stripe capability.
// For more details see https://stripe.com/docs/api/capabilities
type Capability struct {
Account *Account `json:"account"`
ID string `json:"id"`
Object string `json:"object"`
Requested bool `json:"requested"`
RequestedAt int64 `json:"requested_at"`
Requirements *CapabilityRequirements `json:"requirements"`
Status CapabilityStatus `json:"status"`
}
// CapabilityList is a list of capabilities as retrieved from a list endpoint.
type CapabilityList struct {
ListMeta
Data []*Capability `json:"data"`
}
// UnmarshalJSON handles deserialization of a Capability.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *Capability) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type capability Capability
var v capability
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = Capability(v)
return nil
}

273
vendor/github.com/stripe/stripe-go/card.go generated vendored Normal file
View file

@ -0,0 +1,273 @@
package stripe
import (
"encoding/json"
"strconv"
"github.com/stripe/stripe-go/form"
)
// CardAvailablePayoutMethod is a set of available payout methods for the card.
type CardAvailablePayoutMethod string
// List of values that CardAvailablePayoutMethod can take.
const (
CardAvailablePayoutMethodInstant CardAvailablePayoutMethod = "Instant"
CardAvailablePayoutMethodStandard CardAvailablePayoutMethod = "Standard"
)
// CardBrand is the list of allowed values for the card's brand.
type CardBrand string
// List of values that CardBrand can take.
const (
CardBrandAmex CardBrand = "American Express"
CardBrandDiscover CardBrand = "Discover"
CardBrandDinersClub CardBrand = "Diners Club"
CardBrandJCB CardBrand = "JCB"
CardBrandMasterCard CardBrand = "MasterCard"
CardBrandUnknown CardBrand = "Unknown"
CardBrandUnionPay CardBrand = "UnionPay"
CardBrandVisa CardBrand = "Visa"
)
// CardFunding is the list of allowed values for the card's funding.
type CardFunding string
// List of values that CardFunding can take.
const (
CardFundingCredit CardFunding = "credit"
CardFundingDebit CardFunding = "debit"
CardFundingPrepaid CardFunding = "prepaid"
CardFundingUnknown CardFunding = "unknown"
)
// CardTokenizationMethod is the list of allowed values for the card's tokenization method.
type CardTokenizationMethod string
// List of values that CardTokenizationMethod can take.
const (
TokenizationMethodAndroidPay CardTokenizationMethod = "android_pay"
TokenizationMethodApplePay CardTokenizationMethod = "apple_pay"
)
// CardVerification is the list of allowed verification responses.
type CardVerification string
// List of values that CardVerification can take.
const (
CardVerificationFail CardVerification = "fail"
CardVerificationPass CardVerification = "pass"
CardVerificationUnavailable CardVerification = "unavailable"
CardVerificationUnchecked CardVerification = "unchecked"
)
// cardSource is a string that's used to build card form parameters. It's a
// constant just to make mistakes less likely.
const cardSource = "source"
// CardParams is the set of parameters that can be used when creating or updating a card.
// For more details see https://stripe.com/docs/api#create_card and https://stripe.com/docs/api#update_card.
//
// Note that while form annotations are used for tokenization and updates,
// cards have some unusual logic on creates that necessitates manual handling
// of all parameters. See AppendToAsCardSourceOrExternalAccount.
type CardParams struct {
Params `form:"*"`
Account *string `form:"-"`
AddressCity *string `form:"address_city"`
AddressCountry *string `form:"address_country"`
AddressLine1 *string `form:"address_line1"`
AddressLine2 *string `form:"address_line2"`
AddressState *string `form:"address_state"`
AddressZip *string `form:"address_zip"`
CVC *string `form:"cvc"`
Currency *string `form:"currency"`
Customer *string `form:"-"`
DefaultForCurrency *bool `form:"default_for_currency"`
ExpMonth *string `form:"exp_month"`
ExpYear *string `form:"exp_year"`
Name *string `form:"name"`
Number *string `form:"number"`
Recipient *string `form:"-"`
Token *string `form:"-"`
// ID is used when tokenizing a card for shared customers
ID string `form:"*"`
}
// AppendToAsCardSourceOrExternalAccount appends the given CardParams as either a
// card or external account.
//
// It may look like an AppendTo from the form package, but it's not, and is
// only used in the special case where we use `card.New`. It's needed because
// we have some weird encoding logic here that can't be handled by the form
// package (and it's special enough that it wouldn't be desirable to have it do
// so).
//
// This is not a pattern that we want to push forward, and this largely exists
// because the cards endpoint is a little unusual. There is one other resource
// like it, which is bank account.
func (c *CardParams) AppendToAsCardSourceOrExternalAccount(body *form.Values, keyParts []string) {
// Rather than being called in addition to `AppendTo`, this function
// *replaces* `AppendTo`, so we must also make sure to handle the encoding
// of `Params` so metadata and the like is included in the encoded payload.
form.AppendToPrefixed(body, c.Params, keyParts)
if c.DefaultForCurrency != nil {
body.Add(form.FormatKey(append(keyParts, "default_for_currency")), strconv.FormatBool(BoolValue(c.DefaultForCurrency)))
}
if c.Token != nil {
if c.Account != nil {
body.Add(form.FormatKey(append(keyParts, "external_account")), StringValue(c.Token))
} else {
body.Add(form.FormatKey(append(keyParts, cardSource)), StringValue(c.Token))
}
}
if c.Number != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "object")), "card")
body.Add(form.FormatKey(append(keyParts, cardSource, "number")), StringValue(c.Number))
}
if c.CVC != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "cvc")), StringValue(c.CVC))
}
if c.Currency != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "currency")), StringValue(c.Currency))
}
if c.ExpMonth != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "exp_month")), StringValue(c.ExpMonth))
}
if c.ExpYear != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "exp_year")), StringValue(c.ExpYear))
}
if c.Name != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "name")), StringValue(c.Name))
}
if c.AddressCity != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "address_city")), StringValue(c.AddressCity))
}
if c.AddressCountry != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "address_country")), StringValue(c.AddressCountry))
}
if c.AddressLine1 != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "address_line1")), StringValue(c.AddressLine1))
}
if c.AddressLine2 != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "address_line2")), StringValue(c.AddressLine2))
}
if c.AddressState != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "address_state")), StringValue(c.AddressState))
}
if c.AddressZip != nil {
body.Add(form.FormatKey(append(keyParts, cardSource, "address_zip")), StringValue(c.AddressZip))
}
}
// CardListParams is the set of parameters that can be used when listing cards.
// For more details see https://stripe.com/docs/api#list_cards.
type CardListParams struct {
ListParams `form:"*"`
Account *string `form:"-"`
Customer *string `form:"-"`
Recipient *string `form:"-"`
}
// AppendTo implements custom encoding logic for CardListParams
// so that we can send the special required `object` field up along with the
// other specified parameters.
func (p *CardListParams) AppendTo(body *form.Values, keyParts []string) {
if p.Account != nil || p.Customer != nil {
body.Add(form.FormatKey(append(keyParts, "object")), "card")
}
}
// Card is the resource representing a Stripe credit/debit card.
// For more details see https://stripe.com/docs/api#cards.
type Card struct {
AddressCity string `json:"address_city"`
AddressCountry string `json:"address_country"`
AddressLine1 string `json:"address_line1"`
AddressLine1Check CardVerification `json:"address_line1_check"`
AddressLine2 string `json:"address_line2"`
AddressState string `json:"address_state"`
AddressZip string `json:"address_zip"`
AddressZipCheck CardVerification `json:"address_zip_check"`
AvailablePayoutMethods []CardAvailablePayoutMethod `json:"available_payout_methods"`
Brand CardBrand `json:"brand"`
CVCCheck CardVerification `json:"cvc_check"`
Country string `json:"country"`
Currency Currency `json:"currency"`
Customer *Customer `json:"customer"`
DefaultForCurrency bool `json:"default_for_currency"`
Deleted bool `json:"deleted"`
// Description is a succinct summary of the card's information.
//
// Please note that this field is for internal use only and is not returned
// as part of standard API requests.
Description string `json:"description"`
DynamicLast4 string `json:"dynamic_last4"`
ExpMonth uint8 `json:"exp_month"`
ExpYear uint16 `json:"exp_year"`
Fingerprint string `json:"fingerprint"`
Funding CardFunding `json:"funding"`
ID string `json:"id"`
// IIN is the card's "Issuer Identification Number".
//
// Please note that this field is for internal use only and is not returned
// as part of standard API requests.
IIN string `json:"iin"`
// Issuer is a bank or financial institution that provides the card.
//
// Please note that this field is for internal use only and is not returned
// as part of standard API requests.
Issuer string `json:"issuer"`
Last4 string `json:"last4"`
Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
Recipient *Recipient `json:"recipient"`
ThreeDSecure *ThreeDSecure `json:"three_d_secure"`
TokenizationMethod CardTokenizationMethod `json:"tokenization_method"`
}
// CardList is a list object for cards.
type CardList struct {
ListMeta
Data []*Card `json:"data"`
}
// UnmarshalJSON handles deserialization of a Card.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *Card) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type card Card
var v card
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = Card(v)
return nil
}

586
vendor/github.com/stripe/stripe-go/charge.go generated vendored Normal file
View file

@ -0,0 +1,586 @@
package stripe
import (
"encoding/json"
)
// ChargeFraudUserReport is the list of allowed values for reporting fraud.
type ChargeFraudUserReport string
// List of values that ChargeFraudUserReport can take.
const (
ChargeFraudUserReportFraudulent ChargeFraudUserReport = "fraudulent"
ChargeFraudUserReportSafe ChargeFraudUserReport = "safe"
)
// ChargeFraudStripeReport is the list of allowed values for reporting fraud.
type ChargeFraudStripeReport string
// List of values that ChargeFraudStripeReport can take.
const (
ChargeFraudStripeReportFraudulent ChargeFraudStripeReport = "fraudulent"
)
// ChargePaymentMethodDetailsType is the type of the PaymentMethod associated with the Charge's
// payment method details.
type ChargePaymentMethodDetailsType string
// List of values that ChargePaymentMethodDetailsType can take.
const (
ChargePaymentMethodDetailsTypeAchCreditTransfer ChargePaymentMethodDetailsType = "ach_credit_transfer"
ChargePaymentMethodDetailsTypeAchDebit ChargePaymentMethodDetailsType = "ach_debit"
ChargePaymentMethodDetailsTypeAcssDebit ChargePaymentMethodDetailsType = "acss_debit"
ChargePaymentMethodDetailsTypeAlipay ChargePaymentMethodDetailsType = "alipay"
ChargePaymentMethodDetailsTypeAUBECSDebit ChargePaymentMethodDetailsType = "au_becs_debit"
ChargePaymentMethodDetailsTypeBancontact ChargePaymentMethodDetailsType = "bancontact"
ChargePaymentMethodDetailsTypeBitcoin ChargePaymentMethodDetailsType = "bitcoin" // This is unsupported today and is here for legacy charges.
ChargePaymentMethodDetailsTypeCard ChargePaymentMethodDetailsType = "card"
ChargePaymentMethodDetailsTypeCardPresent ChargePaymentMethodDetailsType = "card_present"
ChargePaymentMethodDetailsTypeEps ChargePaymentMethodDetailsType = "eps"
ChargePaymentMethodDetailsTypeFPX ChargePaymentMethodDetailsType = "fpx"
ChargePaymentMethodDetailsTypeGiropay ChargePaymentMethodDetailsType = "giropay"
ChargePaymentMethodDetailsTypeIdeal ChargePaymentMethodDetailsType = "ideal"
ChargePaymentMethodDetailsTypeKlarna ChargePaymentMethodDetailsType = "klarna"
ChargePaymentMethodDetailsTypeMultibanco ChargePaymentMethodDetailsType = "multibanco"
ChargePaymentMethodDetailsTypeP24 ChargePaymentMethodDetailsType = "p24"
ChargePaymentMethodDetailsTypeSepaDebit ChargePaymentMethodDetailsType = "sepa_debit"
ChargePaymentMethodDetailsTypeSofort ChargePaymentMethodDetailsType = "sofort"
ChargePaymentMethodDetailsTypeStripeAccount ChargePaymentMethodDetailsType = "stripe_account"
ChargePaymentMethodDetailsTypeWechat ChargePaymentMethodDetailsType = "wechat"
)
// ChargeLevel3LineItemsParams is the set of parameters that represent a line item on level III data.
type ChargeLevel3LineItemsParams struct {
DiscountAmount *int64 `form:"discount_amount"`
ProductCode *string `form:"product_code"`
ProductDescription *string `form:"product_description"`
Quantity *int64 `form:"quantity"`
TaxAmount *int64 `form:"tax_amount"`
UnitCost *int64 `form:"unit_cost"`
}
// ChargeLevel3Params is the set of parameters that can be used for the Level III data.
type ChargeLevel3Params struct {
CustomerReference *string `form:"customer_reference"`
LineItems []*ChargeLevel3LineItemsParams `form:"line_items"`
MerchantReference *string `form:"merchant_reference"`
ShippingAddressZip *string `form:"shipping_address_zip"`
ShippingFromZip *string `form:"shipping_from_zip"`
ShippingAmount *int64 `form:"shipping_amount"`
}
// ChargeTransferDataParams is the set of parameters allowed for the transfer_data hash.
type ChargeTransferDataParams struct {
Amount *int64 `form:"amount"`
// This parameter can only be used on Charge creation.
Destination *string `form:"destination"`
}
// ChargeParams is the set of parameters that can be used when creating or updating a charge.
type ChargeParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
ApplicationFeeAmount *int64 `form:"application_fee_amount"`
Capture *bool `form:"capture"`
Currency *string `form:"currency"`
Customer *string `form:"customer"`
Description *string `form:"description"`
Destination *DestinationParams `form:"destination"`
ExchangeRate *float64 `form:"exchange_rate"`
FraudDetails *FraudDetailsParams `form:"fraud_details"`
Level3 *ChargeLevel3Params `form:"level3"`
OnBehalfOf *string `form:"on_behalf_of"`
ReceiptEmail *string `form:"receipt_email"`
Shipping *ShippingDetailsParams `form:"shipping"`
Source *SourceParams `form:"*"` // SourceParams has custom encoding so brought to top level with "*"
StatementDescriptor *string `form:"statement_descriptor"`
StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"`
TransferData *ChargeTransferDataParams `form:"transfer_data"`
TransferGroup *string `form:"transfer_group"`
}
// ShippingDetailsParams is the structure containing shipping information as parameters
type ShippingDetailsParams struct {
Address *AddressParams `form:"address"`
Carrier *string `form:"carrier"`
Name *string `form:"name"`
Phone *string `form:"phone"`
TrackingNumber *string `form:"tracking_number"`
}
// SetSource adds valid sources to a ChargeParams object,
// returning an error for unsupported sources.
func (p *ChargeParams) SetSource(sp interface{}) error {
source, err := SourceParamsFor(sp)
p.Source = source
return err
}
// DestinationParams describes the parameters available for the destination hash when creating a charge.
type DestinationParams struct {
Account *string `form:"account"`
Amount *int64 `form:"amount"`
}
// FraudDetailsParams provides information on the fraud details for a charge.
type FraudDetailsParams struct {
UserReport *string `form:"user_report"`
}
// ChargeListParams is the set of parameters that can be used when listing charges.
type ChargeListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Customer *string `form:"customer"`
PaymentIntent *string `form:"payment_intent"`
TransferGroup *string `form:"transfer_group"`
}
// CaptureParams is the set of parameters that can be used when capturing a charge.
type CaptureParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
ApplicationFeeAmount *int64 `form:"application_fee_amount"`
ExchangeRate *float64 `form:"exchange_rate"`
ReceiptEmail *string `form:"receipt_email"`
StatementDescriptor *string `form:"statement_descriptor"`
StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"`
TransferGroup *string `form:"transfer_group"`
TransferData *ChargeTransferDataParams `form:"transfer_data"`
}
// ChargeLevel3LineItem represents a line item on level III data.
// This is in private beta and would be empty for most integrations
type ChargeLevel3LineItem struct {
DiscountAmount int64 `json:"discount_amount"`
ProductCode string `json:"product_code"`
ProductDescription string `json:"product_description"`
Quantity int64 `json:"quantity"`
TaxAmount int64 `json:"tax_amount"`
UnitCost int64 `json:"unit_cost"`
}
// ChargeLevel3 represents the Level III data.
// This is in private beta and would be empty for most integrations
type ChargeLevel3 struct {
CustomerReference string `json:"customer_reference"`
LineItems []*ChargeLevel3LineItem `json:"line_items"`
MerchantReference string `json:"merchant_reference"`
ShippingAddressZip string `json:"shipping_address_zip"`
ShippingFromZip string `json:"shipping_from_zip"`
ShippingAmount int64 `json:"shipping_amount"`
}
// ChargePaymentMethodDetailsAchCreditTransfer represents details about the ACH Credit Transfer
// PaymentMethod.
type ChargePaymentMethodDetailsAchCreditTransfer struct {
AccountNumber string `json:"account_number"`
BankName string `json:"bank_name"`
RoutingNumber string `json:"routing_number"`
SwiftCode string `json:"swift_code"`
}
// ChargePaymentMethodDetailsAchDebit represents details about the ACH Debit PaymentMethod.
type ChargePaymentMethodDetailsAchDebit struct {
AccountHolderType BankAccountAccountHolderType `json:"account_holder_type"`
BankName string `json:"bank_name"`
Country string `json:"country"`
Fingerprint string `json:"fingerprint"`
Last4 string `json:"last4"`
RoutingNumber string `json:"routing_number"`
}
// ChargePaymentMethodDetailsAcssDebit represents details about the ACSS Debit PaymentMethod.
type ChargePaymentMethodDetailsAcssDebit struct {
Country string `json:"country"`
Fingerprint string `json:"fingerprint"`
Last4 string `json:"last4"`
RoutingNumber string `json:"routing_number"`
}
// ChargePaymentMethodDetailsAlipay represents details about the Alipay PaymentMethod.
type ChargePaymentMethodDetailsAlipay struct {
}
// ChargePaymentMethodDetailsAUBECSDebit represents details about the AU BECS DD PaymentMethod.
type ChargePaymentMethodDetailsAUBECSDebit struct {
BSBNumber string `json:"bsb_number"`
Fingerprint string `json:"fingerprint"`
Last4 string `json:"last4"`
Mandate string `json:"mandate"`
}
// ChargePaymentMethodDetailsBancontact represents details about the Bancontact PaymentMethod.
type ChargePaymentMethodDetailsBancontact struct {
BankCode string `json:"bank_code"`
BankName string `json:"bank_name"`
Bic string `json:"bic"`
IbanLast4 string `json:"iban_last4"`
PreferredLanguage string `json:"preferred_language"`
VerifiedName string `json:"verified_name"`
}
// ChargePaymentMethodDetailsBitcoin represents details about the Bitcoin PaymentMethod.
type ChargePaymentMethodDetailsBitcoin struct {
Address string `json:"address"`
Amount int64 `json:"amount"`
AmountCharged int64 `json:"amount_charged"`
AmountReceived int64 `json:"amount_received"`
AmountReturned int64 `json:"amount_returned"`
RefundAddress string `json:"refund_address"`
}
// ChargePaymentMethodDetailsCardChecks represents the checks associated with the charge's Card
// PaymentMethod.
type ChargePaymentMethodDetailsCardChecks struct {
AddressLine1Check CardVerification `json:"address_line1_check"`
AddressPostalCodeCheck CardVerification `json:"address_postal_code_check"`
CVCCheck CardVerification `json:"cvc_check"`
}
// ChargePaymentMethodDetailsCardInstallments represents details about the installment plan chosen
// for this charge.
type ChargePaymentMethodDetailsCardInstallments struct {
Plan *PaymentIntentPaymentMethodOptionsCardInstallmentsPlan `json:"plan"`
}
// ChargePaymentMethodDetailsCardThreeDSecure represents details about 3DS associated with the
// charge's PaymentMethod.
type ChargePaymentMethodDetailsCardThreeDSecure struct {
Authenticated bool `json:"authenticated"`
Succeeded bool `json:"succeeded"`
Version string `json:"version"`
}
// ChargePaymentMethodDetailsCardWalletAmexExpressCheckout represents the details of the Amex
// Express Checkout wallet.
type ChargePaymentMethodDetailsCardWalletAmexExpressCheckout struct {
}
// ChargePaymentMethodDetailsCardWalletApplePay represents the details of the Apple Pay wallet.
type ChargePaymentMethodDetailsCardWalletApplePay struct {
}
// ChargePaymentMethodDetailsCardWalletGooglePay represents the details of the Google Pay wallet.
type ChargePaymentMethodDetailsCardWalletGooglePay struct {
}
// ChargePaymentMethodDetailsCardWalletMasterpass represents the details of the Masterpass wallet.
type ChargePaymentMethodDetailsCardWalletMasterpass struct {
BillingAddress *Address `json:"billing_address"`
Email string `json:"email"`
Name string `json:"name"`
ShippingAddress *Address `json:"shipping_address"`
}
// ChargePaymentMethodDetailsCardWalletSamsungPay represents the details of the Samsung Pay wallet.
type ChargePaymentMethodDetailsCardWalletSamsungPay struct {
}
// ChargePaymentMethodDetailsCardWalletVisaCheckout represents the details of the Visa Checkout
// wallet.
type ChargePaymentMethodDetailsCardWalletVisaCheckout struct {
BillingAddress *Address `json:"billing_address"`
Email string `json:"email"`
Name string `json:"name"`
ShippingAddress *Address `json:"shipping_address"`
}
// ChargePaymentMethodDetailsCardWallet represents the details of the card wallet if this Card
// PaymentMethod is part of a card wallet.
type ChargePaymentMethodDetailsCardWallet struct {
AmexExpressCheckout *ChargePaymentMethodDetailsCardWalletAmexExpressCheckout `json:"amex_express_checkout"`
ApplePay *ChargePaymentMethodDetailsCardWalletApplePay `json:"apple_pay"`
DynamicLast4 string `json:"dynamic_last4"`
GooglePay *ChargePaymentMethodDetailsCardWalletGooglePay `json:"google_pay"`
Masterpass *ChargePaymentMethodDetailsCardWalletMasterpass `json:"masterpass"`
SamsungPay *ChargePaymentMethodDetailsCardWalletSamsungPay `json:"samsung_pay"`
Type PaymentMethodCardWalletType `json:"type"`
VisaCheckout *ChargePaymentMethodDetailsCardWalletVisaCheckout `json:"visa_checkout"`
}
// ChargePaymentMethodDetailsCard represents details about the Card PaymentMethod.
type ChargePaymentMethodDetailsCard struct {
Brand PaymentMethodCardBrand `json:"brand"`
Checks *ChargePaymentMethodDetailsCardChecks `json:"checks"`
Country string `json:"country"`
ExpMonth uint64 `json:"exp_month"`
ExpYear uint64 `json:"exp_year"`
Fingerprint string `json:"fingerprint"`
Funding CardFunding `json:"funding"`
Installments *ChargePaymentMethodDetailsCardInstallments `json:"installments"`
Last4 string `json:"last4"`
Network PaymentMethodCardNetwork `json:"network"`
MOTO bool `json:"moto"`
ThreeDSecure *ChargePaymentMethodDetailsCardThreeDSecure `json:"three_d_secure"`
Wallet *ChargePaymentMethodDetailsCardWallet `json:"wallet"`
// Please note that the fields below are for internal use only and are not returned
// as part of standard API requests.
Description string `json:"description"`
IIN string `json:"iin"`
Issuer string `json:"issuer"`
}
// ChargePaymentMethodDetailsCardPresentReceipt represents details about the receipt on a
// Card Present PaymentMethod.
type ChargePaymentMethodDetailsCardPresentReceipt struct {
ApplicationCryptogram string `json:"application_cryptogram"`
ApplicationPreferredName string `json:"application_preferred_name"`
AuthorizationCode string `json:"authorization_code"`
AuthorizationResponseCode string `json:"authorization_response_code"`
CardholderVerificationMethod string `json:"cardholder_verification_method"`
DedicatedFileName string `json:"dedicated_file_name"`
TerminalVerificationResults string `json:"terminal_verification_results"`
TransactionStatusInformation string `json:"transaction_status_information"`
}
// ChargePaymentMethodDetailsCardPresent represents details about the Card Present PaymentMethod.
type ChargePaymentMethodDetailsCardPresent struct {
Brand PaymentMethodCardBrand `json:"brand"`
Country string `json:"country"`
EmvAuthData string `json:"emv_auth_data"`
ExpMonth uint64 `json:"exp_month"`
ExpYear uint64 `json:"exp_year"`
Fingerprint string `json:"fingerprint"`
Funding CardFunding `json:"funding"`
GeneratedCard string `json:"generated_card"`
Last4 string `json:"last4"`
Network PaymentMethodCardNetwork `json:"network"`
ReadMethod string `json:"read_method"`
Receipt *ChargePaymentMethodDetailsCardPresentReceipt `json:"receipt"`
}
// ChargePaymentMethodDetailsEps represents details about the EPS PaymentMethod.
type ChargePaymentMethodDetailsEps struct {
VerifiedName string `json:"verified_name"`
}
// ChargePaymentMethodDetailsFPX represents details about the FPX PaymentMethod.
type ChargePaymentMethodDetailsFPX struct {
AccountHolderType PaymentMethodFPXAccountHolderType `json:"account_holder_type"`
Bank string `json:"bank"`
TransactionID string `json:"transaction_id"`
}
// ChargePaymentMethodDetailsGiropay represents details about the Giropay PaymentMethod.
type ChargePaymentMethodDetailsGiropay struct {
BankCode string `json:"bank_code"`
BankName string `json:"bank_name"`
Bic string `json:"bic"`
VerifiedName string `json:"verified_name"`
}
// ChargePaymentMethodDetailsIdeal represents details about the Ideal PaymentMethod.
type ChargePaymentMethodDetailsIdeal struct {
Bank string `json:"bank"`
Bic string `json:"bic"`
IbanLast4 string `json:"iban_last4"`
VerifiedName string `json:"verified_name"`
}
// ChargePaymentMethodDetailsKlarna represents details for the Klarna
// PaymentMethod.
type ChargePaymentMethodDetailsKlarna struct {
}
// ChargePaymentMethodDetailsMultibanco represents details about the Multibanco PaymentMethod.
type ChargePaymentMethodDetailsMultibanco struct {
Entity string `json:"entity"`
Reference string `json:"reference"`
}
// ChargePaymentMethodDetailsP24 represents details about the P24 PaymentMethod.
type ChargePaymentMethodDetailsP24 struct {
Reference string `json:"reference"`
VerifiedName string `json:"verified_name"`
}
// ChargePaymentMethodDetailsSepaDebit represents details about the Sepa Debit PaymentMethod.
type ChargePaymentMethodDetailsSepaDebit struct {
BankCode string `json:"bank_code"`
BranchCode string `json:"branch_code"`
Country string `json:"country"`
Fingerprint string `json:"fingerprint"`
Last4 string `json:"last4"`
}
// ChargePaymentMethodDetailsSofort represents details about the Sofort PaymentMethod.
type ChargePaymentMethodDetailsSofort struct {
BankCode string `json:"bank_code"`
BankName string `json:"bank_name"`
Bic string `json:"bic"`
Country string `json:"country"`
IbanLast4 string `json:"iban_last4"`
VerifiedName string `json:"verified_name"`
}
// ChargePaymentMethodDetailsStripeAccount represents details about the StripeAccount PaymentMethod.
type ChargePaymentMethodDetailsStripeAccount struct {
}
// ChargePaymentMethodDetailsWechat represents details about the Wechat PaymentMethod.
type ChargePaymentMethodDetailsWechat struct {
}
// ChargePaymentMethodDetails represents the details about the PaymentMethod associated with the
// charge.
type ChargePaymentMethodDetails struct {
AchCreditTransfer *ChargePaymentMethodDetailsAchCreditTransfer `json:"ach_credit_transfer"`
AchDebit *ChargePaymentMethodDetailsAchDebit `json:"ach_debit"`
Alipay *ChargePaymentMethodDetailsAlipay `json:"alipay"`
Bancontact *ChargePaymentMethodDetailsBancontact `json:"bancontact"`
AUBECSDebit *ChargePaymentMethodDetailsAUBECSDebit `json:"au_becs_debit"`
Bitcoin *ChargePaymentMethodDetailsBitcoin `json:"bitcoin"`
Card *ChargePaymentMethodDetailsCard `json:"card"`
CardPresent *ChargePaymentMethodDetailsCardPresent `json:"card_present"`
Eps *ChargePaymentMethodDetailsEps `json:"eps"`
FPX *ChargePaymentMethodDetailsFPX `json:"fpx"`
Giropay *ChargePaymentMethodDetailsGiropay `json:"giropay"`
Ideal *ChargePaymentMethodDetailsIdeal `json:"ideal"`
Klarna *ChargePaymentMethodDetailsKlarna `json:"klarna"`
Multibanco *ChargePaymentMethodDetailsMultibanco `json:"multibanco"`
P24 *ChargePaymentMethodDetailsP24 `json:"p24"`
SepaDebit *ChargePaymentMethodDetailsSepaDebit `json:"sepa_debit"`
Sofort *ChargePaymentMethodDetailsSofort `json:"sofort"`
StripeAccount *ChargePaymentMethodDetailsStripeAccount `json:"stripe_account"`
Type ChargePaymentMethodDetailsType `json:"type"`
Wechat *ChargePaymentMethodDetailsWechat `json:"wechat"`
}
// ChargeTransferData represents the information for the transfer_data associated with a charge.
type ChargeTransferData struct {
Amount int64 `form:"amount"`
Destination *Account `json:"destination"`
}
// Charge is the resource representing a Stripe charge.
// For more details see https://stripe.com/docs/api#charges.
type Charge struct {
Amount int64 `json:"amount"`
AmountRefunded int64 `json:"amount_refunded"`
Application *Application `json:"application"`
ApplicationFee *ApplicationFee `json:"application_fee"`
ApplicationFeeAmount int64 `json:"application_fee_amount"`
AuthorizationCode string `json:"authorization_code"`
BalanceTransaction *BalanceTransaction `json:"balance_transaction"`
BillingDetails *BillingDetails `json:"billing_details"`
Captured bool `json:"captured"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Customer *Customer `json:"customer"`
Description string `json:"description"`
Destination *Account `json:"destination"`
Dispute *Dispute `json:"dispute"`
Disputed bool `json:"disputed"`
FailureCode string `json:"failure_code"`
FailureMessage string `json:"failure_message"`
FraudDetails *FraudDetails `json:"fraud_details"`
ID string `json:"id"`
Invoice *Invoice `json:"invoice"`
Level3 ChargeLevel3 `json:"level3"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
OnBehalfOf *Account `json:"on_behalf_of"`
Outcome *ChargeOutcome `json:"outcome"`
Paid bool `json:"paid"`
PaymentIntent string `json:"payment_intent"`
PaymentMethod string `json:"payment_method"`
PaymentMethodDetails *ChargePaymentMethodDetails `json:"payment_method_details"`
ReceiptEmail string `json:"receipt_email"`
ReceiptNumber string `json:"receipt_number"`
ReceiptURL string `json:"receipt_url"`
Refunded bool `json:"refunded"`
Refunds *RefundList `json:"refunds"`
Review *Review `json:"review"`
Shipping *ShippingDetails `json:"shipping"`
Source *PaymentSource `json:"source"`
SourceTransfer *Transfer `json:"source_transfer"`
StatementDescriptor string `json:"statement_descriptor"`
StatementDescriptorSuffix string `json:"statement_descriptor_suffix"`
Status string `json:"status"`
Transfer *Transfer `json:"transfer"`
TransferData *ChargeTransferData `json:"transfer_data"`
TransferGroup string `json:"transfer_group"`
}
// UnmarshalJSON handles deserialization of a charge.
// This custom unmarshaling is needed because the resulting
// property may be an ID or the full struct if it was expanded.
func (c *Charge) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type charge Charge
var v charge
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = Charge(v)
return nil
}
// ChargeList is a list of charges as retrieved from a list endpoint.
type ChargeList struct {
ListMeta
Data []*Charge `json:"data"`
}
// FraudDetails is the structure detailing fraud status.
type FraudDetails struct {
UserReport ChargeFraudUserReport `json:"user_report"`
StripeReport ChargeFraudStripeReport `json:"stripe_report"`
}
// ChargeOutcomeRule tells you the Radar rule that blocked the charge, if any.
type ChargeOutcomeRule struct {
Action string `json:"action"`
ID string `json:"id"`
Predicate string `json:"predicate"`
}
// ChargeOutcome is the charge's outcome that details whether a payment
// was accepted and why.
type ChargeOutcome struct {
NetworkStatus string `json:"network_status"`
Reason string `json:"reason"`
RiskLevel string `json:"risk_level"`
RiskScore int64 `json:"risk_score"`
Rule *ChargeOutcomeRule `json:"rule"`
SellerMessage string `json:"seller_message"`
Type string `json:"type"`
}
// ShippingDetails is the structure containing shipping information.
type ShippingDetails struct {
Address *Address `json:"address"`
Carrier string `json:"carrier"`
Name string `json:"name"`
Phone string `json:"phone"`
TrackingNumber string `json:"tracking_number"`
}
var depth = -1
// UnmarshalJSON handles deserialization of a ChargeOutcomeRule.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *ChargeOutcomeRule) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type chargeOutcomeRule ChargeOutcomeRule
var v chargeOutcomeRule
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = ChargeOutcomeRule(v)
return nil
}

211
vendor/github.com/stripe/stripe-go/checkout_session.go generated vendored Normal file
View file

@ -0,0 +1,211 @@
package stripe
import (
"encoding/json"
)
// CheckoutSessionSubmitType is the list of allowed values for the `submit_type`
// of a Session.
type CheckoutSessionSubmitType string
// List of values that CheckoutSessionSubmitType can take.
const (
CheckoutSessionSubmitTypeAuto CheckoutSessionSubmitType = "auto"
CheckoutSessionSubmitTypeBook CheckoutSessionSubmitType = "book"
CheckoutSessionSubmitTypeDonate CheckoutSessionSubmitType = "donate"
CheckoutSessionSubmitTypePay CheckoutSessionSubmitType = "pay"
)
// CheckoutSessionDisplayItemType is the list of allowed values for the display item type.
type CheckoutSessionDisplayItemType string
// List of values that CheckoutSessionDisplayItemType can take.
const (
CheckoutSessionDisplayItemTypeCustom CheckoutSessionDisplayItemType = "custom"
CheckoutSessionDisplayItemTypePlan CheckoutSessionDisplayItemType = "plan"
CheckoutSessionDisplayItemTypeSKU CheckoutSessionDisplayItemType = "sku"
)
// CheckoutSessionMode is the list of allowed values for the mode on a Session.
type CheckoutSessionMode string
// List of values that CheckoutSessionMode can take.
const (
CheckoutSessionModePayment CheckoutSessionMode = "payment"
CheckoutSessionModeSetup CheckoutSessionMode = "setup"
CheckoutSessionModeSubscription CheckoutSessionMode = "subscription"
)
// CheckoutSessionLineItemParams is the set of parameters allowed for a line item
// on a checkout session.
type CheckoutSessionLineItemParams struct {
Amount *int64 `form:"amount"`
Currency *string `form:"currency"`
Description *string `form:"description"`
Images []*string `form:"images"`
Name *string `form:"name"`
Quantity *int64 `form:"quantity"`
TaxRates []*string `form:"tax_rates"`
}
// CheckoutSessionPaymentIntentDataTransferDataParams is the set of parameters allowed for the
// transfer_data hash.
type CheckoutSessionPaymentIntentDataTransferDataParams struct {
Amount *int64 `form:"amount"`
Destination *string `form:"destination"`
}
// CheckoutSessionPaymentIntentDataParams is the set of parameters allowed for the
// payment intent creation on a checkout session.
type CheckoutSessionPaymentIntentDataParams struct {
Params `form:"*"`
ApplicationFeeAmount *int64 `form:"application_fee_amount"`
CaptureMethod *string `form:"capture_method"`
Description *string `form:"description"`
OnBehalfOf *string `form:"on_behalf_of"`
ReceiptEmail *string `form:"receipt_email"`
SetupFutureUsage *string `form:"setup_future_usage"`
Shipping *ShippingDetailsParams `form:"shipping"`
StatementDescriptor *string `form:"statement_descriptor"`
StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"`
TransferData *CheckoutSessionPaymentIntentDataTransferDataParams `form:"transfer_data"`
}
// CheckoutSessionSetupIntentDataParams is the set of parameters allowed for the setup intent
// creation on a checkout session.
type CheckoutSessionSetupIntentDataParams struct {
Params `form:"*"`
Description *string `form:"description"`
OnBehalfOf *string `form:"on_behalf_of"`
}
// CheckoutSessionShippingAddressCollectionParams is the set of parameters allowed for the
// shipping address collection.
type CheckoutSessionShippingAddressCollectionParams struct {
AllowedCountries []*string `form:"allowed_countries"`
}
// CheckoutSessionSubscriptionDataItemsParams is the set of parameters allowed for one item on a
// checkout session associated with a subscription.
type CheckoutSessionSubscriptionDataItemsParams struct {
Plan *string `form:"plan"`
Quantity *int64 `form:"quantity"`
TaxRates []*string `form:"tax_rates"`
}
// CheckoutSessionSubscriptionDataParams is the set of parameters allowed for the subscription
// creation on a checkout session.
type CheckoutSessionSubscriptionDataParams struct {
Params `form:"*"`
ApplicationFeePercent *float64 `form:"application_fee_percent"`
DefaultTaxRates []*string `form:"default_tax_rates"`
Items []*CheckoutSessionSubscriptionDataItemsParams `form:"items"`
TrialEnd *int64 `form:"trial_end"`
TrialFromPlan *bool `form:"trial_from_plan"`
TrialPeriodDays *int64 `form:"trial_period_days"`
}
// CheckoutSessionParams is the set of parameters that can be used when creating
// a checkout session.
// For more details see https://stripe.com/docs/api/checkout/sessions/create
type CheckoutSessionParams struct {
Params `form:"*"`
BillingAddressCollection *string `form:"billing_address_collection"`
CancelURL *string `form:"cancel_url"`
ClientReferenceID *string `form:"client_reference_id"`
Customer *string `form:"customer"`
CustomerEmail *string `form:"customer_email"`
LineItems []*CheckoutSessionLineItemParams `form:"line_items"`
Locale *string `form:"locale"`
Mode *string `form:"mode"`
PaymentIntentData *CheckoutSessionPaymentIntentDataParams `form:"payment_intent_data"`
PaymentMethodTypes []*string `form:"payment_method_types"`
SetupIntentData *CheckoutSessionSetupIntentDataParams `form:"setup_intent_data"`
ShippingAddressCollection *CheckoutSessionShippingAddressCollectionParams `form:"shipping_address_collection"`
SubscriptionData *CheckoutSessionSubscriptionDataParams `form:"subscription_data"`
SubmitType *string `form:"submit_type"`
SuccessURL *string `form:"success_url"`
}
// CheckoutSessionListParams is the set of parameters that can be
// used when listing sessions.
// For more details see: https://stripe.com/docs/api/checkout/sessions/list
type CheckoutSessionListParams struct {
ListParams `form:"*"`
PaymentIntent *string `form:"payment_intent"`
Subscription *string `form:"subscription"`
}
// CheckoutSessionDisplayItemCustom represents an item of type custom in a checkout session
type CheckoutSessionDisplayItemCustom struct {
Description string `json:"description"`
Images []string `json:"images"`
Name string `json:"name"`
}
// CheckoutSessionDisplayItem represents one of the items in a checkout session.
type CheckoutSessionDisplayItem struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
Custom *CheckoutSessionDisplayItemCustom `json:"custom"`
Quantity int64 `json:"quantity"`
Plan *Plan `json:"plan"`
SKU *SKU `json:"sku"`
Type CheckoutSessionDisplayItemType `json:"type"`
}
// CheckoutSessionShippingAddressCollection is the set of parameters allowed for the
// shipping address collection.
type CheckoutSessionShippingAddressCollection struct {
AllowedCountries []string `json:"allowed_countries"`
}
// CheckoutSession is the resource representing a Stripe checkout session.
// For more details see https://stripe.com/docs/api/checkout/sessions/object
type CheckoutSession struct {
CancelURL string `json:"cancel_url"`
ClientReferenceID string `json:"client_reference_id"`
Customer *Customer `json:"customer"`
CustomerEmail string `json:"customer_email"`
Deleted bool `json:"deleted"`
DisplayItems []*CheckoutSessionDisplayItem `json:"display_items"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
Locale string `json:"locale"`
Metadata map[string]string `json:"metadata"`
Mode CheckoutSessionMode `json:"mode"`
Object string `json:"object"`
PaymentIntent *PaymentIntent `json:"payment_intent"`
PaymentMethodTypes []string `json:"payment_method_types"`
SetupIntent *SetupIntent `json:"setup_intent"`
Shipping *ShippingDetails `json:"shipping"`
ShippingAddressCollection *CheckoutSessionShippingAddressCollection `json:"shipping_address_collection"`
Subscription *Subscription `json:"subscription"`
SubmitType CheckoutSessionSubmitType `json:"submit_type"`
SuccessURL string `json:"success_url"`
}
// CheckoutSessionList is a list of sessions as retrieved from a list endpoint.
type CheckoutSessionList struct {
ListMeta
Data []*CheckoutSession `json:"data"`
}
// UnmarshalJSON handles deserialization of a checkout session.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (p *CheckoutSession) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
p.ID = id
return nil
}
type session CheckoutSession
var v session
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*p = CheckoutSession(v)
return nil
}

39
vendor/github.com/stripe/stripe-go/countryspec.go generated vendored Normal file
View file

@ -0,0 +1,39 @@
package stripe
// Country is the list of supported countries
type Country string
// VerificationFieldsList lists the fields needed for an account verification.
// For more details see https://stripe.com/docs/api#country_spec_object-verification_fields.
type VerificationFieldsList struct {
AdditionalFields []string `json:"additional"`
Minimum []string `json:"minimum"`
}
// CountrySpec is the resource representing the rules required for a Stripe account.
// For more details see https://stripe.com/docs/api/#country_specs.
type CountrySpec struct {
DefaultCurrency Currency `json:"default_currency"`
ID string `json:"id"`
SupportedBankAccountCurrencies map[Currency][]Country `json:"supported_bank_account_currencies"`
SupportedPaymentCurrencies []Currency `json:"supported_payment_currencies"`
SupportedPaymentMethods []string `json:"supported_payment_methods"`
SupportedTransferCountries []string `json:"supported_transfer_countries"`
VerificationFields map[AccountBusinessType]*VerificationFieldsList `json:"verification_fields"`
}
// CountrySpecParams are the parameters allowed during CountrySpec retrieval.
type CountrySpecParams struct {
Params `form:"*"`
}
// CountrySpecList is a list of country specs as retrieved from a list endpoint.
type CountrySpecList struct {
ListMeta
Data []*CountrySpec `json:"data"`
}
// CountrySpecListParams are the parameters allowed during CountrySpec listing.
type CountrySpecListParams struct {
ListParams `form:"*"`
}

81
vendor/github.com/stripe/stripe-go/coupon.go generated vendored Normal file
View file

@ -0,0 +1,81 @@
package stripe
import "encoding/json"
// CouponDuration is the list of allowed values for the coupon's duration.
type CouponDuration string
// List of values that CouponDuration can take.
const (
CouponDurationForever CouponDuration = "forever"
CouponDurationOnce CouponDuration = "once"
CouponDurationRepeating CouponDuration = "repeating"
)
// CouponParams is the set of parameters that can be used when creating a coupon.
// For more details see https://stripe.com/docs/api#create_coupon.
type CouponParams struct {
Params `form:"*"`
AmountOff *int64 `form:"amount_off"`
Currency *string `form:"currency"`
Duration *string `form:"duration"`
DurationInMonths *int64 `form:"duration_in_months"`
ID *string `form:"id"`
MaxRedemptions *int64 `form:"max_redemptions"`
Name *string `form:"name"`
PercentOff *float64 `form:"percent_off"`
RedeemBy *int64 `form:"redeem_by"`
}
// CouponListParams is the set of parameters that can be used when listing coupons.
// For more detail see https://stripe.com/docs/api#list_coupons.
type CouponListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
}
// Coupon is the resource representing a Stripe coupon.
// For more details see https://stripe.com/docs/api#coupons.
type Coupon struct {
AmountOff int64 `json:"amount_off"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Deleted bool `json:"deleted"`
Duration CouponDuration `json:"duration"`
DurationInMonths int64 `json:"duration_in_months"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
MaxRedemptions int64 `json:"max_redemptions"`
Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
PercentOff float64 `json:"percent_off"`
RedeemBy int64 `json:"redeem_by"`
TimesRedeemed int64 `json:"times_redeemed"`
Valid bool `json:"valid"`
}
// CouponList is a list of coupons as retrieved from a list endpoint.
type CouponList struct {
ListMeta
Data []*Coupon `json:"data"`
}
// UnmarshalJSON handles deserialization of a Coupon.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *Coupon) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type coupon Coupon
var v coupon
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = Coupon(v)
return nil
}

204
vendor/github.com/stripe/stripe-go/creditnote.go generated vendored Normal file
View file

@ -0,0 +1,204 @@
package stripe
import "encoding/json"
// CreditNoteReason is the reason why a given credit note was created.
type CreditNoteReason string
// List of values that CreditNoteReason can take.
const (
CreditNoteReasonDuplicate CreditNoteReason = "duplicate"
CreditNoteReasonFraudulent CreditNoteReason = "fraudulent"
CreditNoteReasonOrderChange CreditNoteReason = "order_change"
CreditNoteReasonProductUnsatisfactory CreditNoteReason = "product_unsatisfactory"
)
// CreditNoteStatus is the list of allowed values for the credit note's status.
type CreditNoteStatus string
// List of values that CreditNoteStatus can take.
const (
CreditNoteStatusIssued CreditNoteStatus = "issued"
CreditNoteStatusVoid CreditNoteStatus = "void"
)
// CreditNoteType is the list of allowed values for the credit note's type.
type CreditNoteType string
// List of values that CreditNoteType can take.
const (
CreditNoteTypePostPayment CreditNoteType = "post_payment"
CreditNoteTypePrePayment CreditNoteType = "pre_payment"
)
// CreditNoteLineItemType is the list of allowed values for the credit note line item's type.
type CreditNoteLineItemType string
// List of values that CreditNoteType can take.
const (
CreditNoteLineItemTypeCustomLineItem CreditNoteLineItemType = "custom_line_item"
CreditNoteLineItemTypeInvoiceLineItem CreditNoteLineItemType = "invoice_line_item"
)
// CreditNoteParams is the set of parameters that can be used when creating or updating a credit note.
// For more details see https://stripe.com/docs/api/credit_notes/create, https://stripe.com/docs/api/credit_notes/update.
type CreditNoteParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
CreditAmount *int64 `form:"credit_amount"`
Invoice *string `form:"invoice"`
Lines []*CreditNoteLineParams `form:"lines"`
Memo *string `form:"memo"`
OutOfBandAmount *int64 `form:"out_of_band_amount"`
Reason *string `form:"reason"`
Refund *string `form:"refund"`
RefundAmount *int64 `form:"refund_amount"`
}
// CreditNoteListParams is the set of parameters that can be used when listing credit notes.
// For more details see https://stripe.com/docs/api/credit_notes/list.
type CreditNoteListParams struct {
ListParams `form:"*"`
Customer *string `form:"customer"`
Invoice *string `form:"invoice"`
}
// CreditNoteLineItemListParams is the set of parameters that can be used when listing credit note line items.
type CreditNoteLineItemListParams struct {
ListParams `form:"*"`
// ID is the credit note ID to list line items for.
ID *string `form:"-"` // Goes in the URL
}
// CreditNoteLineItemListPreviewParams is the set of parameters that can be used when previewing a credit note's line items
type CreditNoteLineItemListPreviewParams struct {
ListParams `form:"*"`
Amount *int64 `form:"amount"`
CreditAmount *int64 `form:"credit_amount"`
Invoice *string `form:"invoice"`
Lines []*CreditNoteLineParams `form:"lines"`
Memo *string `form:"memo"`
OutOfBandAmount *int64 `form:"out_of_band_amount"`
Reason *string `form:"reason"`
Refund *string `form:"refund"`
RefundAmount *int64 `form:"refund_amount"`
}
// CreditNoteLineParams is the set of parameters that can be used for a line item when creating
// or previewing a credit note.
type CreditNoteLineParams struct {
Amount *int64 `form:"amount"`
Description *string `form:"description"`
InvoiceLineItem *string `form:"invoice_line_item"`
Quantity *int64 `form:"quantity"`
TaxRates []*string `form:"tax_rates"`
UnitAmount *int64 `form:"unit_amount"`
UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"`
Type *string `form:"type"`
}
// CreditNotePreviewParams is the set of parameters that can be used when previewing a credit note.
// For more details see https://stripe.com/docs/api/credit_notes/preview.
type CreditNotePreviewParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
CreditAmount *int64 `form:"credit_amount"`
Invoice *string `form:"invoice"`
Lines []*CreditNoteLineParams `form:"lines"`
Memo *string `form:"memo"`
OutOfBandAmount *int64 `form:"out_of_band_amount"`
Reason *string `form:"reason"`
Refund *string `form:"refund"`
RefundAmount *int64 `form:"refund_amount"`
}
// CreditNoteVoidParams is the set of parameters that can be used when voiding invoices.
type CreditNoteVoidParams struct {
Params `form:"*"`
}
// CreditNoteTaxAmount represent the tax amount applied to a credit note.
type CreditNoteTaxAmount struct {
Amount int64 `json:"amount"`
Inclusive bool `json:"inclusive"`
TaxRate *TaxRate `json:"tax_rate"`
}
// CreditNote is the resource representing a Stripe credit note.
// For more details see https://stripe.com/docs/api/credit_notes/object.
type CreditNote struct {
Amount int64 `json:"amount"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Customer *Customer `json:"customer"`
CustomerBalanceTransaction *CustomerBalanceTransaction `json:"customer_balance_transaction"`
DiscountAmount int64 `json:"discount_amount"`
Invoice *Invoice `json:"invoice"`
ID string `json:"id"`
Lines *CreditNoteLineItemList `json:"lines"`
Livemode bool `json:"livemode"`
Memo string `json:"memo"`
Metadata map[string]string `json:"metadata"`
Number string `json:"number"`
Object string `json:"object"`
OutOfBandAmount int64 `json:"out_of_band_amount"`
PDF string `json:"pdf"`
Reason CreditNoteReason `json:"reason"`
Refund *Refund `json:"refund"`
Status CreditNoteStatus `json:"status"`
Subtotal int64 `json:"subtotal"`
TaxAmounts []*CreditNoteTaxAmount `json:"tax_amounts"`
Total int64 `json:"total"`
Type CreditNoteType `json:"type"`
VoidedAt int64 `json:"voided_at"`
}
// CreditNoteLineItem is the resource representing a Stripe credit note line item.
// For more details see https://stripe.com/docs/api/credit_notes/line_item
type CreditNoteLineItem struct {
Amount int64 `json:"amount"`
Description string `json:"description"`
DiscountAmount int64 `json:"discount_amount"`
ID string `json:"id"`
InvoiceLineItem string `json:"invoice_line_item"`
Livemode bool `json:"livemode"`
Object string `json:"object"`
Quantity int64 `json:"quantity"`
TaxAmounts []*CreditNoteTaxAmount `json:"tax_amounts"`
TaxRates []*TaxRate `json:"tax_rates"`
Type CreditNoteLineItemType `json:"type"`
UnitAmount int64 `json:"unit_amount"`
UnitAmountDecimal float64 `json:"unit_amount_decimal,string"`
}
// CreditNoteList is a list of credit notes as retrieved from a list endpoint.
type CreditNoteList struct {
ListMeta
Data []*CreditNote `json:"data"`
}
// CreditNoteLineItemList is a list of credit note line items as retrieved from a list endpoint.
type CreditNoteLineItemList struct {
ListMeta
Data []*CreditNoteLineItem `json:"data"`
}
// UnmarshalJSON handles deserialization of a CreditNote.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *CreditNote) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type note CreditNote
var v note
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = CreditNote(v)
return nil
}

148
vendor/github.com/stripe/stripe-go/currency.go generated vendored Normal file
View file

@ -0,0 +1,148 @@
package stripe
// Currency is the list of supported currencies.
// For more details see https://support.stripe.com/questions/which-currencies-does-stripe-support.
type Currency string
// List of values that Currency can take.
const (
CurrencyAED Currency = "aed" // United Arab Emirates Dirham
CurrencyAFN Currency = "afn" // Afghan Afghani
CurrencyALL Currency = "all" // Albanian Lek
CurrencyAMD Currency = "amd" // Armenian Dram
CurrencyANG Currency = "ang" // Netherlands Antillean Gulden
CurrencyAOA Currency = "aoa" // Angolan Kwanza
CurrencyARS Currency = "ars" // Argentine Peso
CurrencyAUD Currency = "aud" // Australian Dollar
CurrencyAWG Currency = "awg" // Aruban Florin
CurrencyAZN Currency = "azn" // Azerbaijani Manat
CurrencyBAM Currency = "bam" // Bosnia & Herzegovina Convertible Mark
CurrencyBBD Currency = "bbd" // Barbadian Dollar
CurrencyBDT Currency = "bdt" // Bangladeshi Taka
CurrencyBGN Currency = "bgn" // Bulgarian Lev
CurrencyBIF Currency = "bif" // Burundian Franc
CurrencyBMD Currency = "bmd" // Bermudian Dollar
CurrencyBND Currency = "bnd" // Brunei Dollar
CurrencyBOB Currency = "bob" // Bolivian Boliviano
CurrencyBRL Currency = "brl" // Brazilian Real
CurrencyBSD Currency = "bsd" // Bahamian Dollar
CurrencyBWP Currency = "bwp" // Botswana Pula
CurrencyBZD Currency = "bzd" // Belize Dollar
CurrencyCAD Currency = "cad" // Canadian Dollar
CurrencyCDF Currency = "cdf" // Congolese Franc
CurrencyCHF Currency = "chf" // Swiss Franc
CurrencyCLP Currency = "clp" // Chilean Peso
CurrencyCNY Currency = "cny" // Chinese Renminbi Yuan
CurrencyCOP Currency = "cop" // Colombian Peso
CurrencyCRC Currency = "crc" // Costa Rican Colón
CurrencyCVE Currency = "cve" // Cape Verdean Escudo
CurrencyCZK Currency = "czk" // Czech Koruna
CurrencyDJF Currency = "djf" // Djiboutian Franc
CurrencyDKK Currency = "dkk" // Danish Krone
CurrencyDOP Currency = "dop" // Dominican Peso
CurrencyDZD Currency = "dzd" // Algerian Dinar
CurrencyEEK Currency = "eek" // Estonian Kroon
CurrencyEGP Currency = "egp" // Egyptian Pound
CurrencyETB Currency = "etb" // Ethiopian Birr
CurrencyEUR Currency = "eur" // Euro
CurrencyFJD Currency = "fjd" // Fijian Dollar
CurrencyFKP Currency = "fkp" // Falkland Islands Pound
CurrencyGBP Currency = "gbp" // British Pound
CurrencyGEL Currency = "gel" // Georgian Lari
CurrencyGIP Currency = "gip" // Gibraltar Pound
CurrencyGMD Currency = "gmd" // Gambian Dalasi
CurrencyGNF Currency = "gnf" // Guinean Franc
CurrencyGTQ Currency = "gtq" // Guatemalan Quetzal
CurrencyGYD Currency = "gyd" // Guyanese Dollar
CurrencyHKD Currency = "hkd" // Hong Kong Dollar
CurrencyHNL Currency = "hnl" // Honduran Lempira
CurrencyHRK Currency = "hrk" // Croatian Kuna
CurrencyHTG Currency = "htg" // Haitian Gourde
CurrencyHUF Currency = "huf" // Hungarian Forint
CurrencyIDR Currency = "idr" // Indonesian Rupiah
CurrencyILS Currency = "ils" // Israeli New Sheqel
CurrencyINR Currency = "inr" // Indian Rupee
CurrencyISK Currency = "isk" // Icelandic Króna
CurrencyJMD Currency = "jmd" // Jamaican Dollar
CurrencyJPY Currency = "jpy" // Japanese Yen
CurrencyKES Currency = "kes" // Kenyan Shilling
CurrencyKGS Currency = "kgs" // Kyrgyzstani Som
CurrencyKHR Currency = "khr" // Cambodian Riel
CurrencyKMF Currency = "kmf" // Comorian Franc
CurrencyKRW Currency = "krw" // South Korean Won
CurrencyKYD Currency = "kyd" // Cayman Islands Dollar
CurrencyKZT Currency = "kzt" // Kazakhstani Tenge
CurrencyLAK Currency = "lak" // Lao Kip
CurrencyLBP Currency = "lbp" // Lebanese Pound
CurrencyLKR Currency = "lkr" // Sri Lankan Rupee
CurrencyLRD Currency = "lrd" // Liberian Dollar
CurrencyLSL Currency = "lsl" // Lesotho Loti
CurrencyLTL Currency = "ltl" // Lithuanian Litas
CurrencyLVL Currency = "lvl" // Latvian Lats
CurrencyMAD Currency = "mad" // Moroccan Dirham
CurrencyMDL Currency = "mdl" // Moldovan Leu
CurrencyMGA Currency = "mga" // Malagasy Ariary
CurrencyMKD Currency = "mkd" // Macedonian Denar
CurrencyMNT Currency = "mnt" // Mongolian Tögrög
CurrencyMOP Currency = "mop" // Macanese Pataca
CurrencyMRO Currency = "mro" // Mauritanian Ouguiya
CurrencyMUR Currency = "mur" // Mauritian Rupee
CurrencyMVR Currency = "mvr" // Maldivian Rufiyaa
CurrencyMWK Currency = "mwk" // Malawian Kwacha
CurrencyMXN Currency = "mxn" // Mexican Peso
CurrencyMYR Currency = "myr" // Malaysian Ringgit
CurrencyMZN Currency = "mzn" // Mozambican Metical
CurrencyNAD Currency = "nad" // Namibian Dollar
CurrencyNGN Currency = "ngn" // Nigerian Naira
CurrencyNIO Currency = "nio" // Nicaraguan Córdoba
CurrencyNOK Currency = "nok" // Norwegian Krone
CurrencyNPR Currency = "npr" // Nepalese Rupee
CurrencyNZD Currency = "nzd" // New Zealand Dollar
CurrencyPAB Currency = "pab" // Panamanian Balboa
CurrencyPEN Currency = "pen" // Peruvian Nuevo Sol
CurrencyPGK Currency = "pgk" // Papua New Guinean Kina
CurrencyPHP Currency = "php" // Philippine Peso
CurrencyPKR Currency = "pkr" // Pakistani Rupee
CurrencyPLN Currency = "pln" // Polish Złoty
CurrencyPYG Currency = "pyg" // Paraguayan Guaraní
CurrencyQAR Currency = "qar" // Qatari Riyal
CurrencyRON Currency = "ron" // Romanian Leu
CurrencyRSD Currency = "rsd" // Serbian Dinar
CurrencyRUB Currency = "rub" // Russian Ruble
CurrencyRWF Currency = "rwf" // Rwandan Franc
CurrencySAR Currency = "sar" // Saudi Riyal
CurrencySBD Currency = "sbd" // Solomon Islands Dollar
CurrencySCR Currency = "scr" // Seychellois Rupee
CurrencySEK Currency = "sek" // Swedish Krona
CurrencySGD Currency = "sgd" // Singapore Dollar
CurrencySHP Currency = "shp" // Saint Helenian Pound
CurrencySLL Currency = "sll" // Sierra Leonean Leone
CurrencySOS Currency = "sos" // Somali Shilling
CurrencySRD Currency = "srd" // Surinamese Dollar
CurrencySTD Currency = "std" // São Tomé and Príncipe Dobra
CurrencySVC Currency = "svc" // Salvadoran Colón
CurrencySZL Currency = "szl" // Swazi Lilangeni
CurrencyTHB Currency = "thb" // Thai Baht
CurrencyTJS Currency = "tjs" // Tajikistani Somoni
CurrencyTOP Currency = "top" // Tongan Paʻanga
CurrencyTRY Currency = "try" // Turkish Lira
CurrencyTTD Currency = "ttd" // Trinidad and Tobago Dollar
CurrencyTWD Currency = "twd" // New Taiwan Dollar
CurrencyTZS Currency = "tzs" // Tanzanian Shilling
CurrencyUAH Currency = "uah" // Ukrainian Hryvnia
CurrencyUGX Currency = "ugx" // Ugandan Shilling
CurrencyUSD Currency = "usd" // United States Dollar
CurrencyUYU Currency = "uyu" // Uruguayan Peso
CurrencyUZS Currency = "uzs" // Uzbekistani Som
CurrencyVEF Currency = "vef" // Venezuelan Bolívar
CurrencyVND Currency = "vnd" // Vietnamese Đồng
CurrencyVUV Currency = "vuv" // Vanuatu Vatu
CurrencyWST Currency = "wst" // Samoan Tala
CurrencyXAF Currency = "xaf" // Central African Cfa Franc
CurrencyXCD Currency = "xcd" // East Caribbean Dollar
CurrencyXOF Currency = "xof" // West African Cfa Franc
CurrencyXPF Currency = "xpf" // Cfp Franc
CurrencyYER Currency = "yer" // Yemeni Rial
CurrencyZAR Currency = "zar" // South African Rand
CurrencyZMW Currency = "zmw" // Zambian Kwacha
)

165
vendor/github.com/stripe/stripe-go/customer.go generated vendored Normal file
View file

@ -0,0 +1,165 @@
package stripe
import (
"encoding/json"
)
// CustomerTaxExempt is the type of tax exemption associated with a customer.
type CustomerTaxExempt string
// List of values that CustomerTaxExempt can take.
const (
CustomerTaxExemptExempt CustomerTaxExempt = "exempt"
CustomerTaxExemptNone CustomerTaxExempt = "none"
CustomerTaxExemptReverse CustomerTaxExempt = "reverse"
)
// CustomerParams is the set of parameters that can be used when creating or updating a customer.
// For more details see https://stripe.com/docs/api#create_customer and https://stripe.com/docs/api#update_customer.
type CustomerParams struct {
Params `form:"*"`
Address *AddressParams `form:"address"`
Balance *int64 `form:"balance"`
Coupon *string `form:"coupon"`
DefaultSource *string `form:"default_source"`
Description *string `form:"description"`
Email *string `form:"email"`
InvoicePrefix *string `form:"invoice_prefix"`
InvoiceSettings *CustomerInvoiceSettingsParams `form:"invoice_settings"`
Name *string `form:"name"`
NextInvoiceSequence *int64 `form:"next_invoice_sequence"`
PaymentMethod *string `form:"payment_method"`
Phone *string `form:"phone"`
PreferredLocales []*string `form:"preferred_locales"`
Shipping *CustomerShippingDetailsParams `form:"shipping"`
Source *SourceParams `form:"*"` // SourceParams has custom encoding so brought to top level with "*"
TaxExempt *string `form:"tax_exempt"`
TaxIDData []*CustomerTaxIDDataParams `form:"tax_id_data"`
Token *string `form:"-"` // This doesn't seem to be used?
// The parameters below are considered deprecated. Consider creating a Subscription separately instead.
Plan *string `form:"plan"`
Quantity *int64 `form:"quantity"`
TaxPercent *float64 `form:"tax_percent"`
TrialEnd *int64 `form:"trial_end"`
}
// CustomerInvoiceCustomFieldParams represents the parameters associated with one custom field on
// the customer's invoices.
type CustomerInvoiceCustomFieldParams struct {
Name *string `form:"name"`
Value *string `form:"value"`
}
// CustomerInvoiceSettingsParams is the structure containing the default settings for invoices
// associated with this customer.
type CustomerInvoiceSettingsParams struct {
CustomFields []*CustomerInvoiceCustomFieldParams `form:"custom_fields"`
DefaultPaymentMethod *string `form:"default_payment_method"`
Footer *string `form:"footer"`
}
// CustomerShippingDetailsParams is the structure containing shipping information.
type CustomerShippingDetailsParams struct {
Address *AddressParams `form:"address"`
Name *string `form:"name"`
Phone *string `form:"phone"`
}
// CustomerTaxIDDataParams lets you pass the tax id details associated with a Customer.
type CustomerTaxIDDataParams struct {
Type *string `form:"type"`
Value *string `form:"value"`
}
// SetSource adds valid sources to a CustomerParams object,
// returning an error for unsupported sources.
func (cp *CustomerParams) SetSource(sp interface{}) error {
source, err := SourceParamsFor(sp)
cp.Source = source
return err
}
// CustomerListParams is the set of parameters that can be used when listing customers.
// For more details see https://stripe.com/docs/api#list_customers.
type CustomerListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Email *string `form:"email"`
}
// Customer is the resource representing a Stripe customer.
// For more details see https://stripe.com/docs/api#customers.
type Customer struct {
Address Address `json:"address"`
Balance int64 `json:"balance"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
DefaultSource *PaymentSource `json:"default_source"`
Deleted bool `json:"deleted"`
Delinquent bool `json:"delinquent"`
Description string `json:"description"`
Discount *Discount `json:"discount"`
Email string `json:"email"`
ID string `json:"id"`
InvoicePrefix string `json:"invoice_prefix"`
InvoiceSettings *CustomerInvoiceSettings `json:"invoice_settings"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
NextInvoiceSequence int64 `json:"next_invoice_sequence"`
Phone string `json:"phone"`
PreferredLocales []string `json:"preferred_locales"`
Shipping *CustomerShippingDetails `json:"shipping"`
Sources *SourceList `json:"sources"`
Subscriptions *SubscriptionList `json:"subscriptions"`
TaxExempt CustomerTaxExempt `json:"tax_exempt"`
TaxIDs *TaxIDList `json:"tax_ids"`
}
// CustomerInvoiceCustomField represents a custom field associated with the customer's invoices.
type CustomerInvoiceCustomField struct {
Name *string `form:"name"`
Value *string `form:"value"`
}
// CustomerInvoiceSettings is the structure containing the default settings for invoices associated
// with this customer.
type CustomerInvoiceSettings struct {
CustomFields []*CustomerInvoiceCustomField `json:"custom_fields"`
DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"`
Footer string `json:"footer"`
}
// CustomerList is a list of customers as retrieved from a list endpoint.
type CustomerList struct {
ListMeta
Data []*Customer `json:"data"`
}
// CustomerShippingDetails is the structure containing shipping information.
type CustomerShippingDetails struct {
Address Address `json:"address"`
Name string `json:"name"`
Phone string `json:"phone"`
}
// UnmarshalJSON handles deserialization of a Customer.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *Customer) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type customer Customer
var v customer
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = Customer(v)
return nil
}

View file

@ -0,0 +1,81 @@
package stripe
import "encoding/json"
// CustomerBalanceTransactionType is the list of allowed values for the customer's balance
// transaction type.
type CustomerBalanceTransactionType string
// List of values that CustomerBalanceTransactionDuration can take.
const (
CustomerBalanceTransactionTypeAdjustment CustomerBalanceTransactionType = "adjustment"
CustomerBalanceTransactionTypeAppliedToInvoice CustomerBalanceTransactionType = "applied_to_invoice"
CustomerBalanceTransactionTypeCreditNote CustomerBalanceTransactionType = "credit_note"
CustomerBalanceTransactionTypeInitial CustomerBalanceTransactionType = "initial"
CustomerBalanceTransactionTypeInvoiceTooLarge CustomerBalanceTransactionType = "invoice_too_large"
CustomerBalanceTransactionTypeInvoiceTooSmall CustomerBalanceTransactionType = "invoice_too_small"
CustomerBalanceTransactionTypeUnspentReceiverCredit CustomerBalanceTransactionType = "unspent_receiver_credit"
)
// CustomerBalanceTransactionParams is the set of parameters that can be used when creating or
// updating a customer balance transactions.
// For more details see https://stripe.com/docs/api/customers/create_customer_balance_transaction
type CustomerBalanceTransactionParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
Customer *string `form:"-"`
Currency *string `form:"currency"`
Description *string `form:"description"`
}
// CustomerBalanceTransactionListParams is the set of parameters that can be used when listing
// customer balance transactions.
// For more detail see https://stripe.com/docs/api/customers/customer_balance_transactions
type CustomerBalanceTransactionListParams struct {
ListParams `form:"*"`
Customer *string `form:"-"`
}
// CustomerBalanceTransaction is the resource representing a customer balance transaction.
// For more details see https://stripe.com/docs/api/customers/customer_balance_transaction_object
type CustomerBalanceTransaction struct {
Amount int64 `json:"amount"`
Created int64 `json:"created"`
CreditNote *CreditNote `json:"credit_note"`
Currency Currency `json:"currency"`
Customer *Customer `json:"customer"`
Description string `json:"description"`
EndingBalance int64 `json:"ending_balance"`
ID string `json:"id"`
Invoice *Invoice `json:"invoice"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
Type CustomerBalanceTransactionType `json:"type"`
}
// CustomerBalanceTransactionList is a list of customer balance transactions as retrieved from a
// list endpoint.
type CustomerBalanceTransactionList struct {
ListMeta
Data []*CustomerBalanceTransaction `json:"data"`
}
// UnmarshalJSON handles deserialization of a CustomerBalanceTransaction.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *CustomerBalanceTransaction) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type transaction CustomerBalanceTransaction
var v transaction
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = CustomerBalanceTransaction(v)
return nil
}

17
vendor/github.com/stripe/stripe-go/discount.go generated vendored Normal file
View file

@ -0,0 +1,17 @@
package stripe
// DiscountParams is the set of parameters that can be used when deleting a discount.
type DiscountParams struct {
Params `form:"*"`
}
// Discount is the resource representing a Stripe discount.
// For more details see https://stripe.com/docs/api#discounts.
type Discount struct {
Coupon *Coupon `json:"coupon"`
Customer string `json:"customer"`
Deleted bool `json:"deleted"`
End int64 `json:"end"`
Start int64 `json:"start"`
Subscription string `json:"subscription"`
}

172
vendor/github.com/stripe/stripe-go/dispute.go generated vendored Normal file
View file

@ -0,0 +1,172 @@
package stripe
import (
"encoding/json"
)
// DisputeReason is the list of allowed values for a discount's reason.
type DisputeReason string
// List of values that DisputeReason can take.
const (
DisputeReasonCreditNotProcessed DisputeReason = "credit_not_processed"
DisputeReasonDuplicate DisputeReason = "duplicate"
DisputeReasonFraudulent DisputeReason = "fraudulent"
DisputeReasonGeneral DisputeReason = "general"
DisputeReasonProductNotReceived DisputeReason = "product_not_received"
DisputeReasonProductUnacceptable DisputeReason = "product_unacceptable"
DisputeReasonSubscriptionCanceled DisputeReason = "subscription_canceled"
DisputeReasonUnrecognized DisputeReason = "unrecognized"
)
// DisputeStatus is the list of allowed values for a discount's status.
type DisputeStatus string
// List of values that DisputeStatus can take.
const (
DisputeStatusChargeRefunded DisputeStatus = "charge_refunded"
DisputeStatusLost DisputeStatus = "lost"
DisputeStatusNeedsResponse DisputeStatus = "needs_response"
DisputeStatusUnderReview DisputeStatus = "under_review"
DisputeStatusWarningClosed DisputeStatus = "warning_closed"
DisputeStatusWarningNeedsResponse DisputeStatus = "warning_needs_response"
DisputeStatusWarningUnderReview DisputeStatus = "warning_under_review"
DisputeStatusWon DisputeStatus = "won"
)
// DisputeParams is the set of parameters that can be used when updating a dispute.
// For more details see https://stripe.com/docs/api#update_dispute.
type DisputeParams struct {
Params `form:"*"`
Evidence *DisputeEvidenceParams `form:"evidence"`
Submit *bool `form:"submit"`
}
// DisputeEvidenceParams is the set of parameters that can be used when submitting
// evidence for disputes.
type DisputeEvidenceParams struct {
AccessActivityLog *string `form:"access_activity_log"`
BillingAddress *string `form:"billing_address"`
CancellationPolicy *string `form:"cancellation_policy"`
CancellationPolicyDisclosure *string `form:"cancellation_policy_disclosure"`
CancellationRebuttal *string `form:"cancellation_rebuttal"`
CustomerCommunication *string `form:"customer_communication"`
CustomerEmailAddress *string `form:"customer_email_address"`
CustomerName *string `form:"customer_name"`
CustomerPurchaseIP *string `form:"customer_purchase_ip"`
CustomerSignature *string `form:"customer_signature"`
DuplicateChargeDocumentation *string `form:"duplicate_charge_documentation"`
DuplicateChargeExplanation *string `form:"duplicate_charge_explanation"`
DuplicateChargeID *string `form:"duplicate_charge_id"`
ProductDescription *string `form:"product_description"`
Receipt *string `form:"receipt"`
RefundPolicy *string `form:"refund_policy"`
RefundPolicyDisclosure *string `form:"refund_policy_disclosure"`
RefundRefusalExplanation *string `form:"refund_refusal_explanation"`
ServiceDate *string `form:"service_date"`
ServiceDocumentation *string `form:"service_documentation"`
ShippingAddress *string `form:"shipping_address"`
ShippingCarrier *string `form:"shipping_carrier"`
ShippingDate *string `form:"shipping_date"`
ShippingDocumentation *string `form:"shipping_documentation"`
ShippingTrackingNumber *string `form:"shipping_tracking_number"`
UncategorizedFile *string `form:"uncategorized_file"`
UncategorizedText *string `form:"uncategorized_text"`
}
// DisputeListParams is the set of parameters that can be used when listing disputes.
// For more details see https://stripe.com/docs/api#list_disputes.
type DisputeListParams struct {
ListParams `form:"*"`
Charge *string `form:"charge"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
PaymentIntent *string `form:"payment_intent"`
}
// Dispute is the resource representing a Stripe dispute.
// For more details see https://stripe.com/docs/api#disputes.
type Dispute struct {
Amount int64 `json:"amount"`
BalanceTransactions []*BalanceTransaction `json:"balance_transactions"`
Charge *Charge `json:"charge"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Evidence *DisputeEvidence `json:"evidence"`
EvidenceDetails *EvidenceDetails `json:"evidence_details"`
ID string `json:"id"`
IsChargeRefundable bool `json:"is_charge_refundable"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
PaymentIntent *PaymentIntent `json:"payment_intent"`
Reason DisputeReason `json:"reason"`
Status DisputeStatus `json:"status"`
}
// DisputeList is a list of disputes as retrieved from a list endpoint.
type DisputeList struct {
ListMeta
Data []*Dispute `json:"data"`
}
// EvidenceDetails is the structure representing more details about
// the dispute.
type EvidenceDetails struct {
DueBy int64 `json:"due_by"`
HasEvidence bool `json:"has_evidence"`
PastDue bool `json:"past_due"`
SubmissionCount int64 `json:"submission_count"`
}
// DisputeEvidence is the structure that contains various details about
// the evidence submitted for the dispute.
// Almost all fields are strings since there structures (i.e. address)
// do not typically get parsed by anyone and are thus presented as-received.
type DisputeEvidence struct {
AccessActivityLog string `json:"access_activity_log"`
BillingAddress string `json:"billing_address"`
CancellationPolicy *File `json:"cancellation_policy"`
CancellationPolicyDisclosure string `json:"cancellation_policy_disclosure"`
CancellationRebuttal string `json:"cancellation_rebuttal"`
CustomerCommunication *File `json:"customer_communication"`
CustomerEmailAddress string `json:"customer_email_address"`
CustomerName string `json:"customer_name"`
CustomerPurchaseIP string `json:"customer_purchase_ip"`
CustomerSignature *File `json:"customer_signature"`
DuplicateChargeDocumentation *File `json:"duplicate_charge_documentation"`
DuplicateChargeExplanation string `json:"duplicate_charge_explanation"`
DuplicateChargeID string `json:"duplicate_charge_id"`
ProductDescription string `json:"product_description"`
Receipt *File `json:"receipt"`
RefundPolicy *File `json:"refund_policy"`
RefundPolicyDisclosure string `json:"refund_policy_disclosure"`
RefundRefusalExplanation string `json:"refund_refusal_explanation"`
ServiceDate string `json:"service_date"`
ServiceDocumentation *File `json:"service_documentation"`
ShippingAddress string `json:"shipping_address"`
ShippingCarrier string `json:"shipping_carrier"`
ShippingDate string `json:"shipping_date"`
ShippingDocumentation *File `json:"shipping_documentation"`
ShippingTrackingNumber string `json:"shipping_tracking_number"`
UncategorizedFile *File `json:"uncategorized_file"`
UncategorizedText string `json:"uncategorized_text"`
}
// UnmarshalJSON handles deserialization of a Dispute.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (d *Dispute) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
d.ID = id
return nil
}
type dispute Dispute
var v dispute
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*d = Dispute(v)
return nil
}

50
vendor/github.com/stripe/stripe-go/ephemeralkey.go generated vendored Normal file
View file

@ -0,0 +1,50 @@
package stripe
import "encoding/json"
// EphemeralKeyParams is the set of parameters that can be used when creating
// an ephemeral key.
type EphemeralKeyParams struct {
Params `form:"*"`
Customer *string `form:"customer"`
IssuingCard *string `form:"issuing_card"`
StripeVersion *string `form:"-"` // This goes in the `Stripe-Version` header
}
// EphemeralKey is the resource representing a Stripe ephemeral key. This is used by Mobile SDKs
// to for example manage a Customer's payment methods.
type EphemeralKey struct {
AssociatedObjects []struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"associated_objects"`
Created int64 `json:"created"`
Expires int64 `json:"expires"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
// RawJSON is provided so that it may be passed back to the frontend
// unchanged. Ephemeral keys are issued on behalf of another client which
// may be running a different version of the bindings and thus expect a
// different JSON structure. This ensures that if the structure differs
// from the version of these bindings, we can still pass back a compatible
// key.
RawJSON []byte `json:"-"`
}
// UnmarshalJSON handles deserialization of an EphemeralKey.
// This custom unmarshaling is needed because we need to store the
// raw JSON on the object so it may be passed back to the frontend.
func (e *EphemeralKey) UnmarshalJSON(data []byte) error {
type ephemeralKey EphemeralKey
var ee ephemeralKey
err := json.Unmarshal(data, &ee)
if err == nil {
*e = EphemeralKey(ee)
}
e.RawJSON = data
return nil
}

297
vendor/github.com/stripe/stripe-go/error.go generated vendored Normal file
View file

@ -0,0 +1,297 @@
package stripe
import "encoding/json"
// ErrorType is the list of allowed values for the error's type.
type ErrorType string
// List of values that ErrorType can take.
const (
ErrorTypeAPI ErrorType = "api_error"
ErrorTypeAPIConnection ErrorType = "api_connection_error"
ErrorTypeAuthentication ErrorType = "authentication_error"
ErrorTypeCard ErrorType = "card_error"
ErrorTypeInvalidRequest ErrorType = "invalid_request_error"
ErrorTypePermission ErrorType = "more_permissions_required"
ErrorTypeRateLimit ErrorType = "rate_limit_error"
)
// ErrorCode is the list of allowed values for the error's code.
type ErrorCode string
// DeclineCode is the list of reasons provided by card issuers for decline of payment.
type DeclineCode string
// List of values that ErrorCode can take.
const (
ErrorCodeAccountAlreadyExists ErrorCode = "account_already_exists"
ErrorCodeAccountCountryInvalidAddress ErrorCode = "account_country_invalid_address"
ErrorCodeAccountInvalid ErrorCode = "account_invalid"
ErrorCodeAccountNumberInvalid ErrorCode = "account_number_invalid"
ErrorCodeAlipayUpgradeRequired ErrorCode = "alipay_upgrade_required"
ErrorCodeAmountTooLarge ErrorCode = "amount_too_large"
ErrorCodeAmountTooSmall ErrorCode = "amount_too_small"
ErrorCodeAPIKeyExpired ErrorCode = "api_key_expired"
ErrorCodeAuthenticationRequired ErrorCode = "authentication_required"
ErrorCodeBalanceInsufficient ErrorCode = "balance_insufficient"
ErrorCodeBankAccountExists ErrorCode = "bank_account_exists"
ErrorCodeBankAccountUnusable ErrorCode = "bank_account_unusable"
ErrorCodeBankAccountUnverified ErrorCode = "bank_account_unverified"
ErrorCodeBitcoinUpgradeRequired ErrorCode = "bitcoin_upgrade_required"
ErrorCodeCardDeclined ErrorCode = "card_declined"
ErrorCodeChargeAlreadyCaptured ErrorCode = "charge_already_captured"
ErrorCodeChargeAlreadyRefunded ErrorCode = "charge_already_refunded"
ErrorCodeChargeDisputed ErrorCode = "charge_disputed"
ErrorCodeChargeExceedsSourceLimit ErrorCode = "charge_exceeds_source_limit"
ErrorCodeChargeExpiredForCapture ErrorCode = "charge_expired_for_capture"
ErrorCodeCountryUnsupported ErrorCode = "country_unsupported"
ErrorCodeCouponExpired ErrorCode = "coupon_expired"
ErrorCodeCustomerMaxSubscriptions ErrorCode = "customer_max_subscriptions"
ErrorCodeEmailInvalid ErrorCode = "email_invalid"
ErrorCodeExpiredCard ErrorCode = "expired_card"
ErrorCodeIdempotencyKeyInUse ErrorCode = "idempotency_key_in_use"
ErrorCodeIncorrectAddress ErrorCode = "incorrect_address"
ErrorCodeIncorrectCVC ErrorCode = "incorrect_cvc"
ErrorCodeIncorrectNumber ErrorCode = "incorrect_number"
ErrorCodeIncorrectZip ErrorCode = "incorrect_zip"
ErrorCodeInstantPayoutsUnsupported ErrorCode = "instant_payouts_unsupported"
ErrorCodeInvalidCardType ErrorCode = "invalid_card_type"
ErrorCodeInvalidChargeAmount ErrorCode = "invalid_charge_amount"
ErrorCodeInvalidCVC ErrorCode = "invalid_cvc"
ErrorCodeInvalidExpiryMonth ErrorCode = "invalid_expiry_month"
ErrorCodeInvalidExpiryYear ErrorCode = "invalid_expiry_year"
ErrorCodeInvalidNumber ErrorCode = "invalid_number"
ErrorCodeInvalidSourceUsage ErrorCode = "invalid_source_usage"
ErrorCodeInvoiceNoCustomerLineItems ErrorCode = "invoice_no_customer_line_items"
ErrorCodeInvoiceNoSubscriptionLineItems ErrorCode = "invoice_no_subscription_line_items"
ErrorCodeInvoiceNotEditable ErrorCode = "invoice_not_editable"
ErrorCodeInvoiceUpcomingNone ErrorCode = "invoice_upcoming_none"
ErrorCodeLivemodeMismatch ErrorCode = "livemode_mismatch"
ErrorCodeLockTimeout ErrorCode = "lock_timeout"
ErrorCodeMissing ErrorCode = "missing"
ErrorCodeNotAllowedOnStandardAccount ErrorCode = "not_allowed_on_standard_account"
ErrorCodeOrderCreationFailed ErrorCode = "order_creation_failed"
ErrorCodeOrderRequiredSettings ErrorCode = "order_required_settings"
ErrorCodeOrderStatusInvalid ErrorCode = "order_status_invalid"
ErrorCodeOrderUpstreamTimeout ErrorCode = "order_upstream_timeout"
ErrorCodeOutOfInventory ErrorCode = "out_of_inventory"
ErrorCodeParameterInvalidEmpty ErrorCode = "parameter_invalid_empty"
ErrorCodeParameterInvalidInteger ErrorCode = "parameter_invalid_integer"
ErrorCodeParameterInvalidStringBlank ErrorCode = "parameter_invalid_string_blank"
ErrorCodeParameterInvalidStringEmpty ErrorCode = "parameter_invalid_string_empty"
ErrorCodeParameterMissing ErrorCode = "parameter_missing"
ErrorCodeParameterUnknown ErrorCode = "parameter_unknown"
ErrorCodeParametersExclusive ErrorCode = "parameters_exclusive"
ErrorCodePaymentIntentAuthenticationFailure ErrorCode = "payment_intent_authentication_failure"
ErrorCodePaymentIntentIncompatiblePaymentMethod ErrorCode = "payment_intent_incompatible_payment_method"
ErrorCodePaymentIntentInvalidParameter ErrorCode = "payment_intent_invalid_parameter"
ErrorCodePaymentIntentPaymentAttemptFailed ErrorCode = "payment_intent_payment_attempt_failed"
ErrorCodePaymentIntentUnexpectedState ErrorCode = "payment_intent_unexpected_state"
ErrorCodePaymentMethodUnactivated ErrorCode = "payment_method_unactivated"
ErrorCodePaymentMethodUnexpectedState ErrorCode = "payment_method_unexpected_state"
ErrorCodePayoutsNotAllowed ErrorCode = "payouts_not_allowed"
ErrorCodePlatformAPIKeyExpired ErrorCode = "platform_api_key_expired"
ErrorCodePostalCodeInvalid ErrorCode = "postal_code_invalid"
ErrorCodeProcessingError ErrorCode = "processing_error"
ErrorCodeProductInactive ErrorCode = "product_inactive"
ErrorCodeRateLimit ErrorCode = "rate_limit"
ErrorCodeResourceAlreadyExists ErrorCode = "resource_already_exists"
ErrorCodeResourceMissing ErrorCode = "resource_missing"
ErrorCodeRoutingNumberInvalid ErrorCode = "routing_number_invalid"
ErrorCodeSecretKeyRequired ErrorCode = "secret_key_required"
ErrorCodeSepaUnsupportedAccount ErrorCode = "sepa_unsupported_account"
ErrorCodeSetupAttemptFailed ErrorCode = "setup_attempt_failed"
ErrorCodeSetupIntentAuthenticationFailure ErrorCode = "setup_intent_authentication_failure"
ErrorCodeSetupIntentUnexpectedState ErrorCode = "setup_intent_unexpected_state"
ErrorCodeShippingCalculationFailed ErrorCode = "shipping_calculation_failed"
ErrorCodeSkuInactive ErrorCode = "sku_inactive"
ErrorCodeStateUnsupported ErrorCode = "state_unsupported"
ErrorCodeTaxIDInvalid ErrorCode = "tax_id_invalid"
ErrorCodeTaxesCalculationFailed ErrorCode = "taxes_calculation_failed"
ErrorCodeTestmodeChargesOnly ErrorCode = "testmode_charges_only"
ErrorCodeTLSVersionUnsupported ErrorCode = "tls_version_unsupported"
ErrorCodeTokenAlreadyUsed ErrorCode = "token_already_used"
ErrorCodeTokenInUse ErrorCode = "token_in_use"
ErrorCodeTransfersNotAllowed ErrorCode = "transfers_not_allowed"
ErrorCodeUpstreamOrderCreationFailed ErrorCode = "upstream_order_creation_failed"
ErrorCodeURLInvalid ErrorCode = "url_invalid"
// The following error code can be returned though is undocumented
ErrorCodeInvalidSwipeData ErrorCode = "invalid_swipe_data"
)
// List of DeclineCode values.
const (
DeclineCodeAuthenticationRequired DeclineCode = "authentication_required"
DeclineCodeApproveWithID DeclineCode = "approve_with_id"
DeclineCodeCallIssuer DeclineCode = "call_issuer"
DeclineCodeCardNotSupported DeclineCode = "card_not_supported"
DeclineCodeCardVelocityExceeded DeclineCode = "card_velocity_exceeded"
DeclineCodeCurrencyNotSupported DeclineCode = "currency_not_supported"
DeclineCodeDoNotHonor DeclineCode = "do_not_honor"
DeclineCodeDoNotTryAgain DeclineCode = "do_not_try_again"
DeclineCodeDuplicateTransaction DeclineCode = "duplicate_transaction"
DeclineCodeExpiredCard DeclineCode = "expired_card"
DeclineCodeFraudulent DeclineCode = "fraudulent"
DeclineCodeGenericDecline DeclineCode = "generic_decline"
DeclineCodeIncorrectNumber DeclineCode = "incorrect_number"
DeclineCodeIncorrectCVC DeclineCode = "incorrect_cvc"
DeclineCodeIncorrectPIN DeclineCode = "incorrect_pin"
DeclineCodeIncorrectZip DeclineCode = "incorrect_zip"
DeclineCodeInsufficientFunds DeclineCode = "insufficient_funds"
DeclineCodeInvalidAccount DeclineCode = "invalid_account"
DeclineCodeInvalidAmount DeclineCode = "invalid_amount"
DeclineCodeInvalidCVC DeclineCode = "invalid_cvc"
DeclineCodeInvalidExpiryYear DeclineCode = "invalid_expiry_year"
DeclineCodeInvalidNumber DeclineCode = "invalid_number"
DeclineCodeInvalidPIN DeclineCode = "invalid_pin"
DeclineCodeIssuerNotAvailable DeclineCode = "issuer_not_available"
DeclineCodeLostCard DeclineCode = "lost_card"
DeclineCodeMerchantBlacklist DeclineCode = "merchant_blacklist"
DeclineCodeNewAccountInformationAvailable DeclineCode = "new_account_information_available"
DeclineCodeNoActionTaken DeclineCode = "no_action_taken"
DeclineCodeNotPermitted DeclineCode = "not_permitted"
DeclineCodePickupCard DeclineCode = "pickup_card"
DeclineCodePINTryExceeded DeclineCode = "pin_try_exceeded"
DeclineCodeProcessingError DeclineCode = "processing_error"
DeclineCodeReenterTransaction DeclineCode = "reenter_transaction"
DeclineCodeRestrictedCard DeclineCode = "restricted_card"
DeclineCodeRevocationOfAllAuthorizations DeclineCode = "revocation_of_all_authorizations"
DeclineCodeRevocationOfAuthorization DeclineCode = "revocation_of_authorization"
DeclineCodeSecurityViolation DeclineCode = "security_violation"
DeclineCodeServiceNotAllowed DeclineCode = "service_not_allowed"
DeclineCodeStolenCard DeclineCode = "stolen_card"
DeclineCodeStopPaymentOrder DeclineCode = "stop_payment_order"
DeclineCodeTestModeDecline DeclineCode = "testmode_decline"
DeclineCodeTransactionNotAllowed DeclineCode = "transaction_not_allowed"
DeclineCodeTryAgainLater DeclineCode = "try_again_later"
DeclineCodeWithdrawalCountLimitExceeded DeclineCode = "withdrawal_count_limit_exceeded"
)
// Error is the response returned when a call is unsuccessful.
// For more details see https://stripe.com/docs/api#errors.
type Error struct {
ChargeID string `json:"charge,omitempty"`
Code ErrorCode `json:"code,omitempty"`
DeclineCode DeclineCode `json:"decline_code,omitempty"`
DocURL string `json:"doc_url,omitempty"`
// Err contains an internal error with an additional level of granularity
// that can be used in some cases to get more detailed information about
// what went wrong. For example, Err may hold a CardError that indicates
// exactly what went wrong during charging a card.
Err error `json:"-"`
HTTPStatusCode int `json:"status,omitempty"`
Msg string `json:"message"`
Param string `json:"param,omitempty"`
PaymentIntent *PaymentIntent `json:"payment_intent,omitempty"`
PaymentMethod *PaymentMethod `json:"payment_method,omitempty"`
RequestID string `json:"request_id,omitempty"`
SetupIntent *SetupIntent `json:"setup_intent,omitempty"`
Source *PaymentSource `json:"source,omitempty"`
Type ErrorType `json:"type"`
// OAuth specific Error properties. Named OAuthError because of name conflict.
OAuthError string `json:"error,omitempty"`
OAuthErrorDescription string `json:"error_description,omitempty"`
}
// Error serializes the error object to JSON and returns it as a string.
func (e *Error) Error() string {
ret, _ := json.Marshal(e)
return string(ret)
}
// APIConnectionError is a failure to connect to the Stripe API.
type APIConnectionError struct {
stripeErr *Error
}
// Error serializes the error object to JSON and returns it as a string.
func (e *APIConnectionError) Error() string {
return e.stripeErr.Error()
}
// APIError is a catch all for any errors not covered by other types (and
// should be extremely uncommon).
type APIError struct {
stripeErr *Error
}
// Error serializes the error object to JSON and returns it as a string.
func (e *APIError) Error() string {
return e.stripeErr.Error()
}
// AuthenticationError is a failure to properly authenticate during a request.
type AuthenticationError struct {
stripeErr *Error
}
// Error serializes the error object to JSON and returns it as a string.
func (e *AuthenticationError) Error() string {
return e.stripeErr.Error()
}
// PermissionError results when you attempt to make an API request
// for which your API key doesn't have the right permissions.
type PermissionError struct {
stripeErr *Error
}
// Error serializes the error object to JSON and returns it as a string.
func (e *PermissionError) Error() string {
return e.stripeErr.Error()
}
// CardError are the most common type of error you should expect to handle.
// They result when the user enters a card that can't be charged for some
// reason.
type CardError struct {
stripeErr *Error
// DeclineCode is a code indicating a card issuer's reason for declining a
// card (if they provided one).
DeclineCode DeclineCode `json:"decline_code,omitempty"`
}
// Error serializes the error object to JSON and returns it as a string.
func (e *CardError) Error() string {
return e.stripeErr.Error()
}
// InvalidRequestError is an error that occurs when a request contains invalid
// parameters.
type InvalidRequestError struct {
stripeErr *Error
}
// Error serializes the error object to JSON and returns it as a string.
func (e *InvalidRequestError) Error() string {
return e.stripeErr.Error()
}
// RateLimitError occurs when the Stripe API is hit to with too many requests
// too quickly and indicates that the current request has been rate limited.
type RateLimitError struct {
stripeErr *Error
}
// Error serializes the error object to JSON and returns it as a string.
func (e *RateLimitError) Error() string {
return e.stripeErr.Error()
}
// rawError deserializes the outer JSON object returned in an error response
// from the API.
type rawError struct {
E *rawErrorInternal `json:"error,omitempty"`
}
// rawErrorInternal embeds Error to deserialize all the standard error fields,
// but also adds other fields that may or may not be present depending on error
// type to help with deserialization. (e.g. DeclineCode).
type rawErrorInternal struct {
*Error
DeclineCode *DeclineCode `json:"decline_code,omitempty"`
}

125
vendor/github.com/stripe/stripe-go/event.go generated vendored Normal file
View file

@ -0,0 +1,125 @@
package stripe
import (
"encoding/json"
"fmt"
"strconv"
)
// Event is the resource representing a Stripe event.
// For more details see https://stripe.com/docs/api#events.
type Event struct {
Account string `json:"account"`
Created int64 `json:"created"`
Data *EventData `json:"data"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
PendingWebhooks int64 `json:"pending_webhooks"`
Request *EventRequest `json:"request"`
Type string `json:"type"`
}
// EventRequest contains information on a request that created an event.
type EventRequest struct {
// ID is the request ID of the request that created an event, if the event
// was created by a request.
ID string `json:"id"`
// IdempotencyKey is the idempotency key of the request that created an
// event, if the event was created by a request and if an idempotency key
// was specified for that request.
IdempotencyKey string `json:"idempotency_key"`
}
// EventData is the unmarshalled object as a map.
type EventData struct {
// Object is a raw mapping of the API resource contained in the event.
// Although marked with json:"-", it's still populated independently by
// a custom UnmarshalJSON implementation.
Object map[string]interface{} `json:"-"`
PreviousAttributes map[string]interface{} `json:"previous_attributes"`
Raw json.RawMessage `json:"object"`
}
// EventParams is the set of parameters that can be used when retrieving events.
// For more details see https://stripe.com/docs/api#retrieve_events.
type EventParams struct {
Params `form:"*"`
}
// EventList is a list of events as retrieved from a list endpoint.
type EventList struct {
ListMeta
Data []*Event `json:"data"`
}
// EventListParams is the set of parameters that can be used when listing events.
// For more details see https://stripe.com/docs/api#list_events.
type EventListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
DeliverySuccess *bool `form:"delivery_success"`
Type *string `form:"type"`
Types []*string `form:"types"`
}
// GetObjectValue returns the value from the e.Data.Object bag based on the keys hierarchy.
func (e *Event) GetObjectValue(keys ...string) string {
return getValue(e.Data.Object, keys)
}
// GetPreviousValue returns the value from the e.Data.Prev bag based on the keys hierarchy.
func (e *Event) GetPreviousValue(keys ...string) string {
return getValue(e.Data.PreviousAttributes, keys)
}
// UnmarshalJSON handles deserialization of the EventData.
// This custom unmarshaling exists so that we can keep both the map and raw data.
func (e *EventData) UnmarshalJSON(data []byte) error {
type eventdata EventData
var ee eventdata
err := json.Unmarshal(data, &ee)
if err != nil {
return err
}
*e = EventData(ee)
return json.Unmarshal(e.Raw, &e.Object)
}
// getValue returns the value from the m map based on the keys.
func getValue(m map[string]interface{}, keys []string) string {
node := m[keys[0]]
for i := 1; i < len(keys); i++ {
key := keys[i]
sliceNode, ok := node.([]interface{})
if ok {
intKey, err := strconv.Atoi(key)
if err != nil {
panic(fmt.Sprintf(
"Cannot access nested slice element with non-integer key: %s",
key))
}
node = sliceNode[intKey]
continue
}
mapNode, ok := node.(map[string]interface{})
if ok {
node = mapNode[key]
continue
}
panic(fmt.Sprintf(
"Cannot descend into non-map non-slice object with key: %s", key))
}
if node == nil {
return ""
}
return fmt.Sprintf("%v", node)
}

25
vendor/github.com/stripe/stripe-go/exchangerate.go generated vendored Normal file
View file

@ -0,0 +1,25 @@
package stripe
// ExchangeRate is the resource representing the currency exchange rates at
// a given time.
type ExchangeRate struct {
ID string `json:"id"`
Rates map[Currency]float64 `json:"rates"`
}
// ExchangeRateParams is the set of parameters that can be used when retrieving
// exchange rates.
type ExchangeRateParams struct {
Params `form:"*"`
}
// ExchangeRateList is a list of exchange rates as retrieved from a list endpoint.
type ExchangeRateList struct {
ListMeta
Data []*ExchangeRate `json:"data"`
}
// ExchangeRateListParams are the parameters allowed during ExchangeRate listing.
type ExchangeRateListParams struct {
ListParams `form:"*"`
}

61
vendor/github.com/stripe/stripe-go/fee.go generated vendored Normal file
View file

@ -0,0 +1,61 @@
package stripe
import "encoding/json"
// ApplicationFeeParams is the set of parameters that can be used when refunding an application fee.
// For more details see https://stripe.com/docs/api#refund_application_fee.
type ApplicationFeeParams struct {
Params `form:"*"`
}
// ApplicationFeeListParams is the set of parameters that can be used when listing application fees.
// For more details see https://stripe.com/docs/api#list_application_fees.
type ApplicationFeeListParams struct {
ListParams `form:"*"`
Charge *string `form:"charge"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
}
// ApplicationFee is the resource representing a Stripe application fee.
// For more details see https://stripe.com/docs/api#application_fees.
type ApplicationFee struct {
Account *Account `json:"account"`
Amount int64 `json:"amount"`
AmountRefunded int64 `json:"amount_refunded"`
Application string `json:"application"`
BalanceTransaction *BalanceTransaction `json:"balance_transaction"`
Charge *Charge `json:"charge"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
OriginatingTransaction *Charge `json:"originating_transaction"`
Refunded bool `json:"refunded"`
Refunds *FeeRefundList `json:"refunds"`
}
//ApplicationFeeList is a list of application fees as retrieved from a list endpoint.
type ApplicationFeeList struct {
ListMeta
Data []*ApplicationFee `json:"data"`
}
// UnmarshalJSON handles deserialization of an ApplicationFee.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (f *ApplicationFee) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
f.ID = id
return nil
}
type applicationFee ApplicationFee
var v applicationFee
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*f = ApplicationFee(v)
return nil
}

57
vendor/github.com/stripe/stripe-go/feerefund.go generated vendored Normal file
View file

@ -0,0 +1,57 @@
package stripe
import (
"encoding/json"
)
// FeeRefundParams is the set of parameters that can be used when refunding an application fee.
// For more details see https://stripe.com/docs/api#fee_refund.
type FeeRefundParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
ApplicationFee *string `form:"-"` // Included in the URL
}
// FeeRefundListParams is the set of parameters that can be used when listing application fee refunds.
// For more details see https://stripe.com/docs/api#list_fee_refunds.
type FeeRefundListParams struct {
ListParams `form:"*"`
ApplicationFee *string `form:"-"` // Included in the URL
}
// FeeRefund is the resource representing a Stripe application fee refund.
// For more details see https://stripe.com/docs/api#fee_refunds.
type FeeRefund struct {
Amount int64 `json:"amount"`
BalanceTransaction *BalanceTransaction `json:"balance_transaction"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Fee *ApplicationFee `json:"fee"`
ID string `json:"id"`
Metadata map[string]string `json:"metadata"`
}
// FeeRefundList is a list object for application fee refunds.
type FeeRefundList struct {
ListMeta
Data []*FeeRefund `json:"data"`
}
// UnmarshalJSON handles deserialization of a FeeRefund.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (r *FeeRefund) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
r.ID = id
return nil
}
type feeRefund FeeRefund
var v feeRefund
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*r = FeeRefund(v)
return nil
}

150
vendor/github.com/stripe/stripe-go/file.go generated vendored Normal file
View file

@ -0,0 +1,150 @@
package stripe
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/url"
"path/filepath"
"github.com/stripe/stripe-go/form"
)
// FilePurpose is the purpose of a particular file.
type FilePurpose string
// List of values that FilePurpose can take.
const (
FilePurposeAdditionalVerification FilePurpose = "additional_verification"
FilePurposeBusinessIcon FilePurpose = "business_icon"
FilePurposeBusinessLogo FilePurpose = "business_logo"
FilePurposeCustomerSignature FilePurpose = "customer_signature"
FilePurposeDisputeEvidence FilePurpose = "dispute_evidence"
FilePurposeFinanceReportRun FilePurpose = "finance_report_run"
FilePurposeFoundersStockDocument FilePurpose = "founders_stock_document"
FilePurposeIdentityDocument FilePurpose = "identity_document"
FilePurposePCIDocument FilePurpose = "pci_document"
FilePurposeSigmaScheduledQuery FilePurpose = "sigma_scheduled_query"
FilePurposeTaxDocumentUserUpload FilePurpose = "tax_document_user_upload"
)
// FileParams is the set of parameters that can be used when creating a file.
// For more details see https://stripe.com/docs/api#create_file.
type FileParams struct {
Params `form:"*"`
// FileReader is a reader with the contents of the file that should be uploaded.
FileReader io.Reader
// Filename is just the name of the file without path information.
Filename *string
Purpose *string
FileLinkData *FileFileLinkDataParams
}
// FileFileLinkDataParams is the set of parameters allowed for the
// file_link_data hash.
type FileFileLinkDataParams struct {
Params `form:"*"`
Create *bool `form:"create"`
ExpiresAt *int64 `form:"expires_at"`
}
// FileListParams is the set of parameters that can be used when listing
// files. For more details see https://stripe.com/docs/api#list_files.
type FileListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Purpose *string `form:"purpose"`
}
// File is the resource representing a Stripe file.
// For more details see https://stripe.com/docs/api#file_object.
type File struct {
Created int64 `json:"created"`
ID string `json:"id"`
Filename string `json:"filename"`
Links *FileLinkList `json:"links"`
Purpose FilePurpose `json:"purpose"`
Size int64 `json:"size"`
Type string `json:"type"`
URL string `json:"url"`
}
// FileList is a list of files as retrieved from a list endpoint.
type FileList struct {
ListMeta
Data []*File `json:"data"`
}
// GetBody gets an appropriate multipart form payload to use in a request body
// to create a new file.
func (f *FileParams) GetBody() (*bytes.Buffer, string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if f.Purpose != nil {
err := writer.WriteField("purpose", StringValue(f.Purpose))
if err != nil {
return nil, "", err
}
}
if f.FileReader != nil && f.Filename != nil {
part, err := writer.CreateFormFile("file", filepath.Base(StringValue(f.Filename)))
if err != nil {
return nil, "", err
}
_, err = io.Copy(part, f.FileReader)
if err != nil {
return nil, "", err
}
}
if f.FileLinkData != nil {
values := &form.Values{}
form.AppendToPrefixed(values, f.FileLinkData, []string{"file_link_data"})
params, err := url.ParseQuery(values.Encode())
if err != nil {
return nil, "", err
}
for key, values := range params {
err := writer.WriteField(key, values[0])
if err != nil {
return nil, "", err
}
}
}
err := writer.Close()
if err != nil {
return nil, "", err
}
return body, writer.Boundary(), nil
}
// UnmarshalJSON handles deserialization of a File.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (f *File) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
f.ID = id
return nil
}
type file File
var v file
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*f = File(v)
return nil
}

60
vendor/github.com/stripe/stripe-go/filelink.go generated vendored Normal file
View file

@ -0,0 +1,60 @@
package stripe
import (
"encoding/json"
)
// FileLinkParams is the set of parameters that can be used when creating or updating a file link.
type FileLinkParams struct {
Params `form:"*"`
ExpiresAt *int64 `form:"expires_at"`
File *string `form:"file"`
}
// FileLinkListParams is the set of parameters that can be used when listing file links.
type FileLinkListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Expired *bool `form:"expired"`
File *string `form:"file"`
}
// FileLink is the resource representing a Stripe file link.
// For more details see https://stripe.com/docs/api#file_links.
type FileLink struct {
Created int64 `json:"created"`
Expired bool `json:"expired"`
ExpiresAt int64 `json:"expires_at"`
File *File `json:"file"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
URL string `json:"url"`
}
// UnmarshalJSON handles deserialization of a file link.
// This custom unmarshaling is needed because the resulting
// property may be an ID or the full struct if it was expanded.
func (c *FileLink) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type fileLink FileLink
var v fileLink
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = FileLink(v)
return nil
}
// FileLinkList is a list of file links as retrieved from a list endpoint.
type FileLinkList struct {
ListMeta
Data []*FileLink `json:"data"`
}

623
vendor/github.com/stripe/stripe-go/form/form.go generated vendored Normal file
View file

@ -0,0 +1,623 @@
package form
import (
"bytes"
"fmt"
"net/url"
"reflect"
"strconv"
"strings"
"sync"
)
const tagName = "form"
// Appender is the interface implemented by types that can append themselves to
// a collection of form values.
//
// This is usually something that shouldn't be used, but is needed in a few
// places where authors deviated from norms while implementing various
// parameters.
type Appender interface {
// AppendTo is invoked by the form package on any types found to implement
// Appender so that they have a chance to encode themselves. Note that
// AppendTo is called in addition to normal encoding, so other form tags on
// the struct are still fair game.
AppendTo(values *Values, keyParts []string)
}
// encoderFunc is used to encode any type from a request.
//
// A note about encodeZero: Since some types in the Stripe API are defaulted to
// non-zero values, and Go defaults types to their zero values, any type that
// has a Stripe API default of a non-zero value is defined as a Go pointer,
// meaning nil defaults to the Stripe API non-zero value. To override this, a
// check is made to see if the value is the zero-value for that type. If it is
// and encodeZero is true, it's encoded. This is ignored as a parameter when
// dealing with types like structs, where the decision cannot be made
// preemptively.
type encoderFunc func(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions)
// field represents a single field found in a struct. It caches information
// about that field so that we can make encoding faster.
type field struct {
formName string
index int
isAppender bool
isPtr bool
options *formOptions
}
type formOptions struct {
// Empty indicates that a field's value should be emptied in that its value
// should be an empty string. It's used to workaround the fact that an
// empty string is a string's zero value and wouldn't normally be encoded.
Empty bool
// HighPrecision indicates that this field should be treated as a high
// precision decimal, a decimal whose precision is important to the API and
// which we want to encode as accurately as possible.
//
// All parameters are encoded using form encoding, so this of course
// encodes a value to a string, but notably, these high precision fields
// are sent back as strings in JSON, even though they might be surfaced as
// floats in this library.
//
// This isn't a perfect abstraction because floats are not precise in
// nature, and we might be better-advised to use a real high-precision data
// type like `big.Float`. That said, we suspect that this will be an
// adequate solution in the vast majority of cases and has a usability
// benefit, so we've gone this route.
HighPrecision bool
}
type structEncoder struct {
fields []*field
fieldEncs []encoderFunc
}
func (se *structEncoder) encode(values *Values, v reflect.Value, keyParts []string, _ bool, _ *formOptions) {
for i, f := range se.fields {
var fieldKeyParts []string
fieldV := v.Field(f.index)
// The wildcard on a form tag is a "special" value: it indicates a
// struct field that we should recurse into, but for which no part
// should be added to the key parts, meaning that its own subfields
// will be named at the same level as with the fields of the
// current structure.
if f.formName == "*" {
fieldKeyParts = keyParts
} else {
fieldKeyParts = append(keyParts, f.formName)
}
se.fieldEncs[i](values, fieldV, fieldKeyParts, f.isPtr, f.options)
if f.isAppender && (!f.isPtr || !fieldV.IsNil()) {
fieldV.Interface().(Appender).AppendTo(values, fieldKeyParts)
}
}
}
// ---
// Strict enables strict mode wherein the package will panic on an AppendTo
// function if it finds that a tag string was malformed.
var Strict = false
var encoderCache struct {
m map[reflect.Type]encoderFunc
mu sync.RWMutex // for coordinating concurrent operations on m
}
var structCache struct {
m map[reflect.Type]*structEncoder
mu sync.RWMutex // for coordinating concurrent operations on m
}
// AppendTo uses reflection to form encode into the given values collection
// based off the form tags that it defines.
func AppendTo(values *Values, i interface{}) {
reflectValue(values, reflect.ValueOf(i), false, nil)
}
// AppendToPrefixed is the same as AppendTo, but it allows a slice of key parts
// to be specified to prefix the form values.
//
// I was hoping not to have to expose this function, but I ended up needing it
// for recipients. Recipients is going away, and when it does, we can probably
// remove it again.
func AppendToPrefixed(values *Values, i interface{}, keyParts []string) {
reflectValue(values, reflect.ValueOf(i), false, keyParts)
}
// FormatKey takes a series of key parts that may be parameter keyParts, map keys,
// or array indices and unifies them into a single key suitable for Stripe's
// style of form encoding.
func FormatKey(parts []string) string {
if len(parts) < 1 {
panic("Not allowed 0-length parts slice")
}
key := parts[0]
for i := 1; i < len(parts); i++ {
key += "[" + parts[i] + "]"
}
return key
}
// ---
func boolEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) {
val := v.Bool()
if !val && !encodeZero {
return
}
if options != nil {
switch {
case options.Empty:
values.Add(FormatKey(keyParts), "")
}
} else {
values.Add(FormatKey(keyParts), strconv.FormatBool(val))
}
}
func buildArrayOrSliceEncoder(t reflect.Type) encoderFunc {
// Gets an encoder for the type that the array or slice will hold
elemF := getCachedOrBuildTypeEncoder(t.Elem())
return func(values *Values, v reflect.Value, keyParts []string, _ bool, options *formOptions) {
// When encountering a slice that's been explicitly set (i.e. non-nil)
// and which is of 0 length, we take this as an indication that the
// user is trying to zero the API array. See the `additional_owners`
// property under `legal_entity` on account for an example of somewhere
// that this is useful.
//
// This only works for a slice (and not an array) because even a zeroed
// array always has a fixed length.
if t.Kind() == reflect.Slice && !v.IsNil() && v.Len() == 0 {
values.Add(FormatKey(keyParts), "")
return
}
var arrNames []string
for i := 0; i < v.Len(); i++ {
arrNames = append(keyParts, strconv.Itoa(i))
indexV := v.Index(i)
elemF(values, indexV, arrNames, indexV.Kind() == reflect.Ptr, nil)
if isAppender(indexV.Type()) && !indexV.IsNil() {
indexV.Interface().(Appender).AppendTo(values, arrNames)
}
}
}
}
func buildPtrEncoder(t reflect.Type) encoderFunc {
// Gets an encoder for the type that the pointer wraps
elemF := getCachedOrBuildTypeEncoder(t.Elem())
return func(values *Values, v reflect.Value, keyParts []string, _ bool, options *formOptions) {
// We take a nil to mean that the property wasn't set, so ignore it in
// the final encoding.
if v.IsNil() {
return
}
// Handle "zeroing" an array stored as a pointer to a slice. See
// comment in `buildArrayOrSliceEncoder` above.
if t.Elem().Kind() == reflect.Slice && v.Elem().Len() == 0 {
values.Add(FormatKey(keyParts), "")
return
}
// Otherwise, call into the appropriate encoder for the pointer's type.
elemF(values, v.Elem(), keyParts, true, options)
}
}
func buildStructEncoder(t reflect.Type) encoderFunc {
se := getCachedOrBuildStructEncoder(t)
return se.encode
}
func float32Encoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) {
val := v.Float()
if val == 0.0 && !encodeZero {
return
}
prec := 4
if options != nil && options.HighPrecision {
// Special value that tells Go to format the float in as few required
// digits as necessary for it to be successfully parsable from a string
// back to the same original number.
prec = -1
}
values.Add(FormatKey(keyParts), strconv.FormatFloat(val, 'f', prec, 32))
}
func float64Encoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) {
val := v.Float()
if val == 0.0 && !encodeZero {
return
}
prec := 4
if options != nil && options.HighPrecision {
// Special value that tells Go to format the float in as few required
// digits as necessary for it to be successfully parsable from a string
// back to the same original number.
prec = -1
}
values.Add(FormatKey(keyParts), strconv.FormatFloat(val, 'f', prec, 64))
}
func getCachedOrBuildStructEncoder(t reflect.Type) *structEncoder {
// Just acquire a read lock when extracting a value (note that in Go, a map
// cannot be read while it's also being written).
structCache.mu.RLock()
f := structCache.m[t]
structCache.mu.RUnlock()
if f != nil {
return f
}
// We do the work to get the encoder without holding a lock. This could
// result in duplicate work, but it will help us avoid a deadlock. Encoders
// may be built and stored recursively in the cases of something like an
// array or slice, so we need to make sure that this function is properly
// re-entrant.
f = makeStructEncoder(t)
structCache.mu.Lock()
defer structCache.mu.Unlock()
if structCache.m == nil {
structCache.m = make(map[reflect.Type]*structEncoder)
}
structCache.m[t] = f
return f
}
// getCachedOrBuildTypeEncoder tries to get an encoderFunc for the type from
// the cache, and falls back to building one if there wasn't a cached one
// available. If an encoder is built, it's stored back to the cache.
func getCachedOrBuildTypeEncoder(t reflect.Type) encoderFunc {
// Just acquire a read lock when extracting a value (note that in Go, a map
// cannot be read while it's also being written).
encoderCache.mu.RLock()
f := encoderCache.m[t]
encoderCache.mu.RUnlock()
if f != nil {
return f
}
// We do the work to get the encoder without holding a lock. This could
// result in duplicate work, but it will help us avoid a deadlock. Encoders
// may be built and stored recursively in the cases of something like an
// array or slice, so we need to make sure that this function is properly
// re-entrant.
f = makeTypeEncoder(t)
encoderCache.mu.Lock()
defer encoderCache.mu.Unlock()
if encoderCache.m == nil {
encoderCache.m = make(map[reflect.Type]encoderFunc)
}
encoderCache.m[t] = f
return f
}
func intEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) {
val := v.Int()
if val == 0 && !encodeZero {
return
}
values.Add(FormatKey(keyParts), strconv.FormatInt(val, 10))
}
func interfaceEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, _ *formOptions) {
// interfaceEncoder never encodes a `nil`, but it will pass through an
// `encodeZero` value into its chained encoder
if v.IsNil() {
return
}
reflectValue(values, v.Elem(), encodeZero, keyParts)
}
func isAppender(t reflect.Type) bool {
return t.Implements(reflect.TypeOf((*Appender)(nil)).Elem())
}
func mapEncoder(values *Values, v reflect.Value, keyParts []string, _ bool, _ *formOptions) {
for _, keyVal := range v.MapKeys() {
if Strict && keyVal.Kind() != reflect.String {
panic("Don't support serializing maps with non-string keys")
}
// Unlike a property on a struct which will contain a zero value even
// if never set, any value found in a map has been explicitly set, so
// we always make an effort to encode them, even if a zero value
// (that's why we pass through `true` here).
reflectValue(values, v.MapIndex(keyVal), true, append(keyParts, keyVal.String()))
}
}
func stringEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) {
val := v.String()
if val == "" && !encodeZero {
return
}
values.Add(FormatKey(keyParts), val)
}
func uintEncoder(values *Values, v reflect.Value, keyParts []string, encodeZero bool, options *formOptions) {
val := v.Uint()
if val == 0 && !encodeZero {
return
}
values.Add(FormatKey(keyParts), strconv.FormatUint(val, 10))
}
// reflectValue is roughly the shared entry point of any AppendTo functions.
// It's also called recursively in cases where a precise type isn't yet known
// and its encoding needs to be deferred down the chain; for example, when
// encoding interface{} or the values in an array or map containing
// interface{}.
func reflectValue(values *Values, v reflect.Value, encodeZero bool, keyParts []string) {
t := v.Type()
f := getCachedOrBuildTypeEncoder(t)
if f != nil {
f(values, v, keyParts, encodeZero || v.Kind() == reflect.Ptr, nil)
}
if isAppender(t) {
v.Interface().(Appender).AppendTo(values, keyParts)
}
}
func makeStructEncoder(t reflect.Type) *structEncoder {
// Don't specify capacity because we don't know how many fields are tagged with
// `form`
se := &structEncoder{}
for i := 0; i < t.NumField(); i++ {
reflectField := t.Field(i)
tag := reflectField.Tag.Get(tagName)
if Strict && tag == "" {
panic(fmt.Sprintf(
"All fields in structs to be form-encoded must have `form` tag; on: %s/%s "+
"(hint: use an explicit `form:\"-\"` if the field should not be encoded",
t.Name(), reflectField.Name,
))
}
formName, options := parseTag(tag)
// Like with encoding/json, a hyphen is an explicit way of saying
// that this field should not be encoded
if formName == "-" {
continue
}
fldTyp := reflectField.Type
fldKind := fldTyp.Kind()
if Strict && options != nil {
if options.Empty && fldKind != reflect.Bool {
panic(fmt.Sprintf(
"Cannot specify `empty` for non-boolean field; on: %s/%s",
t.Name(), reflectField.Name,
))
}
var k reflect.Kind
if fldKind == reflect.Ptr {
k = fldTyp.Elem().Kind()
} else {
k = fldKind
}
fldIsFloat := k == reflect.Float32 || k == reflect.Float64
if options.HighPrecision && !fldIsFloat {
panic(fmt.Sprintf(
"Cannot specify `high_precision` for non-float field; on: %s/%s (%s)",
t.Name(), reflectField.Name, fldTyp,
))
}
}
se.fields = append(se.fields, &field{
formName: formName,
index: i,
isAppender: isAppender(fldTyp),
isPtr: fldKind == reflect.Ptr,
options: options,
})
se.fieldEncs = append(se.fieldEncs,
getCachedOrBuildTypeEncoder(fldTyp))
}
return se
}
func makeTypeEncoder(t reflect.Type) encoderFunc {
switch t.Kind() {
case reflect.Array, reflect.Slice:
return buildArrayOrSliceEncoder(t)
case reflect.Bool:
return boolEncoder
case reflect.Float32:
return float32Encoder
case reflect.Float64:
return float64Encoder
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return intEncoder
case reflect.Interface:
return interfaceEncoder
case reflect.Map:
return mapEncoder
case reflect.Ptr:
return buildPtrEncoder(t)
case reflect.String:
return stringEncoder
case reflect.Struct:
return buildStructEncoder(t)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return uintEncoder
}
return nil
}
func parseTag(tag string) (string, *formOptions) {
var options *formOptions
parts := strings.Split(tag, ",")
name := parts[0]
for i := 1; i < len(parts); i++ {
switch parts[i] {
case "empty":
if options == nil {
options = &formOptions{}
}
options.Empty = true
case "high_precision":
if options == nil {
options = &formOptions{}
}
options.HighPrecision = true
default:
if Strict {
part := parts[i]
if part == "" {
part = "(empty)"
}
panic(fmt.Sprintf("Don't know how to handle form tag part: %s (tag: %s)",
part, tag))
}
}
}
return name, options
}
// ---
// Values is a collection of values that can be submitted along with a
// request that specifically allows for duplicate keys and encodes its entries
// in the same order that they were added.
type Values struct {
values []formValue
}
// Add adds a key/value tuple to the form.
func (f *Values) Add(key, val string) {
f.values = append(f.values, formValue{key, val})
}
// Encode encodes the keys and values into “URL encoded” form
// ("bar=baz&foo=quux").
func (f *Values) Encode() string {
var buf bytes.Buffer
for _, v := range f.values {
if buf.Len() > 0 {
buf.WriteByte('&')
}
key := url.QueryEscape(v.Key)
key = strings.Replace(key, "%5B", "[", -1)
key = strings.Replace(key, "%5D", "]", -1)
buf.WriteString(key)
buf.WriteString("=")
buf.WriteString(url.QueryEscape(v.Value))
}
return buf.String()
}
// Empty returns true if no parameters have been set.
func (f *Values) Empty() bool {
return len(f.values) == 0
}
// Set sets the first instance of a parameter for the given key to the given
// value. If no parameters exist with the key, a new one is added.
//
// Note that Set is O(n) and may be quite slow for a very large parameter list.
func (f *Values) Set(key, val string) {
for i, v := range f.values {
if v.Key == key {
f.values[i].Value = val
return
}
}
f.Add(key, val)
}
// Get retrieves the list of values for the given key. If no values exist
// for the key, nil will be returned.
//
// Note that Get is O(n) and may be quite slow for a very large parameter list.
func (f *Values) Get(key string) []string {
var results []string
for i, v := range f.values {
if v.Key == key {
results = append(results, f.values[i].Value)
}
}
return results
}
// ToValues converts an instance of Values into an instance of
// url.Values. This can be useful in cases where it's useful to make an
// unordered comparison of two sets of request values.
//
// Note that url.Values is incapable of representing certain Rack form types in
// a cohesive way. For example, an array of maps in Rack is encoded with a
// string like:
//
// arr[][foo]=foo0&arr[][bar]=bar0&arr[][foo]=foo1&arr[][bar]=bar1
//
// Because url.Values is a map, values will be handled in a way that's grouped
// by their key instead of in the order they were added. Therefore the above
// may by encoded to something like (maps are unordered so the actual result is
// somewhat non-deterministic):
//
// arr[][foo]=foo0&arr[][foo]=foo1&arr[][bar]=bar0&arr[][bar]=bar1
//
// And thus result in an incorrect request to Stripe.
func (f *Values) ToValues() url.Values {
values := url.Values{}
for _, v := range f.values {
values.Add(v.Key, v.Value)
}
return values
}
// A key/value tuple for use in the Values type.
type formValue struct {
Key string
Value string
}

379
vendor/github.com/stripe/stripe-go/invoice.go generated vendored Normal file
View file

@ -0,0 +1,379 @@
package stripe
import (
"encoding/json"
"github.com/stripe/stripe-go/form"
)
// InvoiceLineType is the list of allowed values for the invoice line's type.
type InvoiceLineType string
// List of values that InvoiceLineType can take.
const (
InvoiceLineTypeInvoiceItem InvoiceLineType = "invoiceitem"
InvoiceLineTypeSubscription InvoiceLineType = "subscription"
)
// InvoiceBillingReason is the reason why a given invoice was created
type InvoiceBillingReason string
// List of values that InvoiceBillingReason can take.
const (
InvoiceBillingReasonManual InvoiceBillingReason = "manual"
InvoiceBillingReasonSubscription InvoiceBillingReason = "subscription"
InvoiceBillingReasonSubscriptionCreate InvoiceBillingReason = "subscription_create"
InvoiceBillingReasonSubscriptionCycle InvoiceBillingReason = "subscription_cycle"
InvoiceBillingReasonSubscriptionThreshold InvoiceBillingReason = "subscription_threshold"
InvoiceBillingReasonSubscriptionUpdate InvoiceBillingReason = "subscription_update"
InvoiceBillingReasonUpcoming InvoiceBillingReason = "upcoming"
)
// InvoiceStatus is the reason why a given invoice was created
type InvoiceStatus string
// List of values that InvoiceStatus can take.
const (
InvoiceStatusDraft InvoiceStatus = "draft"
InvoiceStatusOpen InvoiceStatus = "open"
InvoiceStatusPaid InvoiceStatus = "paid"
InvoiceStatusUncollectible InvoiceStatus = "uncollectible"
InvoiceStatusVoid InvoiceStatus = "void"
)
// InvoiceCollectionMethod is the type of collection method for this invoice.
type InvoiceCollectionMethod string
// List of values that InvoiceCollectionMethod can take.
const (
InvoiceCollectionMethodChargeAutomatically InvoiceCollectionMethod = "charge_automatically"
InvoiceCollectionMethodSendInvoice InvoiceCollectionMethod = "send_invoice"
)
// InvoiceUpcomingInvoiceItemPeriodParams represents the period associated with that invoice item
type InvoiceUpcomingInvoiceItemPeriodParams struct {
End *int64 `form:"end"`
Start *int64 `form:"start"`
}
// InvoiceUpcomingInvoiceItemParams is the set of parameters that can be used when adding or modifying
// invoice items on an upcoming invoice.
// For more details see https://stripe.com/docs/api#upcoming_invoice-invoice_items.
type InvoiceUpcomingInvoiceItemParams struct {
Amount *int64 `form:"amount"`
Currency *string `form:"currency"`
Description *string `form:"description"`
Discountable *bool `form:"discountable"`
InvoiceItem *string `form:"invoiceitem"`
Period *InvoiceUpcomingInvoiceItemPeriodParams `form:"period"`
Quantity *int64 `form:"quantity"`
Schedule *string `form:"schedule"`
TaxRates []*string `form:"tax_rates"`
UnitAmount *int64 `form:"unit_amount"`
UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"`
}
// InvoiceCustomFieldParams represents the parameters associated with one custom field on an invoice.
type InvoiceCustomFieldParams struct {
Name *string `form:"name"`
Value *string `form:"value"`
}
// InvoiceTransferDataParams is the set of parameters allowed for the transfer_data hash.
type InvoiceTransferDataParams struct {
Destination *string `form:"destination"`
}
// InvoiceParams is the set of parameters that can be used when creating or updating an invoice.
// For more details see https://stripe.com/docs/api#create_invoice, https://stripe.com/docs/api#update_invoice.
type InvoiceParams struct {
Params `form:"*"`
AutoAdvance *bool `form:"auto_advance"`
ApplicationFeeAmount *int64 `form:"application_fee_amount"`
CollectionMethod *string `form:"collection_method"`
CustomFields []*InvoiceCustomFieldParams `form:"custom_fields"`
Customer *string `form:"customer"`
DaysUntilDue *int64 `form:"days_until_due"`
DefaultPaymentMethod *string `form:"default_payment_method"`
DefaultSource *string `form:"default_source"`
DefaultTaxRates []*string `form:"default_tax_rates"`
Description *string `form:"description"`
DueDate *int64 `form:"due_date"`
Footer *string `form:"footer"`
Paid *bool `form:"paid"`
StatementDescriptor *string `form:"statement_descriptor"`
Subscription *string `form:"subscription"`
TransferData *InvoiceTransferDataParams `form:"transfer_data"`
// These are all for exclusive use by GetNext.
Coupon *string `form:"coupon"`
InvoiceItems []*InvoiceUpcomingInvoiceItemParams `form:"invoice_items"`
SubscriptionBillingCycleAnchor *int64 `form:"subscription_billing_cycle_anchor"`
SubscriptionBillingCycleAnchorNow *bool `form:"-"` // See custom AppendTo
SubscriptionBillingCycleAnchorUnchanged *bool `form:"-"` // See custom AppendTo
SubscriptionCancelAt *int64 `form:"subscription_cancel_at"`
SubscriptionCancelAtPeriodEnd *bool `form:"subscription_cancel_at_period_end"`
SubscriptionCancelNow *bool `form:"subscription_cancel_now"`
SubscriptionDefaultTaxRates []*string `form:"subscription_default_tax_rates"`
SubscriptionItems []*SubscriptionItemsParams `form:"subscription_items"`
SubscriptionPlan *string `form:"subscription_plan"`
SubscriptionProrate *bool `form:"subscription_prorate"`
SubscriptionProrationBehavior *string `form:"subscription_proration_behavior"`
SubscriptionProrationDate *int64 `form:"subscription_proration_date"`
SubscriptionQuantity *int64 `form:"subscription_quantity"`
SubscriptionTrialEnd *int64 `form:"subscription_trial_end"`
SubscriptionTrialFromPlan *bool `form:"subscription_trial_from_plan"`
// This parameter is deprecated and we recommend that you use DefaultTaxRates instead.
TaxPercent *float64 `form:"tax_percent"`
// This parameter is deprecated and we recommend that you use SubscriptionDefaultTaxRates instead.
SubscriptionTaxPercent *float64 `form:"subscription_tax_percent"`
}
// AppendTo implements custom encoding logic for InvoiceParams so that the special
// "now" value for subscription_billing_cycle_anchor can be implemented
// (they're otherwise timestamps rather than strings).
func (p *InvoiceParams) AppendTo(body *form.Values, keyParts []string) {
if BoolValue(p.SubscriptionBillingCycleAnchorNow) {
body.Add(form.FormatKey(append(keyParts, "subscription_billing_cycle_anchor")), "now")
}
if BoolValue(p.SubscriptionBillingCycleAnchorUnchanged) {
body.Add(form.FormatKey(append(keyParts, "subscription_billing_cycle_anchor")), "unchanged")
}
}
// InvoiceListParams is the set of parameters that can be used when listing invoices.
// For more details see https://stripe.com/docs/api#list_customer_invoices.
type InvoiceListParams struct {
ListParams `form:"*"`
CollectionMethod *string `form:"collection_method"`
Customer *string `form:"customer"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
DueDate *int64 `form:"due_date"`
DueDateRange *RangeQueryParams `form:"due_date"`
Status *string `form:"status"`
Subscription *string `form:"subscription"`
}
// InvoiceLineListParams is the set of parameters that can be used when listing invoice line items.
// For more details see https://stripe.com/docs/api#invoice_lines.
type InvoiceLineListParams struct {
ListParams `form:"*"`
Customer *string `form:"customer"`
// ID is the invoice ID to list invoice lines for.
ID *string `form:"-"` // Goes in the URL
Subscription *string `form:"subscription"`
}
// InvoiceFinalizeParams is the set of parameters that can be used when finalizing invoices.
type InvoiceFinalizeParams struct {
Params `form:"*"`
AutoAdvance *bool `form:"auto_advance"`
}
// InvoiceMarkUncollectibleParams is the set of parameters that can be used when marking
// invoices as uncollectible.
type InvoiceMarkUncollectibleParams struct {
Params `form:"*"`
}
// InvoicePayParams is the set of parameters that can be used when
// paying invoices. For more details, see:
// https://stripe.com/docs/api#pay_invoice.
type InvoicePayParams struct {
Params `form:"*"`
Forgive *bool `form:"forgive"`
OffSession *bool `form:"off_session"`
PaidOutOfBand *bool `form:"paid_out_of_band"`
PaymentMethod *string `form:"payment_method"`
Source *string `form:"source"`
}
// InvoiceSendParams is the set of parameters that can be used when sending invoices.
type InvoiceSendParams struct {
Params `form:"*"`
}
// InvoiceVoidParams is the set of parameters that can be used when voiding invoices.
type InvoiceVoidParams struct {
Params `form:"*"`
}
// Invoice is the resource representing a Stripe invoice.
// For more details see https://stripe.com/docs/api#invoice_object.
type Invoice struct {
AccountCountry string `json:"account_country"`
AccountName string `json:"account_name"`
AmountDue int64 `json:"amount_due"`
AmountPaid int64 `json:"amount_paid"`
AmountRemaining int64 `json:"amount_remaining"`
ApplicationFeeAmount int64 `json:"application_fee_amount"`
AttemptCount int64 `json:"attempt_count"`
Attempted bool `json:"attempted"`
AutoAdvance bool `json:"auto_advance"`
BillingReason InvoiceBillingReason `json:"billing_reason"`
Charge *Charge `json:"charge"`
CollectionMethod *InvoiceCollectionMethod `json:"collection_method"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
CustomFields []*InvoiceCustomField `json:"custom_fields"`
Customer *Customer `json:"customer"`
CustomerAddress *Address `json:"customer_address"`
CustomerEmail string `json:"customer_email"`
CustomerName *string `json:"customer_name"`
CustomerPhone *string `json:"customer_phone"`
CustomerShipping *CustomerShippingDetails `json:"customer_shipping"`
CustomerTaxExempt CustomerTaxExempt `json:"customer_tax_exempt"`
CustomerTaxIDs []*InvoiceCustomerTaxID `json:"customer_tax_ids"`
DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"`
DefaultSource *PaymentSource `json:"default_source"`
DefaultTaxRates []*TaxRate `json:"default_tax_rates"`
Description string `json:"description"`
Discount *Discount `json:"discount"`
DueDate int64 `json:"due_date"`
EndingBalance int64 `json:"ending_balance"`
Footer string `json:"footer"`
HostedInvoiceURL string `json:"hosted_invoice_url"`
ID string `json:"id"`
InvoicePDF string `json:"invoice_pdf"`
Lines *InvoiceLineList `json:"lines"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
NextPaymentAttempt int64 `json:"next_payment_attempt"`
Number string `json:"number"`
Paid bool `json:"paid"`
PaymentIntent *PaymentIntent `json:"payment_intent"`
PeriodEnd int64 `json:"period_end"`
PeriodStart int64 `json:"period_start"`
PostPaymentCreditNotesAmount int64 `json:"post_payment_credit_notes_amount"`
PrePaymentCreditNotesAmount int64 `json:"pre_payment_credit_notes_amount"`
ReceiptNumber string `json:"receipt_number"`
StartingBalance int64 `json:"starting_balance"`
StatementDescriptor string `json:"statement_descriptor"`
Status InvoiceStatus `json:"status"`
StatusTransitions InvoiceStatusTransitions `json:"status_transitions"`
Subscription *Subscription `json:"subscription"`
SubscriptionProrationDate int64 `json:"subscription_proration_date"`
Subtotal int64 `json:"subtotal"`
Tax int64 `json:"tax"`
ThreasholdReason *InvoiceThresholdReason `json:"threshold_reason"`
Total int64 `json:"total"`
TotalTaxAmounts []*InvoiceTaxAmount `json:"total_tax_amounts"`
TransferData *InvoiceTransferData `json:"transfer_data"`
WebhooksDeliveredAt int64 `json:"webhooks_delivered_at"`
// This field is deprecated and we recommend that you use TaxRates instead.
TaxPercent float64 `json:"tax_percent"`
}
// InvoiceCustomField is a structure representing a custom field on an invoice.
type InvoiceCustomField struct {
Name string `json:"name"`
Value string `json:"value"`
}
// InvoiceCustomerTaxID is a structure representing a customer tax id on an invoice.
type InvoiceCustomerTaxID struct {
Type TaxIDType `json:"type"`
Value string `json:"value"`
}
// InvoiceTaxAmount is a structure representing one of the tax amounts on an invoice.
type InvoiceTaxAmount struct {
Amount int64 `json:"amount"`
Inclusive bool `json:"inclusive"`
TaxRate *TaxRate `json:"tax_rate"`
}
// InvoiceThresholdReason is a structure representing a reason for a billing threshold.
type InvoiceThresholdReason struct {
AmountGTE int64 `json:"amount_gte"`
ItemReasons []*InvoiceThresholdReasonItemReason `json:"item_reasons"`
}
// InvoiceThresholdReasonItemReason is a structure representing the line items that
// triggered an invoice.
type InvoiceThresholdReasonItemReason struct {
LineItemIDs []string `json:"line_item_ids"`
UsageGTE int64 `json:"usage_gte"`
}
// InvoiceList is a list of invoices as retrieved from a list endpoint.
type InvoiceList struct {
ListMeta
Data []*Invoice `json:"data"`
}
// InvoiceLine is the resource representing a Stripe invoice line item.
// For more details see https://stripe.com/docs/api#invoice_line_item_object.
type InvoiceLine struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
Description string `json:"description"`
Discountable bool `json:"discountable"`
ID string `json:"id"`
InvoiceItem string `json:"invoice_item"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Period *Period `json:"period"`
Plan *Plan `json:"plan"`
Proration bool `json:"proration"`
Quantity int64 `json:"quantity"`
Subscription string `json:"subscription"`
SubscriptionItem string `json:"subscription_item"`
TaxAmounts []*InvoiceTaxAmount `json:"tax_amounts"`
TaxRates []*TaxRate `json:"tax_rates"`
Type InvoiceLineType `json:"type"`
UnifiedProration bool `json:"unified_proration"`
}
// InvoiceTransferData represents the information for the transfer_data associated with an invoice.
type InvoiceTransferData struct {
Destination *Account `json:"destination"`
}
// Period is a structure representing a start and end dates.
type Period struct {
End int64 `json:"end"`
Start int64 `json:"start"`
}
// InvoiceLineList is a list object for invoice line items.
type InvoiceLineList struct {
ListMeta
Data []*InvoiceLine `json:"data"`
}
// InvoiceStatusTransitions are the timestamps at which the invoice status was updated.
type InvoiceStatusTransitions struct {
FinalizedAt int64 `json:"finalized_at"`
MarkedUncollectibleAt int64 `json:"marked_uncollectible_at"`
PaidAt int64 `json:"paid_at"`
VoidedAt int64 `json:"voided_at"`
}
// UnmarshalJSON handles deserialization of an Invoice.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *Invoice) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type invoice Invoice
var v invoice
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = Invoice(v)
return nil
}

87
vendor/github.com/stripe/stripe-go/invoiceitem.go generated vendored Normal file
View file

@ -0,0 +1,87 @@
package stripe
import "encoding/json"
// InvoiceItemParams is the set of parameters that can be used when creating or updating an invoice item.
// For more details see https://stripe.com/docs/api#create_invoiceitem and https://stripe.com/docs/api#update_invoiceitem.
type InvoiceItemParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
Currency *string `form:"currency"`
Customer *string `form:"customer"`
Description *string `form:"description"`
Discountable *bool `form:"discountable"`
Invoice *string `form:"invoice"`
Period *InvoiceItemPeriodParams `form:"period"`
Quantity *int64 `form:"quantity"`
Subscription *string `form:"subscription"`
TaxRates []*string `form:"tax_rates"`
UnitAmount *int64 `form:"unit_amount"`
UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"`
}
// InvoiceItemPeriodParams represents the period associated with that invoice item.
type InvoiceItemPeriodParams struct {
End *int64 `form:"end"`
Start *int64 `form:"start"`
}
// InvoiceItemListParams is the set of parameters that can be used when listing invoice items.
// For more details see https://stripe.com/docs/api#list_invoiceitems.
type InvoiceItemListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Customer *string `form:"customer"`
Invoice *string `form:"invoice"`
Pending *bool `form:"pending"`
}
// InvoiceItem is the resource represneting a Stripe invoice item.
// For more details see https://stripe.com/docs/api#invoiceitems.
type InvoiceItem struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
Customer *Customer `json:"customer"`
Date int64 `json:"date"`
Deleted bool `json:"deleted"`
Description string `json:"description"`
Discountable bool `json:"discountable"`
ID string `json:"id"`
Invoice *Invoice `json:"invoice"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Period *Period `json:"period"`
Plan *Plan `json:"plan"`
Proration bool `json:"proration"`
Quantity int64 `json:"quantity"`
Subscription *Subscription `json:"subscription"`
TaxRates []*TaxRate `json:"tax_rates"`
UnitAmount int64 `json:"unit_amount"`
UnitAmountDecimal float64 `json:"unit_amount_decimal,string"`
}
// InvoiceItemList is a list of invoice items as retrieved from a list endpoint.
type InvoiceItemList struct {
ListMeta
Data []*InvoiceItem `json:"data"`
}
// UnmarshalJSON handles deserialization of an InvoiceItem.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *InvoiceItem) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type invoiceItem InvoiceItem
var v invoiceItem
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = InvoiceItem(v)
return nil
}

View file

@ -0,0 +1,262 @@
package stripe
import "encoding/json"
// IssuingAuthorizationAuthorizationMethod is the list of possible values for the authorization method
// on an issuing authorization.
type IssuingAuthorizationAuthorizationMethod string
// List of values that IssuingAuthorizationAuthorizationMethod can take.
const (
IssuingAuthorizationAuthorizationMethodChip IssuingAuthorizationAuthorizationMethod = "chip"
IssuingAuthorizationAuthorizationMethodContactless IssuingAuthorizationAuthorizationMethod = "contactless"
IssuingAuthorizationAuthorizationMethodKeyedIn IssuingAuthorizationAuthorizationMethod = "keyed_in"
IssuingAuthorizationAuthorizationMethodOnline IssuingAuthorizationAuthorizationMethod = "online"
IssuingAuthorizationAuthorizationMethodSwipe IssuingAuthorizationAuthorizationMethod = "swipe"
)
// IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity is the list of possible values
// for the entity that owns the authorization control.
type IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity string
// List of values that IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity can take.
const (
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntityAccount IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity = "account"
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntityCard IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity = "card"
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntityCardholder IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity = "cardholder"
)
// IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName is the list of possible values
// for the name associated with the authorization control.
type IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName string
// List of values that IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName can take.
const (
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlNameAllowedCategories IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName = "allowed_categories"
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlNameBlockedCategories IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName = "blocked_categories"
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlNameMaxAmount IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName = "max_amount"
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlNameMaxApprovals IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName = "max_approvals"
IssuingAuthorizationRequestHistoryViolatedAuthorizationControlNameSpendingLimits IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName = "spending_limits"
)
// IssuingAuthorizationRequestHistoryReason is the list of possible values for the request history
// reason on an issuing authorization.
type IssuingAuthorizationRequestHistoryReason string
// List of values that IssuingAuthorizationRequestHistoryReason can take.
const (
IssuingAuthorizationRequestHistoryReasonAccountComplianceDisabled IssuingAuthorizationRequestHistoryReason = "account_compliance_disabled"
IssuingAuthorizationRequestHistoryReasonAccountInactive IssuingAuthorizationRequestHistoryReason = "account_inactive"
IssuingAuthorizationRequestHistoryReasonAuthenticationFailed IssuingAuthorizationRequestHistoryReason = "authentication_failed"
IssuingAuthorizationRequestHistoryReasonAuthorizationControls IssuingAuthorizationRequestHistoryReason = "authorization_controls"
IssuingAuthorizationRequestHistoryReasonCardActive IssuingAuthorizationRequestHistoryReason = "card_active"
IssuingAuthorizationRequestHistoryReasonCardInactive IssuingAuthorizationRequestHistoryReason = "card_inactive"
IssuingAuthorizationRequestHistoryReasonCardholderInactive IssuingAuthorizationRequestHistoryReason = "cardholder_inactive"
IssuingAuthorizationRequestHistoryReasonCardholderVerificationRequired IssuingAuthorizationRequestHistoryReason = "cardholder_verification_required"
IssuingAuthorizationRequestHistoryReasonIncorrectCVC IssuingAuthorizationRequestHistoryReason = "incorrect_cvc"
IssuingAuthorizationRequestHistoryReasonIncorrectExpiry IssuingAuthorizationRequestHistoryReason = "incorrect_expiry"
IssuingAuthorizationRequestHistoryReasonInsufficientFunds IssuingAuthorizationRequestHistoryReason = "insufficient_funds"
IssuingAuthorizationRequestHistoryReasonNotAllowed IssuingAuthorizationRequestHistoryReason = "not_allowed"
IssuingAuthorizationRequestHistoryReasonSuspectedFraud IssuingAuthorizationRequestHistoryReason = "suspected_fraud"
IssuingAuthorizationRequestHistoryReasonWebhookApproved IssuingAuthorizationRequestHistoryReason = "webhook_approved"
IssuingAuthorizationRequestHistoryReasonWebhookDeclined IssuingAuthorizationRequestHistoryReason = "webhook_declined"
IssuingAuthorizationRequestHistoryReasonWebhookTimeout IssuingAuthorizationRequestHistoryReason = "webhook_timeout"
)
// IssuingAuthorizationStatus is the possible values for status for an issuing authorization.
type IssuingAuthorizationStatus string
// List of values that IssuingAuthorizationStatus can take.
const (
IssuingAuthorizationStatusClosed IssuingAuthorizationStatus = "closed"
IssuingAuthorizationStatusPending IssuingAuthorizationStatus = "pending"
IssuingAuthorizationStatusReversed IssuingAuthorizationStatus = "reversed"
)
// IssuingAuthorizationVerificationDataAuthentication is the list of possible values for the result
// of an authentication on an issuing authorization.
type IssuingAuthorizationVerificationDataAuthentication string
// List of values that IssuingAuthorizationVerificationDataCheck can take.
const (
IssuingAuthorizationVerificationDataAuthenticationExempt IssuingAuthorizationVerificationDataAuthentication = "exempt"
IssuingAuthorizationVerificationDataAuthenticationFailure IssuingAuthorizationVerificationDataAuthentication = "failure"
IssuingAuthorizationVerificationDataAuthenticationNone IssuingAuthorizationVerificationDataAuthentication = "none"
IssuingAuthorizationVerificationDataAuthenticationSuccess IssuingAuthorizationVerificationDataAuthentication = "success"
)
// IssuingAuthorizationVerificationDataCheck is the list of possible values for result of a check
// for verification data on an issuing authorization.
type IssuingAuthorizationVerificationDataCheck string
// List of values that IssuingAuthorizationVerificationDataCheck can take.
const (
IssuingAuthorizationVerificationDataCheckMatch IssuingAuthorizationVerificationDataCheck = "match"
IssuingAuthorizationVerificationDataCheckMismatch IssuingAuthorizationVerificationDataCheck = "mismatch"
IssuingAuthorizationVerificationDataCheckNotProvided IssuingAuthorizationVerificationDataCheck = "not_provided"
)
// IssuingAuthorizationVerificationDataThreeDSecureResult is the list of possible values for result of 3DS.
type IssuingAuthorizationVerificationDataThreeDSecureResult string
// List of values that IssuingAuthorizationVerificationDataThreeDSecureResult can take.
const (
IssuingAuthorizationVerificationDataThreeDSecureResultAttemptAcknowledged IssuingAuthorizationVerificationDataThreeDSecureResult = "attempt_acknowledged"
IssuingAuthorizationVerificationDataThreeDSecureResultAuthenticated IssuingAuthorizationVerificationDataThreeDSecureResult = "authenticated"
IssuingAuthorizationVerificationDataThreeDSecureResultFailed IssuingAuthorizationVerificationDataThreeDSecureResult = "failed"
)
// IssuingAuthorizationWalletType is the list of possible values for the authorization's wallet provider.
type IssuingAuthorizationWalletType string
// List of values that IssuingAuthorizationWalletType can take.
const (
IssuingAuthorizationWalletTypeApplePay IssuingAuthorizationWalletType = "apple_pay"
IssuingAuthorizationWalletTypeGooglePay IssuingAuthorizationWalletType = "google_pay"
IssuingAuthorizationWalletTypeSamsungPay IssuingAuthorizationWalletType = "samsung_pay"
)
// IssuingAuthorizationWalletProviderType is the list of possible values for the authorization's wallet provider.
// TODO remove in the next major version
type IssuingAuthorizationWalletProviderType string
// List of values that IssuingAuthorizationWalletProviderType can take.
const (
IssuingAuthorizationWalletProviderTypeApplePay IssuingAuthorizationWalletProviderType = "apple_pay"
IssuingAuthorizationWalletProviderTypeGooglePay IssuingAuthorizationWalletProviderType = "google_pay"
IssuingAuthorizationWalletProviderTypeSamsungPay IssuingAuthorizationWalletProviderType = "samsung_pay"
)
// IssuingAuthorizationParams is the set of parameters that can be used when updating an issuing authorization.
type IssuingAuthorizationParams struct {
Params `form:"*"`
HeldAmount *int64 `form:"held_amount"`
}
// IssuingAuthorizationListParams is the set of parameters that can be used when listing issuing authorizations.
type IssuingAuthorizationListParams struct {
ListParams `form:"*"`
Card *string `form:"card"`
Cardholder *string `form:"cardholder"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Status *string `form:"status"`
}
// IssuingAuthorizationAuthorizationControls is the resource representing authorization controls on an issuing authorization.
type IssuingAuthorizationAuthorizationControls struct {
AllowedCategories []string `json:"allowed_categories"`
BlockedCategories []string `json:"blocked_categories"`
Currency Currency `json:"currency"`
MaxAmount int64 `json:"max_amount"`
MaxApprovals int64 `json:"max_approvals"`
}
// IssuingAuthorizationRequestHistoryViolatedAuthorizationControl is the resource representing an
// authorizaton control that caused the authorization to fail.
type IssuingAuthorizationRequestHistoryViolatedAuthorizationControl struct {
Entity IssuingAuthorizationRequestHistoryViolatedAuthorizationControlEntity `json:"entity"`
Name IssuingAuthorizationRequestHistoryViolatedAuthorizationControlName `json:"name"`
}
// IssuingAuthorizationRequestHistory is the resource representing a request history on an issuing authorization.
type IssuingAuthorizationRequestHistory struct {
Approved bool `json:"approved"`
AuthorizedAmount int64 `json:"authorized_amount"`
AuthorizedCurrency Currency `json:"authorized_currency"`
Created int64 `json:"created"`
HeldAmount int64 `json:"held_amount"`
HeldCurrency Currency `json:"held_currency"`
Reason IssuingAuthorizationRequestHistoryReason `json:"reason"`
ViolatedAuthorizationControls []*IssuingAuthorizationRequestHistoryViolatedAuthorizationControl `json:"violated_authorization_controls"`
}
// IssuingAuthorizationVerificationDataThreeDSecure is the resource representing 3DS results.
type IssuingAuthorizationVerificationDataThreeDSecure struct {
Result IssuingAuthorizationVerificationDataThreeDSecureResult `json:"result"`
}
// IssuingAuthorizationVerificationData is the resource representing verification data on an issuing authorization.
type IssuingAuthorizationVerificationData struct {
AddressLine1Check IssuingAuthorizationVerificationDataCheck `json:"address_line1_check"`
AddressPostalCodeCheck IssuingAuthorizationVerificationDataCheck `json:"address_postal_code_check"`
CVCCheck IssuingAuthorizationVerificationDataCheck `json:"cvc_check"`
ExpiryCheck IssuingAuthorizationVerificationDataCheck `json:"expiry_check"`
ThreeDSecure *IssuingAuthorizationVerificationDataThreeDSecure `json:"three_d_secure"`
// The property is considered deprecated. Use AddressPostalCodeCheck instead.
// TODO remove in the next major version
AddressZipCheck IssuingAuthorizationVerificationDataCheck `json:"address_zip_check"`
// The property is considered deprecated. Use ThreeDSecure instead.
// TODO remove in the next major version
Authentication IssuingAuthorizationVerificationDataAuthentication `json:"authentication"`
}
// IssuingAuthorization is the resource representing a Stripe issuing authorization.
type IssuingAuthorization struct {
Approved bool `json:"approved"`
AuthorizationMethod IssuingAuthorizationAuthorizationMethod `json:"authorization_method"`
AuthorizedAmount int64 `json:"authorized_amount"`
AuthorizedCurrency Currency `json:"authorized_currency"`
BalanceTransactions []*BalanceTransaction `json:"balance_transactions"`
Card *IssuingCard `json:"card"`
Cardholder *IssuingCardholder `json:"cardholder"`
Created int64 `json:"created"`
HeldAmount int64 `json:"held_amount"`
HeldCurrency Currency `json:"held_currency"`
ID string `json:"id"`
IsHeldAmountControllable bool `json:"is_held_amount_controllable"`
Livemode bool `json:"livemode"`
MerchantData *IssuingMerchantData `json:"merchant_data"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
PendingAuthorizedAmount int64 `json:"pending_authorized_amount"`
PendingHeldAmount int64 `json:"pending_held_amount"`
RequestHistory []*IssuingAuthorizationRequestHistory `json:"request_history"`
Status IssuingAuthorizationStatus `json:"status"`
Transactions []*IssuingTransaction `json:"transactions"`
VerificationData *IssuingAuthorizationVerificationData `json:"verification_data"`
Wallet IssuingAuthorizationWalletType `json:"wallet"`
// This property is deprecated and we recommend that you use Wallet instead.
// TODO: remove in the next major version
WalletProvider IssuingAuthorizationWalletProviderType `json:"wallet_provider"`
}
// IssuingMerchantData is the resource representing merchant data on Issuing APIs.
type IssuingMerchantData struct {
Category string `json:"category"`
City string `json:"city"`
Country string `json:"country"`
Name string `json:"name"`
NetworkID string `json:"network_id"`
PostalCode string `json:"postal_code"`
State string `json:"state"`
URL string `json:"url"`
}
// IssuingAuthorizationList is a list of issuing authorizations as retrieved from a list endpoint.
type IssuingAuthorizationList struct {
ListMeta
Data []*IssuingAuthorization `json:"data"`
}
// UnmarshalJSON handles deserialization of an IssuingAuthorization.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *IssuingAuthorization) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type issuingAuthorization IssuingAuthorization
var v issuingAuthorization
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = IssuingAuthorization(v)
return nil
}

270
vendor/github.com/stripe/stripe-go/issuing_card.go generated vendored Normal file
View file

@ -0,0 +1,270 @@
package stripe
import "encoding/json"
// IssuingCardPINStatus is the list of possible values for the status field of a Card PIN.
type IssuingCardPINStatus string
// List of values that IssuingCardPINStatus can take.
const (
IssuingCardPINStatusActive IssuingCardPINStatus = "active"
IssuingCardPINStatusBlocked IssuingCardPINStatus = "blocked"
)
// IssuingCardReplacementReason is the list of possible values for the replacement reason on an
// issuing card.
type IssuingCardReplacementReason string
// List of values that IssuingCardReplacementReason can take.
const (
IssuingCardReplacementReasonDamage IssuingCardReplacementReason = "damage"
IssuingCardReplacementReasonExpiration IssuingCardReplacementReason = "expiration"
IssuingCardReplacementReasonLoss IssuingCardReplacementReason = "loss"
IssuingCardReplacementReasonTheft IssuingCardReplacementReason = "theft"
)
// IssuingCardShippingStatus is the list of possible values for the shipping status
// on an issuing card.
type IssuingCardShippingStatus string
// List of values that IssuingCardShippingStatus can take.
const (
IssuingCardShippingTypeDelivered IssuingCardShippingStatus = "delivered"
IssuingCardShippingTypeFailure IssuingCardShippingStatus = "failure"
IssuingCardShippingTypePending IssuingCardShippingStatus = "pending"
IssuingCardShippingTypeReturned IssuingCardShippingStatus = "returned"
IssuingCardShippingTypeShipped IssuingCardShippingStatus = "shipped"
)
// IssuingCardShippingService is the shipment service for a card.
type IssuingCardShippingService string
// List of values that IssuingCardShippingService can take.
const (
IssuingCardShippingServiceExpress IssuingCardShippingService = "express"
IssuingCardShippingServiceOvernight IssuingCardShippingService = "overnight"
IssuingCardShippingServiceStandard IssuingCardShippingService = "standard"
)
// IssuingCardShippingSpeed is the shipment speed for a card.
type IssuingCardShippingSpeed string
// List of values that IssuingCardShippingSpeed can take.
const (
IssuingCardShippingSpeedExpress IssuingCardShippingSpeed = "express"
IssuingCardShippingSpeedOvernight IssuingCardShippingSpeed = "overnight"
IssuingCardShippingSpeedStandard IssuingCardShippingSpeed = "standard"
)
// IssuingCardShippingType is the list of possible values for the shipping type
// on an issuing card.
type IssuingCardShippingType string
// List of values that IssuingCardShippingType can take.
const (
IssuingCardShippingTypeBulk IssuingCardShippingType = "bulk"
IssuingCardShippingTypeIndividual IssuingCardShippingType = "individual"
)
// IssuingCardStatus is the list of possible values for status on an issuing card.
type IssuingCardStatus string
// List of values that IssuingCardStatus can take.
const (
IssuingCardStatusActive IssuingCardStatus = "active"
IssuingCardStatusCanceled IssuingCardStatus = "canceled"
IssuingCardStatusInactive IssuingCardStatus = "inactive"
IssuingCardStatusPending IssuingCardStatus = "pending"
)
// IssuingCardType is the type of an issuing card.
type IssuingCardType string
// List of values that IssuingCardType can take.
const (
IssuingCardTypePhysical IssuingCardType = "physical"
IssuingCardTypeVirtual IssuingCardType = "virtual"
)
// IssuingSpendingLimitInterval is the list of possible values for the interval of a given
// spending limit on an issuing card or cardholder.
type IssuingSpendingLimitInterval string
// List of values that IssuingCardShippingStatus can take.
const (
IssuingSpendingLimitIntervalAllTime IssuingSpendingLimitInterval = "all_time"
IssuingSpendingLimitIntervalDaily IssuingSpendingLimitInterval = "daily"
IssuingSpendingLimitIntervalMonthly IssuingSpendingLimitInterval = "monthly"
IssuingSpendingLimitIntervalPerAuthorization IssuingSpendingLimitInterval = "per_authorization"
IssuingSpendingLimitIntervalWeekly IssuingSpendingLimitInterval = "weekly"
IssuingSpendingLimitIntervalYearly IssuingSpendingLimitInterval = "yearly"
)
// IssuingAuthorizationControlsSpendingLimitsParams is the set of parameters that can be used for
// the spending limits associated with a given issuing card or cardholder.
type IssuingAuthorizationControlsSpendingLimitsParams struct {
Amount *int64 `form:"amount"`
Categories []*string `form:"categories"`
Interval *string `form:"interval"`
}
// AuthorizationControlsParams is the set of parameters that can be used for the shipping parameter.
// TODO: Rename and "un-share" between Card and Cardholder in the next major version.
type AuthorizationControlsParams struct {
AllowedCategories []*string `form:"allowed_categories"`
BlockedCategories []*string `form:"blocked_categories"`
MaxApprovals *int64 `form:"max_approvals"`
SpendingLimits []*IssuingAuthorizationControlsSpendingLimitsParams `form:"spending_limits"`
// The following parameter only applies to Cardholder
SpendingLimitsCurrency *string `form:"spending_limits_currency"`
// The following parameter is considered deprecated
MaxAmount *int64 `form:"max_amount"`
}
// IssuingCardShippingParams is the set of parameters that can be used for the shipping parameter.
type IssuingCardShippingParams struct {
Address *AddressParams `form:"address"`
Name string `form:"name"`
Service *string `form:"service"`
Type *string `form:"type"`
// This parameter is considered deprecated. Use Service instead.
// TODO remove in the next major version
Speed *string `form:"speed"`
}
// IssuingCardParams is the set of parameters that can be used when creating or updating an issuing card.
type IssuingCardParams struct {
Params `form:"*"`
AuthorizationControls *AuthorizationControlsParams `form:"authorization_controls"`
Billing *IssuingBillingParams `form:"billing"`
Cardholder *string `form:"cardholder"`
Currency *string `form:"currency"`
Name *string `form:"name"`
ReplacementFor *string `form:"replacement_for"`
ReplacementReason *string `form:"replacement_reason"`
Status *string `form:"status"`
Shipping *IssuingCardShippingParams `form:"shipping"`
Type *string `form:"type"`
}
// IssuingCardListParams is the set of parameters that can be used when listing issuing cards.
type IssuingCardListParams struct {
ListParams `form:"*"`
Cardholder *string `form:"cardholder"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
ExpMonth *int64 `form:"exp_month"`
ExpYear *int64 `form:"exp_year"`
Name *string `form:"name"`
Last4 *string `form:"last4"`
Source *string `form:"source"`
Status *string `form:"status"`
Type *string `form:"type"`
}
// IssuingCardDetails is the resource representing issuing card details.
type IssuingCardDetails struct {
Card *IssuingCard `json:"card"`
CVC string `json:"cvc"`
ExpMonth *string `form:"exp_month"`
ExpYear *string `form:"exp_year"`
Number string `json:"number"`
Object string `json:"object"`
}
// IssuingAuthorizationControlsSpendingLimits is the resource representing spending limits
// associated with a card or cardholder.
type IssuingAuthorizationControlsSpendingLimits struct {
Amount int64 `json:"amount"`
Categories []string `json:"categories"`
Interval IssuingSpendingLimitInterval `json:"interval"`
}
// IssuingCardAuthorizationControls is the resource representing authorization controls on an issuing card.
// TODO: Add the Cardholder version to "un-share" between Card and Cardholder in the next major version.
type IssuingCardAuthorizationControls struct {
AllowedCategories []string `json:"allowed_categories"`
BlockedCategories []string `json:"blocked_categories"`
MaxApprovals int64 `json:"max_approvals"`
SpendingLimits []*IssuingAuthorizationControlsSpendingLimits `json:"spending_limits"`
SpendingLimitsCurrency Currency `json:"spending_limits_currency"`
// The properties below are considered deprecated and can only be used for an issuing card.
// TODO remove in the next major version
Currency Currency `json:"currency"`
MaxAmount int64 `json:"max_amount"`
}
// IssuingCardPIN contains data about the Card's PIN.
type IssuingCardPIN struct {
Status IssuingCardPINStatus `json:"status"`
}
// IssuingCardShipping is the resource representing shipping on an issuing card.
type IssuingCardShipping struct {
Address *Address `json:"address"`
Carrier string `json:"carrier"`
ETA int64 `json:"eta"`
Name string `json:"name"`
Phone string `json:"phone"`
Service IssuingCardShippingService `json:"service"`
Status IssuingCardShippingStatus `json:"status"`
TrackingNumber string `json:"tracking_number"`
TrackingURL string `json:"tracking_url"`
Type IssuingCardShippingType `json:"type"`
// The property is considered deprecated. Use AddressPostalCodeCheck instead.
// TODO remove in the next major version
Speed IssuingCardShippingSpeed `json:"speed"`
}
// IssuingCard is the resource representing a Stripe issuing card.
type IssuingCard struct {
AuthorizationControls *IssuingCardAuthorizationControls `json:"authorization_controls"`
Billing *IssuingBilling `json:"billing"`
Brand string `json:"brand"`
Cardholder *IssuingCardholder `json:"cardholder"`
Created int64 `json:"created"`
ExpMonth int64 `json:"exp_month"`
ExpYear int64 `json:"exp_year"`
Last4 string `json:"last4"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
Object string `json:"object"`
PIN *IssuingCardPIN `json:"pin"`
ReplacementFor *IssuingCard `json:"replacement_for"`
ReplacementReason IssuingCardReplacementReason `json:"replacement_reason"`
Shipping *IssuingCardShipping `json:"shipping"`
Status IssuingCardStatus `json:"status"`
Type IssuingCardType `json:"type"`
}
// IssuingCardList is a list of issuing cards as retrieved from a list endpoint.
type IssuingCardList struct {
ListMeta
Data []*IssuingCard `json:"data"`
}
// UnmarshalJSON handles deserialization of an IssuingCard.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *IssuingCard) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type issuingCard IssuingCard
var v issuingCard
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = IssuingCard(v)
return nil
}

View file

@ -0,0 +1,200 @@
package stripe
import "encoding/json"
// IssuingCardholderRequirementsDisabledReason is the possible values for the disabled reason on an
// issuing cardholder.
type IssuingCardholderRequirementsDisabledReason string
// List of values that IssuingCardholderRequirementsDisabledReason can take.
const (
IssuingCardholderRequirementsDisabledReasonListed IssuingCardholderRequirementsDisabledReason = "listed"
IssuingCardholderRequirementsDisabledReasonRejectedListed IssuingCardholderRequirementsDisabledReason = "rejected.listed"
IssuingCardholderRequirementsDisabledReasonUnderReview IssuingCardholderRequirementsDisabledReason = "under_review"
)
// IssuingCardholderStatus is the possible values for status on an issuing cardholder.
type IssuingCardholderStatus string
// List of values that IssuingCardholderStatus can take.
const (
IssuingCardholderStatusActive IssuingCardholderStatus = "active"
IssuingCardholderStatusInactive IssuingCardholderStatus = "inactive"
IssuingCardholderStatusPending IssuingCardholderStatus = "pending"
)
// IssuingCardholderType is the type of an issuing cardholder.
type IssuingCardholderType string
// List of values that IssuingCardholderType can take.
const (
IssuingCardholderTypeBusinessEntity IssuingCardholderType = "business_entity"
IssuingCardholderTypeIndividual IssuingCardholderType = "individual"
)
// IssuingBillingParams is the set of parameters that can be used for billing with the Issuing APIs.
type IssuingBillingParams struct {
Address *AddressParams `form:"address"`
Name *string `form:"name"`
}
// IssuingCardholderCompanyParams represents additional information about a
// `business_entity` cardholder.
type IssuingCardholderCompanyParams struct {
TaxID *string `form:"tax_id"`
}
// IssuingCardholderIndividualVerificationDocumentParams represents an
// identifying document, either a passport or local ID card.
type IssuingCardholderIndividualVerificationDocumentParams struct {
Back *string `form:"back"`
Front *string `form:"front"`
}
// IssuingCardholderIndividualVerificationParams represents government-issued ID
// document for this cardholder.
type IssuingCardholderIndividualVerificationParams struct {
Document *IssuingCardholderIndividualVerificationDocumentParams `form:"document"`
}
// IssuingCardholderIndividualDOBParams represents the date of birth of the
// cardholder individual.
type IssuingCardholderIndividualDOBParams struct {
Day *int64 `form:"day"`
Month *int64 `form:"month"`
Year *int64 `form:"year"`
}
// IssuingCardholderIndividualParams represents additional information about an
// `individual` cardholder.
type IssuingCardholderIndividualParams struct {
DOB *IssuingCardholderIndividualDOBParams `form:"dob"`
FirstName *string `form:"first_name"`
LastName *string `form:"last_name"`
Verification *IssuingCardholderIndividualVerificationParams `form:"verification"`
}
// IssuingCardholderParams is the set of parameters that can be used when creating or updating an issuing cardholder.
type IssuingCardholderParams struct {
Params `form:"*"`
AuthorizationControls *AuthorizationControlsParams `form:"authorization_controls"`
Billing *IssuingBillingParams `form:"billing"`
Company *IssuingCardholderCompanyParams `form:"company"`
Email *string `form:"email"`
Individual *IssuingCardholderIndividualParams `form:"individual"`
Name *string `form:"name"`
PhoneNumber *string `form:"phone_number"`
Status *string `form:"status"`
Type *string `form:"type"`
// This parameter is considered deprecated.
// TODO remove in the next major version
IsDefault *bool `form:"is_default"`
}
// IssuingCardholderListParams is the set of parameters that can be used when listing issuing cardholders.
type IssuingCardholderListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Email *string `form:"email"`
PhoneNumber *string `form:"phone_number"`
Status *string `form:"status"`
Type *string `form:"type"`
// The property is considered deprecated.
// TODO remove in the next major version
IsDefault *bool `form:"is_default"`
}
// IssuingBilling is the resource representing the billing hash with the Issuing APIs.
type IssuingBilling struct {
Address *Address `json:"address"`
Name string `json:"name"`
}
// IssuingCardholderRequirements contains the verification requirements for the cardholder.
type IssuingCardholderRequirements struct {
DisabledReason IssuingCardholderRequirementsDisabledReason `json:"disabled_reason"`
PastDue []string `json:"past_due"`
}
// IssuingCardholderIndividualVerificationDocument represents an identifying
// document, either a passport or local ID card.
type IssuingCardholderIndividualVerificationDocument struct {
Back *File `json:"back"`
Front *File `json:"front"`
}
// IssuingCardholderIndividualVerification represents the Government-issued ID
// document for this cardholder
type IssuingCardholderIndividualVerification struct {
Document *IssuingCardholderIndividualVerificationDocument `json:"document"`
}
// IssuingCardholderIndividualDOB represents the date of birth of the issuing card hoder
// individual.
type IssuingCardholderIndividualDOB struct {
Day int64 `json:"day"`
Month int64 `json:"month"`
Year int64 `json:"year"`
}
// IssuingCardholderIndividual represents additional information about an
// individual cardholder.
type IssuingCardholderIndividual struct {
DOB *IssuingCardholderIndividualDOB `json:"dob"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Verification *IssuingCardholderIndividualVerification `json:"verification"`
}
// IssuingCardholderCompany represents additional information about a
// business_entity cardholder.
type IssuingCardholderCompany struct {
TaxIDProvided bool `json:"tax_id_provided"`
}
// IssuingCardholder is the resource representing a Stripe issuing cardholder.
type IssuingCardholder struct {
AuthorizationControls *IssuingCardAuthorizationControls `json:"authorization_controls"`
Billing *IssuingBilling `json:"billing"`
Company *IssuingCardholderCompany `json:"company"`
Created int64 `json:"created"`
Email string `json:"email"`
ID string `json:"id"`
Individual *IssuingCardholderIndividual `json:"individual"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
Object string `json:"object"`
PhoneNumber string `json:"phone_number"`
Requirements *IssuingCardholderRequirements `json:"requirements"`
Status IssuingCardholderStatus `json:"status"`
Type IssuingCardholderType `json:"type"`
}
// IssuingCardholderList is a list of issuing cardholders as retrieved from a list endpoint.
type IssuingCardholderList struct {
ListMeta
Data []*IssuingCardholder `json:"data"`
}
// UnmarshalJSON handles deserialization of an IssuingCardholder.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *IssuingCardholder) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type issuingCardholder IssuingCardholder
var v issuingCardholder
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = IssuingCardholder(v)
return nil
}

123
vendor/github.com/stripe/stripe-go/issuing_dispute.go generated vendored Normal file
View file

@ -0,0 +1,123 @@
package stripe
import "encoding/json"
// IssuingDisputeReason is the list of possible values for status on an issuing dispute.
type IssuingDisputeReason string
// List of values that IssuingDisputeReason can take.
const (
IssuingDisputeReasonDuplicate IssuingDisputeReason = "duplicate"
IssuingDisputeReasonFraudulent IssuingDisputeReason = "fraudulent"
IssuingDisputeReasonOther IssuingDisputeReason = "other"
IssuingDisputeReasonProductNotReceived IssuingDisputeReason = "product_not_received"
)
// IssuingDisputeStatus is the list of possible values for status on an issuing dispute.
type IssuingDisputeStatus string
// List of values that IssuingDisputeStatus can take.
const (
IssuingDisputeStatusLost IssuingDisputeStatus = "lost"
IssuingDisputeStatusUnderReview IssuingDisputeStatus = "under_review"
IssuingDisputeStatusUnsubmitted IssuingDisputeStatus = "unsubmitted"
IssuingDisputeStatusWon IssuingDisputeStatus = "won"
)
// IssuingDisputeEvidenceFraudulentParams is the subset of parameters that can be sent as evidence for an issuing dispute
// with the reason set as fraudulent.
type IssuingDisputeEvidenceFraudulentParams struct {
DisputeExplanation *string `form:"dispute_explanation"`
UncategorizedFile *string `form:"uncategorized_file"`
}
// IssuingDisputeEvidenceOtherParams is the subset of parameters that can be sent as evidence for an issuing dispute
// with the reason set as other.
type IssuingDisputeEvidenceOtherParams struct {
DisputeExplanation *string `form:"dispute_explanation"`
UncategorizedFile *string `form:"uncategorized_file"`
}
// IssuingDisputeEvidenceParams is the set of parameters that can be sent as evidence for an issuing dispute.
type IssuingDisputeEvidenceParams struct {
Fraudulent *IssuingDisputeEvidenceFraudulentParams `form:"fraudulent"`
Other *IssuingDisputeEvidenceOtherParams `form:"other"`
}
// IssuingDisputeParams is the set of parameters that can be used when creating or updating an issuing dispute.
type IssuingDisputeParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
Evidence *IssuingDisputeEvidenceParams `form:"evidence"`
Reason *string `form:"reason"`
DisputedTransaction *string `form:"disputed_transaction"`
}
// IssuingDisputeListParams is the set of parameters that can be used when listing issuing dispute.
type IssuingDisputeListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
DisputedTransaction *string `form:"disputed_transaction"`
Transaction *string `form:"transaction"`
}
// IssuingDisputeEvidenceFraudulent is the resource representing the evidence hash on an issuing dispute
// with the reason set as fraudulent.
type IssuingDisputeEvidenceFraudulent struct {
DisputeExplanation string `json:"dispute_explanation"`
UncategorizedFile *File `json:"uncategorized_file"`
}
// IssuingDisputeEvidenceOther is the resource representing the evidence hash on an issuing dispute
// with the reason set as other.
type IssuingDisputeEvidenceOther struct {
DisputeExplanation string `json:"dispute_explanation"`
UncategorizedFile *File `json:"uncategorized_file"`
}
// IssuingDisputeEvidence is the resource representing evidence on an issuing dispute.
type IssuingDisputeEvidence struct {
Fraudulent *IssuingDisputeEvidenceFraudulent `json:"fraudulent"`
Other *IssuingDisputeEvidenceOther `json:"other"`
}
// IssuingDispute is the resource representing an issuing dispute.
type IssuingDispute struct {
Amount int64 `json:"amount"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Evidence *IssuingDisputeEvidence `json:"evidence"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
Reason IssuingDisputeReason `json:"reason"`
Status IssuingDisputeStatus `json:"status"`
Transaction *IssuingTransaction `json:"transaction"`
}
// IssuingDisputeList is a list of issuing disputes as retrieved from a list endpoint.
type IssuingDisputeList struct {
ListMeta
Data []*IssuingDispute `json:"data"`
}
// UnmarshalJSON handles deserialization of an IssuingDispute.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *IssuingDispute) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type issuingDispute IssuingDispute
var v issuingDispute
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = IssuingDispute(v)
return nil
}

View file

@ -0,0 +1,74 @@
package stripe
import "encoding/json"
// IssuingTransactionType is the type of an issuing transaction.
type IssuingTransactionType string
// List of values that IssuingTransactionType can take.
const (
IssuingTransactionTypeCapture IssuingTransactionType = "capture"
IssuingTransactionTypeCashWithdrawal IssuingTransactionType = "cash_withdrawal"
IssuingTransactionTypeRefund IssuingTransactionType = "refund"
IssuingTransactionTypeRefundReversal IssuingTransactionType = "refund_reversal"
)
// IssuingTransactionParams is the set of parameters that can be used when creating or updating an issuing transaction.
type IssuingTransactionParams struct {
Params `form:"*"`
}
// IssuingTransactionListParams is the set of parameters that can be used when listing issuing transactions.
type IssuingTransactionListParams struct {
ListParams `form:"*"`
Card *string `form:"card"`
Cardholder *string `form:"cardholder"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Dispute *string `form:"dispute"`
}
// IssuingTransaction is the resource representing a Stripe issuing transaction.
type IssuingTransaction struct {
Amount int64 `json:"amount"`
Authorization *IssuingAuthorization `json:"authorization"`
BalanceTransaction *BalanceTransaction `json:"balance_transaction"`
Card *IssuingCard `json:"card"`
Cardholder *IssuingCardholder `json:"cardholder"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Dispute *IssuingDispute `json:"dispute"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
MerchantData *IssuingMerchantData `json:"merchant_data"`
MerchantAmount int64 `json:"merchant_amount"`
MerchantCurrency Currency `json:"merchant_currency"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
Type IssuingTransactionType `json:"type"`
}
// IssuingTransactionList is a list of issuing transactions as retrieved from a list endpoint.
type IssuingTransactionList struct {
ListMeta
Data []*IssuingTransaction `json:"data"`
}
// UnmarshalJSON handles deserialization of an IssuingTransaction.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *IssuingTransaction) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type issuingTransaction IssuingTransaction
var v issuingTransaction
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = IssuingTransaction(v)
return nil
}

133
vendor/github.com/stripe/stripe-go/iter.go generated vendored Normal file
View file

@ -0,0 +1,133 @@
package stripe
import (
"reflect"
"github.com/stripe/stripe-go/form"
)
//
// Public types
//
// Iter provides a convenient interface
// for iterating over the elements
// returned from paginated list API calls.
// Successive calls to the Next method
// will step through each item in the list,
// fetching pages of items as needed.
// Iterators are not thread-safe, so they should not be consumed
// across multiple goroutines.
type Iter struct {
cur interface{}
err error
formValues *form.Values
listParams ListParams
meta ListMeta
query Query
values []interface{}
}
// Current returns the most recent item
// visited by a call to Next.
func (it *Iter) Current() interface{} {
return it.cur
}
// Err returns the error, if any,
// that caused the Iter to stop.
// It must be inspected
// after Next returns false.
func (it *Iter) Err() error {
return it.err
}
// Meta returns the list metadata.
func (it *Iter) Meta() *ListMeta {
return &it.meta
}
// Next advances the Iter to the next item in the list,
// which will then be available
// through the Current method.
// It returns false when the iterator stops
// at the end of the list.
func (it *Iter) Next() bool {
if len(it.values) == 0 && it.meta.HasMore && !it.listParams.Single {
// determine if we're moving forward or backwards in paging
if it.listParams.EndingBefore != nil {
it.listParams.EndingBefore = String(listItemID(it.cur))
it.formValues.Set(EndingBefore, *it.listParams.EndingBefore)
} else {
it.listParams.StartingAfter = String(listItemID(it.cur))
it.formValues.Set(StartingAfter, *it.listParams.StartingAfter)
}
it.getPage()
}
if len(it.values) == 0 {
return false
}
it.cur = it.values[0]
it.values = it.values[1:]
return true
}
func (it *Iter) getPage() {
it.values, it.meta, it.err = it.query(it.listParams.GetParams(), it.formValues)
if it.listParams.EndingBefore != nil {
// We are moving backward,
// but items arrive in forward order.
reverse(it.values)
}
}
// Query is the function used to get a page listing.
type Query func(*Params, *form.Values) ([]interface{}, ListMeta, error)
//
// Public functions
//
// GetIter returns a new Iter for a given query and its options.
func GetIter(container ListParamsContainer, query Query) *Iter {
var listParams *ListParams
formValues := &form.Values{}
if container != nil {
reflectValue := reflect.ValueOf(container)
// See the comment on Call in stripe.go.
if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() {
listParams = container.GetListParams()
form.AppendTo(formValues, container)
}
}
if listParams == nil {
listParams = &ListParams{}
}
iter := &Iter{
formValues: formValues,
listParams: *listParams,
query: query,
}
iter.getPage()
return iter
}
//
// Private functions
//
func listItemID(x interface{}) string {
return reflect.ValueOf(x).Elem().FieldByName("ID").String()
}
func reverse(a []interface{}) {
for i := 0; i < len(a)/2; i++ {
a[i], a[len(a)-i-1] = a[len(a)-i-1], a[i]
}
}

221
vendor/github.com/stripe/stripe-go/log.go generated vendored Normal file
View file

@ -0,0 +1,221 @@
package stripe
import (
"fmt"
"io"
"log"
"os"
)
//
// Public constants
//
const (
// LevelError sets a logger to show error messages only.
LevelError Level = 1
// LevelWarn sets a logger to show warning messages or anything more
// severe.
LevelWarn Level = 2
// LevelInfo sets a logger to show informational messages or anything more
// severe.
LevelInfo Level = 3
// LevelDebug sets a logger to show informational messages or anything more
// severe.
LevelDebug Level = 4
// Older deprecated levels for Printfer-style logging.
printferLevelError = 1
printferLevelInfo = 2
printferLevelDebug = 3
)
//
// Public variables
//
// DefaultLeveledLogger is the default logger that the library will use to log
// errors, warnings, and informational messages.
//
// LeveledLoggerInterface is implemented by LeveledLogger, and one can be
// initialized at the desired level of logging. LeveledLoggerInterface also
// provides out-of-the-box compatibility with a Logrus Logger, but may require
// a thin shim for use with other logging libraries that use less standard
// conventions like Zap.
//
// This Logger will be inherited by any backends created by default, but will
// be overridden if a backend is created with GetBackendWithConfig with a
// custom LeveledLogger set.
var DefaultLeveledLogger LeveledLoggerInterface
// LogLevel is the logging level for this library.
// 0: no logging
// 1: errors only
// 2: errors + informational (default)
// 3: errors + informational + debug
//
// Deprecated: Logging should be configured with DefaultLeveledLogger instead.
var LogLevel = 2
// Logger controls how stripe performs logging at a package level. It is useful
// to customise if you need it prefixed for your application to meet other
// requirements.
//
// This Logger will be inherited by any backends created by default, but will
// be overridden if a backend is created with GetBackendWithConfig with a
// custom Logger set.
//
// Deprecated: Logging should be configured with DefaultLeveledLogger instead.
var Logger Printfer
//
// Public types
//
// Level represents a logging level.
type Level uint32
// LeveledLogger is a leveled logger implementation.
//
// It prints warnings and errors to `os.Stderr` and other messages to
// `os.Stdout`.
type LeveledLogger struct {
// Level is the minimum logging level that will be emitted by this logger.
//
// For example, a Level set to LevelWarn will emit warnings and errors, but
// not informational or debug messages.
//
// Always set this with a constant like LevelWarn because the individual
// values are not guaranteed to be stable.
Level Level
// Internal testing use only.
stderrOverride io.Writer
stdoutOverride io.Writer
}
// Debugf logs a debug message using Printf conventions.
func (l *LeveledLogger) Debugf(format string, v ...interface{}) {
if l.Level >= LevelDebug {
fmt.Fprintf(l.stdout(), "[DEBUG] "+format+"\n", v...)
}
}
// Errorf logs a warning message using Printf conventions.
func (l *LeveledLogger) Errorf(format string, v ...interface{}) {
// Infof logs a debug message using Printf conventions.
if l.Level >= LevelError {
fmt.Fprintf(l.stderr(), "[ERROR] "+format+"\n", v...)
}
}
// Infof logs an informational message using Printf conventions.
func (l *LeveledLogger) Infof(format string, v ...interface{}) {
if l.Level >= LevelInfo {
fmt.Fprintf(l.stdout(), "[INFO] "+format+"\n", v...)
}
}
// Warnf logs a warning message using Printf conventions.
func (l *LeveledLogger) Warnf(format string, v ...interface{}) {
if l.Level >= LevelWarn {
fmt.Fprintf(l.stderr(), "[WARN] "+format+"\n", v...)
}
}
func (l *LeveledLogger) stderr() io.Writer {
if l.stderrOverride != nil {
return l.stderrOverride
}
return os.Stderr
}
func (l *LeveledLogger) stdout() io.Writer {
if l.stdoutOverride != nil {
return l.stdoutOverride
}
return os.Stdout
}
// LeveledLoggerInterface provides a basic leveled logging interface for
// printing debug, informational, warning, and error messages.
//
// It's implemented by LeveledLogger and also provides out-of-the-box
// compatibility with a Logrus Logger, but may require a thin shim for use with
// other logging libraries that you use less standard conventions like Zap.
type LeveledLoggerInterface interface {
// Debugf logs a debug message using Printf conventions.
Debugf(format string, v ...interface{})
// Errorf logs a warning message using Printf conventions.
Errorf(format string, v ...interface{})
// Infof logs an informational message using Printf conventions.
Infof(format string, v ...interface{})
// Warnf logs a warning message using Printf conventions.
Warnf(format string, v ...interface{})
}
// Printfer is an interface to be implemented by Logger.
type Printfer interface {
Printf(format string, v ...interface{})
}
//
// Private types
//
// Level represents a deprecated logging level.
type printferLevel uint32
type leveledLoggerPrintferShim struct {
level printferLevel
logger Printfer
}
// Debugf logs a debug message using Printf conventions.
func (l *leveledLoggerPrintferShim) Debugf(format string, v ...interface{}) {
if l.level >= printferLevelDebug {
l.logger.Printf(format+"\n", v...)
}
}
// Errorf logs a warning message using Printf conventions.
func (l *leveledLoggerPrintferShim) Errorf(format string, v ...interface{}) {
if l.level >= printferLevelError {
l.logger.Printf(format+"\n", v...)
}
}
// Infof logs an informational message using Printf conventions.
func (l *leveledLoggerPrintferShim) Infof(format string, v ...interface{}) {
if l.level >= printferLevelInfo {
l.logger.Printf(format+"\n", v...)
}
}
// Warnf logs a warning message using Printf conventions.
func (l *leveledLoggerPrintferShim) Warnf(format string, v ...interface{}) {
// The original Stripe log level system didn't have a concept for warnings,
// so just reuse the same levels as error.
if l.level >= printferLevelError {
l.logger.Printf(format+"\n", v...)
}
}
//
// Private functions
//
func init() {
// Defaults to logging nothing, but also makes sure that we have a logger
// so that we don't panic on a `nil` when the library tries to log
// something.
Logger = log.New(os.Stderr, "", log.LstdFlags)
}

16
vendor/github.com/stripe/stripe-go/loginlink.go generated vendored Normal file
View file

@ -0,0 +1,16 @@
package stripe
// LoginLinkParams is the set of parameters that can be used when creating a login_link.
// For more details see https://stripe.com/docs/api#create_login_link.
type LoginLinkParams struct {
Params `form:"*"`
Account *string `form:"-"` // Included in URL
RedirectURL *string `form:"redirect_url"`
}
// LoginLink is the resource representing a login link for Express accounts.
// For more details see https://stripe.com/docs/api#login_link_object
type LoginLink struct {
Created int64 `json:"created"`
URL string `json:"url"`
}

126
vendor/github.com/stripe/stripe-go/mandate.go generated vendored Normal file
View file

@ -0,0 +1,126 @@
package stripe
import "encoding/json"
// List of values that MandateStatus can take.
const (
MandateCustomerAcceptanceTypeOffline MandateCustomerAcceptanceType = "offline"
MandateCustomerAcceptanceTypeOnline MandateCustomerAcceptanceType = "online"
)
// MandateCustomerAcceptanceType is the list of allowed values for the type of customer acceptance
// for a given mandate..
type MandateCustomerAcceptanceType string
// List of values that MandateStatus can take.
const (
MandateStatusActive MandateStatus = "active"
MandateStatusInactive MandateStatus = "inactive"
MandateStatusPending MandateStatus = "pending"
)
// MandateStatus is the list of allowed values for the mandate status.
type MandateStatus string
// List of values that MandateType can take.
const (
MandateTypeMultiUse MandateType = "multi_use"
MandateTypeSingleUse MandateType = "single_use"
)
// MandateType is the list of allowed values for the mandate type.
type MandateType string
// MandateParams is the set of parameters that can be used when retrieving a mandate.
type MandateParams struct {
Params `form:"*"`
}
// MandateCustomerAcceptanceOffline represents details about the customer acceptance of an offline
// mandate.
type MandateCustomerAcceptanceOffline struct {
}
// MandateCustomerAcceptanceOnline represents details about the customer acceptance of an online
// mandate.
type MandateCustomerAcceptanceOnline struct {
IPAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
}
// MandateCustomerAcceptance represents details about the customer acceptance for a mandate.
type MandateCustomerAcceptance struct {
AcceptedAt int64 `json:"accepted_at"`
Offline *MandateCustomerAcceptanceOffline `json:"offline"`
Online *MandateCustomerAcceptanceOnline `json:"online"`
Type MandateCustomerAcceptanceType `json:"type"`
}
// MandateMultiUse represents details about a multi-use mandate.
type MandateMultiUse struct {
}
// MandatePaymentMethodDetailsAUBECSDebit represents details about the Australia BECS debit account
// associated with this mandate.
type MandatePaymentMethodDetailsAUBECSDebit struct {
URL string `json:"url"`
}
// MandatePaymentMethodDetailsCard represents details about the card associated with this mandate.
type MandatePaymentMethodDetailsCard struct {
}
// MandatePaymentMethodDetailsSepaDebit represents details about the SEPA debit bank account
// associated with this mandate.
type MandatePaymentMethodDetailsSepaDebit struct {
Reference string `json:"reference"`
URL string `json:"url"`
}
// MandatePaymentMethodDetails represents details about the payment method associated with this
// mandate.
type MandatePaymentMethodDetails struct {
AUBECSDebit *MandatePaymentMethodDetailsAUBECSDebit `json:"au_becs_debit"`
Card *MandatePaymentMethodDetailsCard `json:"card"`
SepaDebit *MandatePaymentMethodDetailsSepaDebit `json:"sepa_debit"`
Type PaymentMethodType `json:"type"`
}
// MandateSingleUse represents details about a single-use mandate.
type MandateSingleUse struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
}
// Mandate is the resource representing a Mandate.
type Mandate struct {
CustomerAcceptance *MandateCustomerAcceptance `json:"customer_acceptance"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
MultiUse *MandateMultiUse `json:"multi_use"`
Object string `json:"object"`
PaymentMethod *PaymentMethod `json:"payment_method"`
PaymentMethodDetails *MandatePaymentMethodDetails `json:"payment_method_details"`
SingleUse *MandateSingleUse `json:"single_use"`
Status MandateStatus `json:"status"`
Type MandateType `json:"type"`
}
// UnmarshalJSON handles deserialization of a Mandate.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *Mandate) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type ma Mandate
var v ma
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = Mandate(v)
return nil
}

129
vendor/github.com/stripe/stripe-go/oauth.go generated vendored Normal file
View file

@ -0,0 +1,129 @@
package stripe
// OAuthScopeType is the type of OAuth scope.
type OAuthScopeType string
// List of possible values for OAuth scopes.
const (
OAuthScopeTypeReadOnly OAuthScopeType = "read_only"
OAuthScopeTypeReadWrite OAuthScopeType = "read_write"
)
// OAuthTokenType is the type of token. This will always be "bearer."
type OAuthTokenType string
// List of possible OAuthTokenType values.
const (
OAuthTokenTypeBearer OAuthTokenType = "bearer"
)
// OAuthStripeUserBusinessType is the business type for the Stripe oauth user.
type OAuthStripeUserBusinessType string
// List of supported values for business type.
const (
OAuthStripeUserBusinessTypeCorporation OAuthStripeUserBusinessType = "corporation"
OAuthStripeUserBusinessTypeLLC OAuthStripeUserBusinessType = "llc"
OAuthStripeUserBusinessTypeNonProfit OAuthStripeUserBusinessType = "non_profit"
OAuthStripeUserBusinessTypePartnership OAuthStripeUserBusinessType = "partnership"
OAuthStripeUserBusinessTypeSoleProp OAuthStripeUserBusinessType = "sole_prop"
)
// OAuthStripeUserGender of the person who will be filling out a Stripe
// application. (International regulations require either male or female.)
type OAuthStripeUserGender string
// The gender of the person who will be filling out a Stripe application.
// (International regulations require either male or female.)
const (
OAuthStripeUserGenderFemale OAuthStripeUserGender = "female"
OAuthStripeUserGenderMale OAuthStripeUserGender = "male"
)
// OAuthStripeUserParams for the stripe_user OAuth Authorize params.
type OAuthStripeUserParams struct {
BlockKana *string `form:"block_kana"`
BlockKanji *string `form:"block_kanji"`
BuildingKana *string `form:"building_kana"`
BuildingKanji *string `form:"building_kanji"`
BusinessName *string `form:"business_name"`
BusinessType *string `form:"business_type"`
City *string `form:"city"`
Country *string `form:"country"`
Currency *string `form:"currency"`
DOBDay *int64 `form:"dob_day"`
DOBMonth *int64 `form:"dob_month"`
DOBYear *int64 `form:"dob_year"`
Email *string `form:"email"`
FirstName *string `form:"first_name"`
FirstNameKana *string `form:"first_name_kana"`
FirstNameKanji *string `form:"first_name_kanji"`
Gender *string `form:"gender"`
LastName *string `form:"last_name"`
LastNameKana *string `form:"last_name_kana"`
LastNameKanji *string `form:"last_name_kanji"`
PhoneNumber *string `form:"phone_number"`
PhysicalProduct *bool `form:"physical_product"`
ProductDescription *string `form:"product_description"`
State *string `form:"state"`
StreetAddress *string `form:"street_address"`
URL *string `form:"url"`
Zip *string `form:"zip"`
}
// AuthorizeURLParams for creating OAuth AuthorizeURLs.
type AuthorizeURLParams struct {
Params `form:"*"`
AlwaysPrompt *bool `form:"always_prompt"`
ClientID *string `form:"client_id"`
RedirectURI *string `form:"redirect_uri"`
ResponseType *string `form:"response_type"`
Scope *string `form:"scope"`
State *string `form:"state"`
StripeLanding *string `form:"stripe_landing"`
StripeUser *OAuthStripeUserParams `form:"stripe_user"`
SuggestedCapabilities []*string `form:"suggested_capabilities"`
// Express is not sent as a parameter, but is used to modify the authorize URL
// path to use the express OAuth path.
Express *bool `form:"-"`
}
// DeauthorizeParams for deauthorizing an account.
type DeauthorizeParams struct {
Params `form:"*"`
ClientID *string `form:"client_id"`
StripeUserID *string `form:"stripe_user_id"`
}
// OAuthTokenParams is the set of paramaters that can be used to request
// OAuthTokens.
type OAuthTokenParams struct {
Params `form:"*"`
AssertCapabilities []*string `form:"assert_capabilities"`
ClientSecret *string `form:"client_secret"`
Code *string `form:"code"`
GrantType *string `form:"grant_type"`
RefreshToken *string `form:"refresh_token"`
Scope *string `form:"scope"`
}
// OAuthToken is the value of the OAuthToken from OAuth flow.
// https://stripe.com/docs/connect/oauth-reference#post-token
type OAuthToken struct {
Livemode bool `json:"livemode"`
Scope OAuthScopeType `json:"scope"`
StripeUserID string `json:"stripe_user_id"`
TokenType OAuthTokenType `json:"token_type"`
// Deprecated, please use StripeUserID
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
StripePublishableKey string `json:"stripe_publishable_key"`
}
// Deauthorize is the value of the return from deauthorizing.
// https://stripe.com/docs/connect/oauth-reference#post-deauthorize
type Deauthorize struct {
StripeUserID string `json:"stripe_user_id"`
}

272
vendor/github.com/stripe/stripe-go/order.go generated vendored Normal file
View file

@ -0,0 +1,272 @@
package stripe
import (
"encoding/json"
)
// OrderStatus represents the statuses of an order object.
type OrderStatus string
// List of values that OrderStatus can take.
const (
OrderStatusCanceled OrderStatus = "canceled"
OrderStatusCreated OrderStatus = "created"
OrderStatusFulfilled OrderStatus = "fulfilled"
OrderStatusPaid OrderStatus = "paid"
OrderStatusReturned OrderStatus = "returned"
)
// OrderDeliveryEstimateType represents the type of delivery estimate for shipping methods
type OrderDeliveryEstimateType string
// List of values that OrderDeliveryEstimateType can take.
const (
OrderDeliveryEstimateTypeExact OrderDeliveryEstimateType = "exact"
OrderDeliveryEstimateTypeRange OrderDeliveryEstimateType = "range"
)
// OrderItemType represents the type of order item
type OrderItemType string
// List of values that OrderItemType can take.
const (
OrderItemTypeCoupon OrderItemType = "coupon"
OrderItemTypeDiscount OrderItemType = "discount"
OrderItemTypeSKU OrderItemType = "sku"
OrderItemTypeShipping OrderItemType = "shipping"
OrderItemTypeTax OrderItemType = "tax"
)
// OrderItemParentType represents the type of order item parent
type OrderItemParentType string
// List of values that OrderItemParentType can take.
const (
OrderItemParentTypeCoupon OrderItemParentType = "coupon"
OrderItemParentTypeDiscount OrderItemParentType = "discount"
OrderItemParentTypeSKU OrderItemParentType = "sku"
OrderItemParentTypeShipping OrderItemParentType = "shipping"
OrderItemParentTypeTax OrderItemParentType = "tax"
)
// OrderItemParent describes the parent of an order item.
type OrderItemParent struct {
ID string `json:"id"`
SKU *SKU `json:"-"`
Type OrderItemParentType `json:"object"`
}
// OrderParams is the set of parameters that can be used when creating an order.
type OrderParams struct {
Params `form:"*"`
Coupon *string `form:"coupon"`
Currency *string `form:"currency"`
Customer *string `form:"customer"`
Email *string `form:"email"`
Items []*OrderItemParams `form:"items"`
Shipping *ShippingParams `form:"shipping"`
}
// ShippingParams is the set of parameters that can be used for the shipping hash
// on order creation.
type ShippingParams struct {
Address *AddressParams `form:"address"`
Name *string `form:"name"`
Phone *string `form:"phone"`
}
// OrderUpdateParams is the set of parameters that can be used when updating an order.
type OrderUpdateParams struct {
Params `form:"*"`
Coupon *string `form:"coupon"`
SelectedShippingMethod *string `form:"selected_shipping_method"`
Shipping *OrderUpdateShippingParams `form:"shipping"`
Status *string `form:"status"`
}
// OrderUpdateShippingParams is the set of parameters that can be used for the shipping
// hash on order update.
type OrderUpdateShippingParams struct {
Carrier *string `form:"carrier"`
TrackingNumber *string `form:"tracking_number"`
}
// Shipping describes the shipping hash on an order.
type Shipping struct {
Address *Address `json:"address"`
Carrier string `json:"carrier"`
Name string `json:"name"`
Phone string `json:"phone"`
TrackingNumber string `json:"tracking_number"`
}
// ShippingMethod describes a shipping method as available on an order.
type ShippingMethod struct {
Amount int64 `json:"amount"`
ID string `json:"id"`
Currency Currency `json:"currency"`
DeliveryEstimate *DeliveryEstimate `json:"delivery_estimate"`
Description string `json:"description"`
}
// DeliveryEstimate represent the properties available for a shipping method's
// estimated delivery.
type DeliveryEstimate struct {
// If Type == Exact
Date string `json:"date"`
// If Type == Range
Earliest string `json:"earliest"`
Latest string `json:"latest"`
Type OrderDeliveryEstimateType `json:"type"`
}
// Order is the resource representing a Stripe charge.
// For more details see https://stripe.com/docs/api#orders.
type Order struct {
Amount int64 `json:"amount"`
AmountReturned int64 `json:"amount_returned"`
Application string `json:"application"`
ApplicationFee int64 `json:"application_fee"`
Charge *Charge `json:"charge"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Customer Customer `json:"customer"`
Email string `json:"email"`
ID string `json:"id"`
Items []*OrderItem `json:"items"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Returns *OrderReturnList `json:"returns"`
SelectedShippingMethod *string `json:"selected_shipping_method"`
Shipping *Shipping `json:"shipping"`
ShippingMethods []*ShippingMethod `json:"shipping_methods"`
Status string `json:"status"`
StatusTransitions StatusTransitions `json:"status_transitions"`
Updated int64 `json:"updated"`
UpstreamID string `json:"upstream_id"`
}
// OrderList is a list of orders as retrieved from a list endpoint.
type OrderList struct {
ListMeta
Data []*Order `json:"data"`
}
// OrderListParams is the set of parameters that can be used when listing orders.
type OrderListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Customer *string `form:"customer"`
IDs []*string `form:"ids"`
Status *string `form:"status"`
StatusTransitions *StatusTransitionsFilterParams `form:"status_transitions"`
UpstreamIDs []*string `form:"upstream_ids"`
}
// StatusTransitionsFilterParams are parameters that can used to filter on status_transition when listing orders.
type StatusTransitionsFilterParams struct {
Canceled *int64 `form:"canceled"`
CanceledRange *RangeQueryParams `form:"canceled"`
Fulfilled *int64 `form:"fulfilled"`
FulfilledRange *RangeQueryParams `form:"fulfilled"`
Paid *int64 `form:"paid"`
PaidRange *RangeQueryParams `form:"paid"`
Returned *int64 `form:"returned"`
ReturnedRange *RangeQueryParams `form:"returned"`
}
// StatusTransitions are the timestamps at which the order status was updated.
type StatusTransitions struct {
Canceled int64 `json:"canceled"`
Fulfilled int64 `json:"fulfilled"`
Paid int64 `json:"paid"`
Returned int64 `json:"returned"`
}
// OrderPayParams is the set of parameters that can be used when paying orders.
type OrderPayParams struct {
Params `form:"*"`
ApplicationFee *int64 `form:"application_fee"`
Customer *string `form:"customer"`
Email *string `form:"email"`
Source *SourceParams `form:"*"` // SourceParams has custom encoding so brought to top level with "*"
}
// OrderItemParams is the set of parameters describing an order item on order creation or update.
type OrderItemParams struct {
Amount *int64 `form:"amount"`
Currency *string `form:"currency"`
Description *string `form:"description"`
Parent *string `form:"parent"`
Quantity *int64 `form:"quantity"`
Type *string `form:"type"`
}
// OrderItem is the resource representing an order item.
type OrderItem struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
Description string `json:"description"`
Parent *OrderItemParent `json:"parent"`
Quantity int64 `json:"quantity"`
Type OrderItemType `json:"type"`
}
// SetSource adds valid sources to a OrderParams object,
// returning an error for unsupported sources.
func (op *OrderPayParams) SetSource(sp interface{}) error {
source, err := SourceParamsFor(sp)
op.Source = source
return err
}
// UnmarshalJSON handles deserialization of an OrderItemParent.
// This custom unmarshaling is needed because the resulting
// property may be an id or a full SKU struct if it was expanded.
func (p *OrderItemParent) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
p.ID = id
return nil
}
type orderItemParent OrderItemParent
var v orderItemParent
if err := json.Unmarshal(data, &v); err != nil {
return err
}
var err error
*p = OrderItemParent(v)
switch p.Type {
case OrderItemParentTypeSKU:
// Currently only SKUs `parent` is returned as an object when expanded.
// For other items only IDs are returned.
if err = json.Unmarshal(data, &p.SKU); err != nil {
return err
}
p.ID = p.SKU.ID
}
return nil
}
// UnmarshalJSON handles deserialization of an Order.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (o *Order) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
o.ID = id
return nil
}
type order Order
var v order
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*o = Order(v)
return nil
}

56
vendor/github.com/stripe/stripe-go/orderreturn.go generated vendored Normal file
View file

@ -0,0 +1,56 @@
package stripe
import "encoding/json"
// OrderReturnParams is the set of parameters that can be used when returning orders.
type OrderReturnParams struct {
Params `form:"*"`
Items []*OrderItemParams `form:"items"`
Order *string `form:"-"` // Included in the URL
}
// OrderReturn is the resource representing an order return.
// For more details see https://stripe.com/docs/api#order_returns.
type OrderReturn struct {
Amount int64 `json:"amount"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
ID string `json:"id"`
Items []*OrderItem `json:"items"`
Livemode bool `json:"livemode"`
Order *Order `json:"order"`
Refund *Refund `json:"refund"`
}
// OrderReturnList is a list of order returns as retrieved from a list endpoint.
type OrderReturnList struct {
ListMeta
Data []*OrderReturn `json:"data"`
}
// OrderReturnListParams is the set of parameters that can be used when listing order returns.
type OrderReturnListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Order *string `form:"order"`
}
// UnmarshalJSON handles deserialization of an OrderReturn.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (r *OrderReturn) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
r.ID = id
return nil
}
type orderReturn OrderReturn
var v orderReturn
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*r = OrderReturn(v)
return nil
}

269
vendor/github.com/stripe/stripe-go/params.go generated vendored Normal file
View file

@ -0,0 +1,269 @@
package stripe
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"time"
"github.com/stripe/stripe-go/form"
)
//
// Public constants
//
// Contains constants for the names of parameters used for pagination in list APIs.
const (
EndingBefore = "ending_before"
StartingAfter = "starting_after"
)
//
// Public types
//
// ExtraValues are extra parameters that are attached to an API request.
// They're implemented as a custom type so that they can have their own
// AppendTo implementation.
type ExtraValues struct {
url.Values `form:"-"` // See custom AppendTo implementation
}
// AppendTo implements custom form encoding for extra parameter values.
func (v ExtraValues) AppendTo(body *form.Values, keyParts []string) {
for k, vs := range v.Values {
for _, v := range vs {
body.Add(form.FormatKey(append(keyParts, k)), v)
}
}
}
// Filters is a structure that contains a collection of filters for list-related APIs.
type Filters struct {
f []*filter `form:"-"` // See custom AppendTo implementation
}
// AddFilter adds a new filter with a given key, op and value.
func (f *Filters) AddFilter(key, op, value string) {
filter := &filter{Key: key, Op: op, Val: value}
f.f = append(f.f, filter)
}
// AppendTo implements custom form encoding for filters.
func (f Filters) AppendTo(body *form.Values, keyParts []string) {
if len(f.f) > 0 {
for _, v := range f.f {
if len(v.Op) > 0 {
body.Add(form.FormatKey(append(keyParts, v.Key, v.Op)), v.Val)
} else {
body.Add(form.FormatKey(append(keyParts, v.Key)), v.Val)
}
}
}
}
// ListMeta is the structure that contains the common properties
// of List iterators. The Count property is only populated if the
// total_count include option is passed in (see tests for example).
type ListMeta struct {
HasMore bool `json:"has_more"`
TotalCount uint32 `json:"total_count"`
URL string `json:"url"`
}
// ListParams is the structure that contains the common properties
// of any *ListParams structure.
type ListParams struct {
// Context used for request. It may carry deadlines, cancelation signals,
// and other request-scoped values across API boundaries and between
// processes.
//
// Note that a cancelled or timed out context does not provide any
// guarantee whether the operation was or was not completed on Stripe's API
// servers. For certainty, you must either retry with the same idempotency
// key or query the state of the API.
Context context.Context `form:"-"`
EndingBefore *string `form:"ending_before"`
Expand []*string `form:"expand"`
Filters Filters `form:"*"`
Limit *int64 `form:"limit"`
// Single specifies whether this is a single page iterator. By default,
// listing through an iterator will automatically grab additional pages as
// the query progresses. To change this behavior and just load a single
// page, set this to true.
Single bool `form:"-"` // Not an API parameter
StartingAfter *string `form:"starting_after"`
// StripeAccount may contain the ID of a connected account. By including
// this field, the request is made as if it originated from the connected
// account instead of under the account of the owner of the configured
// Stripe key.
StripeAccount *string `form:"-"` // Passed as header
}
// AddExpand appends a new field to expand.
func (p *ListParams) AddExpand(f string) {
p.Expand = append(p.Expand, &f)
}
// GetListParams returns a ListParams struct (itself). It exists because any
// structs that embed ListParams will inherit it, and thus implement the
// ListParamsContainer interface.
func (p *ListParams) GetListParams() *ListParams {
return p
}
// GetParams returns ListParams as a Params struct. It exists because any
// structs that embed Params will inherit it, and thus implement the
// ParamsContainer interface.
func (p *ListParams) GetParams() *Params {
return p.ToParams()
}
// SetStripeAccount sets a value for the Stripe-Account header.
func (p *ListParams) SetStripeAccount(val string) {
p.StripeAccount = &val
}
// ToParams converts a ListParams to a Params by moving over any fields that
// have valid targets in the new type. This is useful because fields in
// Params can be injected directly into an http.Request while generally
// ListParams is only used to build a set of parameters.
func (p *ListParams) ToParams() *Params {
return &Params{
Context: p.Context,
StripeAccount: p.StripeAccount,
}
}
// ListParamsContainer is a general interface for which all list parameter
// structs should comply. They achieve this by embedding a ListParams struct
// and inheriting its implementation of this interface.
type ListParamsContainer interface {
GetListParams() *ListParams
}
// Params is the structure that contains the common properties
// of any *Params structure.
type Params struct {
// Context used for request. It may carry deadlines, cancelation signals,
// and other request-scoped values across API boundaries and between
// processes.
//
// Note that a cancelled or timed out context does not provide any
// guarantee whether the operation was or was not completed on Stripe's API
// servers. For certainty, you must either retry with the same idempotency
// key or query the state of the API.
Context context.Context `form:"-"`
Expand []*string `form:"expand"`
Extra *ExtraValues `form:"*"`
// Headers may be used to provide extra header lines on the HTTP request.
Headers http.Header `form:"-"`
IdempotencyKey *string `form:"-"` // Passed as header
Metadata map[string]string `form:"metadata"`
// StripeAccount may contain the ID of a connected account. By including
// this field, the request is made as if it originated from the connected
// account instead of under the account of the owner of the configured
// Stripe key.
StripeAccount *string `form:"-"` // Passed as header
}
// AddExpand appends a new field to expand.
func (p *Params) AddExpand(f string) {
p.Expand = append(p.Expand, &f)
}
// AddExtra adds a new arbitrary key-value pair to the request data
func (p *Params) AddExtra(key, value string) {
if p.Extra == nil {
p.Extra = &ExtraValues{Values: make(url.Values)}
}
p.Extra.Add(key, value)
}
// AddMetadata adds a new key-value pair to the Metadata.
func (p *Params) AddMetadata(key, value string) {
if p.Metadata == nil {
p.Metadata = make(map[string]string)
}
p.Metadata[key] = value
}
// GetParams returns a Params struct (itself). It exists because any structs
// that embed Params will inherit it, and thus implement the ParamsContainer
// interface.
func (p *Params) GetParams() *Params {
return p
}
// SetIdempotencyKey sets a value for the Idempotency-Key header.
func (p *Params) SetIdempotencyKey(val string) {
p.IdempotencyKey = &val
}
// SetStripeAccount sets a value for the Stripe-Account header.
func (p *Params) SetStripeAccount(val string) {
p.StripeAccount = &val
}
// ParamsContainer is a general interface for which all parameter structs
// should comply. They achieve this by embedding a Params struct and inheriting
// its implementation of this interface.
type ParamsContainer interface {
GetParams() *Params
}
// RangeQueryParams are a set of generic request parameters that are used on
// list endpoints to filter their results by some timestamp.
type RangeQueryParams struct {
// GreaterThan specifies that values should be a greater than this
// timestamp.
GreaterThan int64 `form:"gt"`
// GreaterThanOrEqual specifies that values should be greater than or equal
// to this timestamp.
GreaterThanOrEqual int64 `form:"gte"`
// LesserThan specifies that values should be lesser than this timetamp.
LesserThan int64 `form:"lt"`
// LesserThanOrEqual specifies that values should be lesser than or
// equalthis timetamp.
LesserThanOrEqual int64 `form:"lte"`
}
//
// Public functions
//
// NewIdempotencyKey generates a new idempotency key that
// can be used on a request.
func NewIdempotencyKey() string {
now := time.Now().UnixNano()
buf := make([]byte, 4)
rand.Read(buf)
return fmt.Sprintf("%v_%v", now, base64.URLEncoding.EncodeToString(buf)[:6])
}
//
// Private types
//
// filter is the structure that contains a filter for list-related APIs.
// It ends up passing query string parameters in the format key[op]=value.
type filter struct {
Key, Op, Val string
}

355
vendor/github.com/stripe/stripe-go/paymentintent.go generated vendored Normal file
View file

@ -0,0 +1,355 @@
package stripe
import (
"encoding/json"
)
// PaymentIntentCancellationReason is the list of allowed values for the cancelation reason.
type PaymentIntentCancellationReason string
// List of values that PaymentIntentCancellationReason can take.
const (
PaymentIntentCancellationReasonAbandoned PaymentIntentCancellationReason = "abandoned"
PaymentIntentCancellationReasonAutomatic PaymentIntentCancellationReason = "automatic"
PaymentIntentCancellationReasonDuplicate PaymentIntentCancellationReason = "duplicate"
PaymentIntentCancellationReasonFailedInvoice PaymentIntentCancellationReason = "failed_invoice"
PaymentIntentCancellationReasonFraudulent PaymentIntentCancellationReason = "fraudulent"
PaymentIntentCancellationReasonRequestedByCustomer PaymentIntentCancellationReason = "requested_by_customer"
PaymentIntentCancellationReasonVoidInvoice PaymentIntentCancellationReason = "void_invoice"
)
// PaymentIntentCaptureMethod is the list of allowed values for the capture method.
type PaymentIntentCaptureMethod string
// List of values that PaymentIntentCaptureMethod can take.
const (
PaymentIntentCaptureMethodAutomatic PaymentIntentCaptureMethod = "automatic"
PaymentIntentCaptureMethodManual PaymentIntentCaptureMethod = "manual"
)
// PaymentIntentConfirmationMethod is the list of allowed values for the confirmation method.
type PaymentIntentConfirmationMethod string
// List of values that PaymentIntentConfirmationMethod can take.
const (
PaymentIntentConfirmationMethodAutomatic PaymentIntentConfirmationMethod = "automatic"
PaymentIntentConfirmationMethodManual PaymentIntentConfirmationMethod = "manual"
)
// PaymentIntentNextActionType is the list of allowed values for the next action's type.
type PaymentIntentNextActionType string
// List of values that PaymentIntentNextActionType can take.
const (
PaymentIntentNextActionTypeRedirectToURL PaymentIntentNextActionType = "redirect_to_url"
)
// PaymentIntentOffSession is the list of allowed values for types of off-session.
type PaymentIntentOffSession string
// List of values that PaymentIntentOffSession can take.
const (
PaymentIntentOffSessionOneOff PaymentIntentOffSession = "one_off"
PaymentIntentOffSessionRecurring PaymentIntentOffSession = "recurring"
)
// PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval is the interval of a card installment plan.
type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval string
// List of values that PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval can take.
const (
PaymentIntentPaymentMethodOptionsCardInstallmentsPlanIntervalMonth PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval = "month"
)
// PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType is the type of a card installment plan.
type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType string
// List of values that PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType can take.
const (
PaymentIntentPaymentMethodOptionsCardInstallmentsPlanTypeFixedCount PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType = "fixed_count"
)
// PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure is the list of allowed values
//controlling when to request 3D Secure on a PaymentIntent.
type PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure string
// List of values that PaymentIntentNextActionType can take.
const (
PaymentIntentPaymentMethodOptionsCardRequestThreeDSecureAny PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure = "any"
PaymentIntentPaymentMethodOptionsCardRequestThreeDSecureAutomatic PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure = "automatic"
)
// PaymentIntentSetupFutureUsage is the list of allowed values for SetupFutureUsage.
type PaymentIntentSetupFutureUsage string
// List of values that PaymentIntentSetupFutureUsage can take.
const (
PaymentIntentSetupFutureUsageOffSession PaymentIntentSetupFutureUsage = "off_session"
PaymentIntentSetupFutureUsageOnSession PaymentIntentSetupFutureUsage = "on_session"
)
// PaymentIntentStatus is the list of allowed values for the payment intent's status.
type PaymentIntentStatus string
// List of values that PaymentIntentStatus can take.
const (
PaymentIntentStatusCanceled PaymentIntentStatus = "canceled"
PaymentIntentStatusProcessing PaymentIntentStatus = "processing"
PaymentIntentStatusRequiresAction PaymentIntentStatus = "requires_action"
PaymentIntentStatusRequiresCapture PaymentIntentStatus = "requires_capture"
PaymentIntentStatusRequiresConfirmation PaymentIntentStatus = "requires_confirmation"
PaymentIntentStatusRequiresPaymentMethod PaymentIntentStatus = "requires_payment_method"
PaymentIntentStatusSucceeded PaymentIntentStatus = "succeeded"
)
// PaymentIntentCancelParams is the set of parameters that can be used when canceling a payment intent.
type PaymentIntentCancelParams struct {
Params `form:"*"`
CancellationReason *string `form:"cancellation_reason"`
}
// PaymentIntentCaptureParams is the set of parameters that can be used when capturing a payment intent.
type PaymentIntentCaptureParams struct {
Params `form:"*"`
AmountToCapture *int64 `form:"amount_to_capture"`
ApplicationFeeAmount *int64 `form:"application_fee_amount"`
StatementDescriptor *string `form:"statement_descriptor"`
StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"`
TransferData *PaymentIntentTransferDataParams `form:"transfer_data"`
}
// PaymentIntentConfirmParams is the set of parameters that can be used when confirming a payment intent.
type PaymentIntentConfirmParams struct {
Params `form:"*"`
ErrorOnRequiresAction *bool `form:"error_on_requires_action"`
Mandate *string `form:"mandate"`
MandateData *PaymentIntentMandateDataParams `form:"mandate_data"`
OffSession *bool `form:"off_session"`
PaymentMethod *string `form:"payment_method"`
PaymentMethodOptions *PaymentIntentPaymentMethodOptionsParams `form:"payment_method_options"`
PaymentMethodTypes []*string `form:"payment_method_types"`
ReceiptEmail *string `form:"receipt_email"`
ReturnURL *string `form:"return_url"`
SavePaymentMethod *bool `form:"save_payment_method"`
SetupFutureUsage *string `form:"setup_future_usage"`
Shipping *ShippingDetailsParams `form:"shipping"`
Source *string `form:"source"`
UseStripeSDK *bool `form:"use_stripe_sdk"`
}
// PaymentIntentMandateDataCustomerAcceptanceOfflineParams is the set of parameters for the customer
// acceptance of an offline mandate.
type PaymentIntentMandateDataCustomerAcceptanceOfflineParams struct {
}
// PaymentIntentMandateDataCustomerAcceptanceOnlineParams is the set of parameters for the customer
// acceptance of an online mandate.
type PaymentIntentMandateDataCustomerAcceptanceOnlineParams struct {
IPAddress *string `form:"ip_address"`
UserAgent *string `form:"user_agent"`
}
// PaymentIntentMandateDataCustomerAcceptanceParams is the set of parameters for the customer
// acceptance of a mandate.
type PaymentIntentMandateDataCustomerAcceptanceParams struct {
AcceptedAt int64 `form:"accepted_at"`
Offline *PaymentIntentMandateDataCustomerAcceptanceOfflineParams `form:"offline"`
Online *PaymentIntentMandateDataCustomerAcceptanceOnlineParams `form:"online"`
Type MandateCustomerAcceptanceType `form:"type"`
}
// PaymentIntentMandateDataParams is the set of parameters controlling the creation of the mandate
// associated with this PaymentIntent.
type PaymentIntentMandateDataParams struct {
CustomerAcceptance *PaymentIntentMandateDataCustomerAcceptanceParams `form:"customer_acceptance"`
}
// PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams represents details about the
// installment plan chosen for this payment intent.
type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams struct {
Count *int64 `form:"count"`
Interval *string `form:"interval"`
Type *string `form:"type"`
}
// PaymentIntentPaymentMethodOptionsCardInstallmentsParams controls whether to enable installment
// plans for this payment intent.
type PaymentIntentPaymentMethodOptionsCardInstallmentsParams struct {
Enabled *bool `form:"enabled"`
Plan *PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams `form:"plan"`
}
// PaymentIntentPaymentMethodOptionsCardParams represents the card-specific options applied to a
// PaymentIntent.
type PaymentIntentPaymentMethodOptionsCardParams struct {
Installments *PaymentIntentPaymentMethodOptionsCardInstallmentsParams `form:"installments"`
MOTO *bool `form:"moto"`
RequestThreeDSecure *string `form:"request_three_d_secure"`
}
// PaymentIntentPaymentMethodOptionsParams represents the type-specific payment method options
// applied to a PaymentIntent.
type PaymentIntentPaymentMethodOptionsParams struct {
Card *PaymentIntentPaymentMethodOptionsCardParams `form:"card"`
}
// PaymentIntentTransferDataParams is the set of parameters allowed for the transfer hash.
type PaymentIntentTransferDataParams struct {
Amount *int64 `form:"amount"`
Destination *string `form:"destination"`
}
// PaymentIntentParams is the set of parameters that can be used when handling a payment intent.
type PaymentIntentParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
ApplicationFeeAmount *int64 `form:"application_fee_amount"`
CaptureMethod *string `form:"capture_method"`
Confirm *bool `form:"confirm"`
ConfirmationMethod *string `form:"confirmation_method"`
Currency *string `form:"currency"`
Customer *string `form:"customer"`
Description *string `form:"description"`
Mandate *string `form:"mandate"`
MandateData *PaymentIntentMandateDataParams `form:"mandate_data"`
OnBehalfOf *string `form:"on_behalf_of"`
PaymentMethod *string `form:"payment_method"`
PaymentMethodOptions *PaymentIntentPaymentMethodOptionsParams `form:"payment_method_options"`
PaymentMethodTypes []*string `form:"payment_method_types"`
ReceiptEmail *string `form:"receipt_email"`
ReturnURL *string `form:"return_url"`
SavePaymentMethod *bool `form:"save_payment_method"`
SetupFutureUsage *string `form:"setup_future_usage"`
Shipping *ShippingDetailsParams `form:"shipping"`
Source *string `form:"source"`
StatementDescriptor *string `form:"statement_descriptor"`
StatementDescriptorSuffix *string `form:"statement_descriptor_suffix"`
TransferData *PaymentIntentTransferDataParams `form:"transfer_data"`
TransferGroup *string `form:"transfer_group"`
// Those parameters only works if you confirm on creation.
ErrorOnRequiresAction *bool `form:"error_on_requires_action"`
OffSession *bool `form:"off_session"`
UseStripeSDK *bool `form:"use_stripe_sdk"`
}
// PaymentIntentListParams is the set of parameters that can be used when listing payment intents.
// For more details see https://stripe.com/docs/api#list_payouts.
type PaymentIntentListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Customer *string `form:"customer"`
}
// PaymentIntentNextActionRedirectToURL represents the resource for the next action of type
// "redirect_to_url".
type PaymentIntentNextActionRedirectToURL struct {
ReturnURL string `json:"return_url"`
URL string `json:"url"`
}
// PaymentIntentNextAction represents the type of action to take on a payment intent.
type PaymentIntentNextAction struct {
RedirectToURL *PaymentIntentNextActionRedirectToURL `json:"redirect_to_url"`
Type PaymentIntentNextActionType `json:"type"`
}
// PaymentIntentPaymentMethodOptionsCardInstallmentsPlan describe a specific card installment plan.
type PaymentIntentPaymentMethodOptionsCardInstallmentsPlan struct {
Count int64 `json:"count"`
Interval PaymentIntentPaymentMethodOptionsCardInstallmentsPlanInterval `json:"interval"`
Type PaymentIntentPaymentMethodOptionsCardInstallmentsPlanType `json:"type"`
}
// PaymentIntentPaymentMethodOptionsCardInstallments describe the installment options available for
// a card associated with that payment intent.
type PaymentIntentPaymentMethodOptionsCardInstallments struct {
AvailablePlans []*PaymentIntentPaymentMethodOptionsCardInstallmentsPlan `json:"available_plans"`
Enabled bool `json:"enabled"`
Plan *PaymentIntentPaymentMethodOptionsCardInstallmentsPlan `json:"plan"`
}
// PaymentIntentPaymentMethodOptionsCard is the set of card-specific options associated with that
// payment intent.
type PaymentIntentPaymentMethodOptionsCard struct {
Installments *PaymentIntentPaymentMethodOptionsCardInstallments `json:"installments"`
RequestThreeDSecure PaymentIntentPaymentMethodOptionsCardRequestThreeDSecure `json:"request_three_d_secure"`
}
// PaymentIntentPaymentMethodOptions is the set of payment method-specific options associated with
// that payment intent.
type PaymentIntentPaymentMethodOptions struct {
Card *PaymentIntentPaymentMethodOptionsCard `json:"card"`
}
// PaymentIntentTransferData represents the information for the transfer associated with a payment intent.
type PaymentIntentTransferData struct {
Amount int64 `json:"amount"`
Destination *Account `json:"destination"`
}
// PaymentIntent is the resource representing a Stripe payout.
// For more details see https://stripe.com/docs/api#payment_intents.
type PaymentIntent struct {
Amount int64 `json:"amount"`
AmountCapturable int64 `json:"amount_capturable"`
AmountReceived int64 `json:"amount_received"`
Application *Application `json:"application"`
ApplicationFeeAmount int64 `json:"application_fee_amount"`
CanceledAt int64 `json:"canceled_at"`
CancellationReason PaymentIntentCancellationReason `json:"cancellation_reason"`
CaptureMethod PaymentIntentCaptureMethod `json:"capture_method"`
Charges *ChargeList `json:"charges"`
ClientSecret string `json:"client_secret"`
ConfirmationMethod PaymentIntentConfirmationMethod `json:"confirmation_method"`
Created int64 `json:"created"`
Currency string `json:"currency"`
Customer *Customer `json:"customer"`
Description string `json:"description"`
Invoice *Invoice `json:"invoice"`
LastPaymentError *Error `json:"last_payment_error"`
Livemode bool `json:"livemode"`
ID string `json:"id"`
Metadata map[string]string `json:"metadata"`
NextAction *PaymentIntentNextAction `json:"next_action"`
OnBehalfOf *Account `json:"on_behalf_of"`
PaymentMethod *PaymentMethod `json:"payment_method"`
PaymentMethodOptions *PaymentIntentPaymentMethodOptions `json:"payment_method_options"`
PaymentMethodTypes []string `json:"payment_method_types"`
ReceiptEmail string `json:"receipt_email"`
Review *Review `json:"review"`
SetupFutureUsage PaymentIntentSetupFutureUsage `json:"setup_future_usage"`
Shipping ShippingDetails `json:"shipping"`
Source *PaymentSource `json:"source"`
StatementDescriptor string `json:"statement_descriptor"`
StatementDescriptorSuffix string `json:"statement_descriptor_suffix"`
Status PaymentIntentStatus `json:"status"`
TransferData *PaymentIntentTransferData `json:"transfer_data"`
TransferGroup string `json:"transfer_group"`
}
// PaymentIntentList is a list of payment intents as retrieved from a list endpoint.
type PaymentIntentList struct {
ListMeta
Data []*PaymentIntent `json:"data"`
}
// UnmarshalJSON handles deserialization of a Payment Intent.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (p *PaymentIntent) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
p.ID = id
return nil
}
type paymentintent PaymentIntent
var v paymentintent
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*p = PaymentIntent(v)
return nil
}

View file

@ -0,0 +1,128 @@
// Package paymentintent provides API functions related to payment intents.
//
// For more details, see: https://stripe.com/docs/api/go#payment_intents.
package paymentintent
import (
"net/http"
stripe "github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/form"
)
// Client is used to invoke APIs related to payment intents.
type Client struct {
B stripe.Backend
Key string
}
// New creates a payment intent.
func New(params *stripe.PaymentIntentParams) (*stripe.PaymentIntent, error) {
return getC().New(params)
}
// New creates a payment intent.
func (c Client) New(params *stripe.PaymentIntentParams) (*stripe.PaymentIntent, error) {
intent := &stripe.PaymentIntent{}
err := c.B.Call(http.MethodPost, "/v1/payment_intents", c.Key, params, intent)
return intent, err
}
// Get retrieves a payment intent.
func Get(id string, params *stripe.PaymentIntentParams) (*stripe.PaymentIntent, error) {
return getC().Get(id, params)
}
// Get retrieves a payment intent.
func (c Client) Get(id string, params *stripe.PaymentIntentParams) (*stripe.PaymentIntent, error) {
path := stripe.FormatURLPath("/v1/payment_intents/%s", id)
intent := &stripe.PaymentIntent{}
err := c.B.Call(http.MethodGet, path, c.Key, params, intent)
return intent, err
}
// Update updates a payment intent.
func Update(id string, params *stripe.PaymentIntentParams) (*stripe.PaymentIntent, error) {
return getC().Update(id, params)
}
// Update updates a payment intent.
func (c Client) Update(id string, params *stripe.PaymentIntentParams) (*stripe.PaymentIntent, error) {
path := stripe.FormatURLPath("/v1/payment_intents/%s", id)
intent := &stripe.PaymentIntent{}
err := c.B.Call(http.MethodPost, path, c.Key, params, intent)
return intent, err
}
// Cancel cancels a payment intent.
func Cancel(id string, params *stripe.PaymentIntentCancelParams) (*stripe.PaymentIntent, error) {
return getC().Cancel(id, params)
}
// Cancel cancels a payment intent.
func (c Client) Cancel(id string, params *stripe.PaymentIntentCancelParams) (*stripe.PaymentIntent, error) {
path := stripe.FormatURLPath("/v1/payment_intents/%s/cancel", id)
intent := &stripe.PaymentIntent{}
err := c.B.Call(http.MethodPost, path, c.Key, params, intent)
return intent, err
}
// Capture captures a payment intent.
func Capture(id string, params *stripe.PaymentIntentCaptureParams) (*stripe.PaymentIntent, error) {
return getC().Capture(id, params)
}
// Capture captures a payment intent.
func (c Client) Capture(id string, params *stripe.PaymentIntentCaptureParams) (*stripe.PaymentIntent, error) {
path := stripe.FormatURLPath("/v1/payment_intents/%s/capture", id)
intent := &stripe.PaymentIntent{}
err := c.B.Call(http.MethodPost, path, c.Key, params, intent)
return intent, err
}
// Confirm confirms a payment intent.
func Confirm(id string, params *stripe.PaymentIntentConfirmParams) (*stripe.PaymentIntent, error) {
return getC().Confirm(id, params)
}
// Confirm confirms a payment intent.
func (c Client) Confirm(id string, params *stripe.PaymentIntentConfirmParams) (*stripe.PaymentIntent, error) {
path := stripe.FormatURLPath("/v1/payment_intents/%s/confirm", id)
intent := &stripe.PaymentIntent{}
err := c.B.Call(http.MethodPost, path, c.Key, params, intent)
return intent, err
}
// List returns a list of payment intents.
func List(params *stripe.PaymentIntentListParams) *Iter {
return getC().List(params)
}
// List returns a list of payment intents.
func (c Client) List(listParams *stripe.PaymentIntentListParams) *Iter {
return &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListMeta, error) {
list := &stripe.PaymentIntentList{}
err := c.B.CallRaw(http.MethodGet, "/v1/payment_intents", c.Key, b, p, list)
ret := make([]interface{}, len(list.Data))
for i, v := range list.Data {
ret[i] = v
}
return ret, list.ListMeta, err
})}
}
// Iter is an iterator for payment intents.
type Iter struct {
*stripe.Iter
}
// PaymentIntent returns the payment intent which the iterator is currently pointing to.
func (i *Iter) PaymentIntent() *stripe.PaymentIntent {
return i.Current().(*stripe.PaymentIntent)
}
func getC() Client {
return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}

276
vendor/github.com/stripe/stripe-go/paymentmethod.go generated vendored Normal file
View file

@ -0,0 +1,276 @@
package stripe
import "encoding/json"
// PaymentMethodFPXAccountHolderType is a list of string values that FPX AccountHolderType accepts.
type PaymentMethodFPXAccountHolderType string
// List of values that PaymentMethodFPXAccountHolderType can take
const (
PaymentMethodFPXAccountHolderTypeIndividual PaymentMethodFPXAccountHolderType = "individual"
PaymentMethodFPXAccountHolderTypeCompany PaymentMethodFPXAccountHolderType = "company"
)
// PaymentMethodType is the list of allowed values for the payment method type.
type PaymentMethodType string
// List of values that PaymentMethodType can take.
const (
PaymentMethodTypeAUBECSDebit PaymentMethodType = "au_becs_debit"
PaymentMethodTypeCard PaymentMethodType = "card"
PaymentMethodTypeCardPresent PaymentMethodType = "card_present"
PaymentMethodTypeFPX PaymentMethodType = "fpx"
PaymentMethodTypeIdeal PaymentMethodType = "ideal"
PaymentMethodTypeSepaDebit PaymentMethodType = "sepa_debit"
)
// PaymentMethodCardBrand is the list of allowed values for the brand property on a
// Card PaymentMethod.
type PaymentMethodCardBrand string
// List of values that PaymentMethodCardBrand can take.
const (
PaymentMethodCardBrandAmex PaymentMethodCardBrand = "amex"
PaymentMethodCardBrandDiners PaymentMethodCardBrand = "diners"
PaymentMethodCardBrandDiscover PaymentMethodCardBrand = "discover"
PaymentMethodCardBrandJCB PaymentMethodCardBrand = "jcb"
PaymentMethodCardBrandMastercard PaymentMethodCardBrand = "mastercard"
PaymentMethodCardBrandUnionpay PaymentMethodCardBrand = "unionpay"
PaymentMethodCardBrandUnknown PaymentMethodCardBrand = "unknown"
PaymentMethodCardBrandVisa PaymentMethodCardBrand = "visa"
)
// PaymentMethodCardNetwork is the list of allowed values to represent the network
// used for a card-like transaction.
type PaymentMethodCardNetwork string
// List of values that PaymentMethodCardNetwork can take.
const (
PaymentMethodCardNetworkAmex PaymentMethodCardNetwork = "amex"
PaymentMethodCardNetworkDiners PaymentMethodCardNetwork = "diners"
PaymentMethodCardNetworkDiscover PaymentMethodCardNetwork = "discover"
PaymentMethodCardNetworkInterac PaymentMethodCardNetwork = "interac"
PaymentMethodCardNetworkJCB PaymentMethodCardNetwork = "jcb"
PaymentMethodCardNetworkMastercard PaymentMethodCardNetwork = "mastercard"
PaymentMethodCardNetworkUnionpay PaymentMethodCardNetwork = "unionpay"
PaymentMethodCardNetworkUnknown PaymentMethodCardNetwork = "unknown"
PaymentMethodCardNetworkVisa PaymentMethodCardNetwork = "visa"
)
// PaymentMethodCardWalletType is the list of allowed values for the type a wallet can take on
// a Card PaymentMethod.
type PaymentMethodCardWalletType string
// List of values that PaymentMethodCardWalletType can take.
const (
PaymentMethodCardWalletTypeAmexExpressCheckout PaymentMethodCardWalletType = "amex_express_checkout"
PaymentMethodCardWalletTypeApplePay PaymentMethodCardWalletType = "apple_pay"
PaymentMethodCardWalletTypeGooglePay PaymentMethodCardWalletType = "google_pay"
PaymentMethodCardWalletTypeMasterpass PaymentMethodCardWalletType = "masterpass"
PaymentMethodCardWalletTypeSamsungPay PaymentMethodCardWalletType = "samsung_pay"
PaymentMethodCardWalletTypeVisaCheckout PaymentMethodCardWalletType = "visa_checkout"
)
// BillingDetailsParams is the set of parameters that can be used as billing details
// when creating or updating a PaymentMethod
type BillingDetailsParams struct {
Address *AddressParams `form:"address"`
Email *string `form:"email"`
Name *string `form:"name"`
Phone *string `form:"phone"`
}
// PaymentMethodAUBECSDebitParams is the set of parameters allowed for the `AUBECSDebit` hash when creating a
// PaymentMethod of type AUBECSDebit.
type PaymentMethodAUBECSDebitParams struct {
AccountNumber *string `form:"account_number"`
BSBNumber *string `form:"bsb_number"`
}
// PaymentMethodCardParams is the set of parameters allowed for the `card` hash when creating a
// PaymentMethod of type card.
type PaymentMethodCardParams struct {
CVC *string `form:"cvc"`
ExpMonth *string `form:"exp_month"`
ExpYear *string `form:"exp_year"`
Number *string `form:"number"`
Token *string `form:"token"`
}
// PaymentMethodFPXParams is the set of parameters allowed for the `fpx` hash when creating a
// PaymentMethod of type fpx.
type PaymentMethodFPXParams struct {
AccountHolderType *string `form:"account_holder_type"`
Bank *string `form:"bank"`
}
// PaymentMethodIdealParams is the set of parameters allowed for the `ideal` hash when creating a
// PaymentMethod of type ideal.
type PaymentMethodIdealParams struct {
Bank *string `form:"bank"`
}
// PaymentMethodSepaDebitParams is the set of parameters allowed for the `sepa_debit` hash when
// creating a PaymentMethod of type sepa_debit.
type PaymentMethodSepaDebitParams struct {
Iban *string `form:"iban"`
}
// PaymentMethodParams is the set of parameters that can be used when creating or updating a
// PaymentMethod.
type PaymentMethodParams struct {
Params `form:"*"`
AUBECSDebit *PaymentMethodAUBECSDebitParams `form:"au_becs_debit"`
BillingDetails *BillingDetailsParams `form:"billing_details"`
Card *PaymentMethodCardParams `form:"card"`
FPX *PaymentMethodFPXParams `form:"fpx"`
SepaDebit *PaymentMethodSepaDebitParams `form:"sepa_debit"`
Type *string `form:"type"`
// The following parameters are used when cloning a PaymentMethod to the connected account
Customer *string `form:"customer"`
PaymentMethod *string `form:"payment_method"`
}
// PaymentMethodAttachParams is the set of parameters that can be used when attaching a
// PaymentMethod to a Customer.
type PaymentMethodAttachParams struct {
Params `form:"*"`
Customer *string `form:"customer"`
}
// PaymentMethodDetachParams is the set of parameters that can be used when detaching a
// PaymentMethod.
type PaymentMethodDetachParams struct {
Params `form:"*"`
}
// PaymentMethodListParams is the set of parameters that can be used when listing PaymentMethods.
type PaymentMethodListParams struct {
ListParams `form:"*"`
Customer *string `form:"customer"`
Type *string `form:"type"`
}
// BillingDetails represents the billing details associated with a PaymentMethod.
type BillingDetails struct {
Address *Address `json:"address"`
Email string `json:"email"`
Name string `json:"name"`
Phone string `json:"phone"`
}
// PaymentMethodAUBECSDebit represents AUBECSDebit-specific properties (Australia Only).
type PaymentMethodAUBECSDebit struct {
BSBNumber string `json:"bsb_number"`
Fingerprint string `json:"fingerprint"`
Last4 string `json:"last4"`
}
// PaymentMethodCardChecks represents the checks associated with a Card PaymentMethod.
type PaymentMethodCardChecks struct {
AddressLine1Check CardVerification `json:"address_line1_check"`
AddressPostalCodeCheck CardVerification `json:"address_postal_code_check"`
CVCCheck CardVerification `json:"cvc_check"`
}
// PaymentMethodCardThreeDSecureUsage represents the 3DS usage for that Card PaymentMethod.
type PaymentMethodCardThreeDSecureUsage struct {
Supported bool `json:"supported"`
}
// PaymentMethodCardWallet represents the details of the card wallet if this Card PaymentMethod
// is part of a card wallet.
type PaymentMethodCardWallet struct {
DynamicLast4 string `json:"dynamic_last4"`
Type PaymentMethodCardWalletType `json:"type"`
}
// PaymentMethodCard represents the card-specific properties.
type PaymentMethodCard struct {
Brand PaymentMethodCardBrand `json:"brand"`
Checks *PaymentMethodCardChecks `json:"checks"`
Country string `json:"country"`
ExpMonth uint64 `json:"exp_month"`
ExpYear uint64 `json:"exp_year"`
Fingerprint string `json:"fingerprint"`
Funding CardFunding `json:"funding"`
Last4 string `json:"last4"`
ThreeDSecureUsage *PaymentMethodCardThreeDSecureUsage `json:"three_d_secure_usage"`
Wallet *PaymentMethodCardWallet `json:"wallet"`
// Please note that the fields below are for internal use only and are not returned
// as part of standard API requests.
Description string `json:"description"`
IIN string `json:"iin"`
Issuer string `json:"issuer"`
}
// PaymentMethodCardPresent represents the card-present-specific properties.
type PaymentMethodCardPresent struct {
}
// PaymentMethodFPX represents FPX-specific properties (Malaysia Only).
type PaymentMethodFPX struct {
AccountHolderType PaymentMethodFPXAccountHolderType `json:"account_holder_type"`
Bank string `json:"bank"`
TransactionID string `json:"transaction_id"`
}
// PaymentMethodIdeal represents the iDEAL-specific properties.
type PaymentMethodIdeal struct {
Bank string `json:"bank"`
Bic string `json:"bic"`
}
// PaymentMethodSepaDebit represents the SEPA-debit-specific properties.
type PaymentMethodSepaDebit struct {
BankCode string `json:"bank_code"`
BranchCode string `json:"branch_code"`
Country string `json:"country"`
Fingerprint string `json:"fingerprint"`
Last4 string `json:"last4"`
}
// PaymentMethod is the resource representing a PaymentMethod.
type PaymentMethod struct {
AUBECSDebit *PaymentMethodAUBECSDebit `json:"au_becs_debit"`
BillingDetails *BillingDetails `json:"billing_details"`
Card *PaymentMethodCard `json:"card"`
CardPresent *PaymentMethodCardPresent `json:"card_present"`
Created int64 `json:"created"`
Customer *Customer `json:"customer"`
FPX *PaymentMethodFPX `json:"fpx"`
ID string `json:"id"`
Ideal *PaymentMethodIdeal `json:"ideal"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
SepaDebit *PaymentMethodSepaDebit `json:"sepa_debit"`
Type PaymentMethodType `json:"type"`
}
// PaymentMethodList is a list of PaymentMethods as retrieved from a list endpoint.
type PaymentMethodList struct {
ListMeta
Data []*PaymentMethod `json:"data"`
}
// UnmarshalJSON handles deserialization of a PaymentMethod.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (i *PaymentMethod) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
i.ID = id
return nil
}
type pm PaymentMethod
var v pm
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = PaymentMethod(v)
return nil
}

202
vendor/github.com/stripe/stripe-go/paymentsource.go generated vendored Normal file
View file

@ -0,0 +1,202 @@
package stripe
import (
"encoding/json"
"fmt"
"github.com/stripe/stripe-go/form"
)
// PaymentSourceType consts represent valid payment sources.
type PaymentSourceType string
// List of values that PaymentSourceType can take.
const (
PaymentSourceTypeAccount PaymentSourceType = "account"
PaymentSourceTypeBankAccount PaymentSourceType = "bank_account"
PaymentSourceTypeBitcoinReceiver PaymentSourceType = "bitcoin_receiver"
PaymentSourceTypeCard PaymentSourceType = "card"
PaymentSourceTypeObject PaymentSourceType = "source"
)
// SourceParams is a union struct used to describe an
// arbitrary payment source.
type SourceParams struct {
Card *CardParams `form:"-"`
Token *string `form:"source"`
}
// AppendTo implements custom encoding logic for SourceParams.
func (p *SourceParams) AppendTo(body *form.Values, keyParts []string) {
if p.Card != nil {
p.Card.AppendToAsCardSourceOrExternalAccount(body, keyParts)
}
}
// CustomerSourceParams are used to manipulate a given Stripe
// Customer object's payment sources.
// For more details see https://stripe.com/docs/api#sources
type CustomerSourceParams struct {
Params `form:"*"`
Customer *string `form:"-"` // Goes in the URL
Source *SourceParams `form:"*"` // SourceParams has custom encoding so brought to top level with "*"
}
// SourceVerifyParams are used to verify a customer source
// For more details see https://stripe.com/docs/guides/ach-beta
type SourceVerifyParams struct {
Params `form:"*"`
Amounts [2]int64 `form:"amounts"` // Amounts is used when verifying bank accounts
Customer *string `form:"-"` // Goes in the URL
Values []*string `form:"values"` // Values is used when verifying sources
}
// SetSource adds valid sources to a CustomerSourceParams object,
// returning an error for unsupported sources.
func (cp *CustomerSourceParams) SetSource(sp interface{}) error {
source, err := SourceParamsFor(sp)
cp.Source = source
return err
}
// SourceParamsFor creates SourceParams objects around supported
// payment sources, returning errors if not.
//
// Currently supported source types are Card (CardParams) and
// Tokens/IDs (string), where Tokens could be single use card
// tokens or bitcoin receiver ids
func SourceParamsFor(obj interface{}) (*SourceParams, error) {
var sp *SourceParams
var err error
switch p := obj.(type) {
case *CardParams:
sp = &SourceParams{
Card: p,
}
case string:
sp = &SourceParams{
Token: &p,
}
default:
err = fmt.Errorf("Unsupported source type %s", p)
}
return sp, err
}
// PaymentSource describes the payment source used to make a Charge.
// The Type should indicate which object is fleshed out (eg. BitcoinReceiver or Card)
// For more details see https://stripe.com/docs/api#retrieve_charge
type PaymentSource struct {
BankAccount *BankAccount `json:"-"`
BitcoinReceiver *BitcoinReceiver `json:"-"`
Card *Card `json:"-"`
Deleted bool `json:"deleted"`
ID string `json:"id"`
SourceObject *Source `json:"-"`
Type PaymentSourceType `json:"object"`
}
// SourceList is a list object for cards.
type SourceList struct {
ListMeta
Data []*PaymentSource `json:"data"`
}
// SourceListParams are used to enumerate the payment sources that are attached
// to a Customer.
type SourceListParams struct {
ListParams `form:"*"`
Customer *string `form:"-"` // Handled in URL
}
// UnmarshalJSON handles deserialization of a PaymentSource.
// This custom unmarshaling is needed because the specific
// type of payment instrument it refers to is specified in the JSON
func (s *PaymentSource) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
s.ID = id
return nil
}
type paymentSource PaymentSource
var v paymentSource
if err := json.Unmarshal(data, &v); err != nil {
return err
}
var err error
*s = PaymentSource(v)
switch s.Type {
case PaymentSourceTypeBankAccount:
err = json.Unmarshal(data, &s.BankAccount)
case PaymentSourceTypeBitcoinReceiver:
err = json.Unmarshal(data, &s.BitcoinReceiver)
case PaymentSourceTypeCard:
err = json.Unmarshal(data, &s.Card)
case PaymentSourceTypeObject:
err = json.Unmarshal(data, &s.SourceObject)
}
return err
}
// MarshalJSON handles serialization of a PaymentSource.
// This custom marshaling is needed because the specific type
// of payment instrument it represents is specified by the Type
func (s *PaymentSource) MarshalJSON() ([]byte, error) {
var target interface{}
switch s.Type {
case PaymentSourceTypeBitcoinReceiver:
target = struct {
*BitcoinReceiver
Type PaymentSourceType `json:"object"`
}{
BitcoinReceiver: s.BitcoinReceiver,
Type: s.Type,
}
case PaymentSourceTypeCard:
var customerID *string
if s.Card.Customer != nil {
customerID = &s.Card.Customer.ID
}
target = struct {
*Card
Customer *string `json:"customer"`
Type PaymentSourceType `json:"object"`
}{
Card: s.Card,
Customer: customerID,
Type: s.Type,
}
case PaymentSourceTypeAccount:
target = struct {
ID string `json:"id"`
Type PaymentSourceType `json:"object"`
}{
ID: s.ID,
Type: s.Type,
}
case PaymentSourceTypeBankAccount:
var customerID *string
if s.BankAccount.Customer != nil {
customerID = &s.BankAccount.Customer.ID
}
target = struct {
*BankAccount
Customer *string `json:"customer"`
Type PaymentSourceType `json:"object"`
}{
BankAccount: s.BankAccount,
Customer: customerID,
Type: s.Type,
}
case "":
target = s.ID
}
return json.Marshal(target)
}

185
vendor/github.com/stripe/stripe-go/payout.go generated vendored Normal file
View file

@ -0,0 +1,185 @@
package stripe
import "encoding/json"
// PayoutDestinationType consts represent valid payout destinations.
type PayoutDestinationType string
// List of values that PayoutDestinationType can take.
const (
PayoutDestinationTypeBankAccount PayoutDestinationType = "bank_account"
PayoutDestinationTypeCard PayoutDestinationType = "card"
)
// PayoutFailureCode is the list of allowed values for the payout's failure code.
type PayoutFailureCode string
// List of values that PayoutFailureCode can take.
const (
PayoutFailureCodeAccountClosed PayoutFailureCode = "account_closed"
PayoutFailureCodeAccountFrozen PayoutFailureCode = "account_frozen"
PayoutFailureCodeBankAccountRestricted PayoutFailureCode = "bank_account_restricted"
PayoutFailureCodeBankOwnershipChanged PayoutFailureCode = "bank_ownership_changed"
PayoutFailureCodeCouldNotProcess PayoutFailureCode = "could_not_process"
PayoutFailureCodeDebitNotAuthorized PayoutFailureCode = "debit_not_authorized"
PayoutFailureCodeInsufficientFunds PayoutFailureCode = "insufficient_funds"
PayoutFailureCodeInvalidAccountNumber PayoutFailureCode = "invalid_account_number"
PayoutFailureCodeInvalidCurrency PayoutFailureCode = "invalid_currency"
PayoutFailureCodeNoAccount PayoutFailureCode = "no_account"
)
// PayoutSourceType is the list of allowed values for the payout's source_type field.
type PayoutSourceType string
// List of values that PayoutSourceType can take.
const (
PayoutSourceTypeAlipayAccount PayoutSourceType = "alipay_account"
PayoutSourceTypeBankAccount PayoutSourceType = "bank_account"
PayoutSourceTypeBitcoinReceiver PayoutSourceType = "bitcoin_receiver"
PayoutSourceTypeCard PayoutSourceType = "card"
PayoutSourceTypeFPX PayoutSourceType = "fpx"
)
// PayoutStatus is the list of allowed values for the payout's status.
type PayoutStatus string
// List of values that PayoutStatus can take.
const (
PayoutStatusCanceled PayoutStatus = "canceled"
PayoutStatusFailed PayoutStatus = "failed"
PayoutStatusInTransit PayoutStatus = "in_transit"
PayoutStatusPaid PayoutStatus = "paid"
PayoutStatusPending PayoutStatus = "pending"
)
// PayoutType is the list of allowed values for the payout's type.
type PayoutType string
// List of values that PayoutType can take.
const (
PayoutTypeBank PayoutType = "bank_account"
PayoutTypeCard PayoutType = "card"
)
// PayoutMethodType represents the type of payout
type PayoutMethodType string
// List of values that PayoutMethodType can take.
const (
PayoutMethodInstant PayoutMethodType = "instant"
PayoutMethodStandard PayoutMethodType = "standard"
)
// PayoutDestination describes the destination of a Payout.
// The Type should indicate which object is fleshed out
// For more details see https://stripe.com/docs/api/go#payout_object
type PayoutDestination struct {
BankAccount *BankAccount `json:"-"`
Card *Card `json:"-"`
ID string `json:"id"`
Type PayoutDestinationType `json:"object"`
}
// PayoutParams is the set of parameters that can be used when creating or updating a payout.
// For more details see https://stripe.com/docs/api#create_payout and https://stripe.com/docs/api#update_payout.
type PayoutParams struct {
Params `form:"*"`
Amount *int64 `form:"amount"`
Currency *string `form:"currency"`
Description *string `form:"description"`
Destination *string `form:"destination"`
Method *string `form:"method"`
SourceType *string `form:"source_type"`
StatementDescriptor *string `form:"statement_descriptor"`
}
// PayoutListParams is the set of parameters that can be used when listing payouts.
// For more details see https://stripe.com/docs/api#list_payouts.
type PayoutListParams struct {
ListParams `form:"*"`
ArrivalDate *int64 `form:"arrival_date"`
ArrivalDateRange *RangeQueryParams `form:"arrival_date"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Destination *string `form:"destination"`
Status *string `form:"status"`
}
// Payout is the resource representing a Stripe payout.
// For more details see https://stripe.com/docs/api#payouts.
type Payout struct {
Amount int64 `json:"amount"`
ArrivalDate int64 `json:"arrival_date"`
Automatic bool `json:"automatic"`
BalanceTransaction *BalanceTransaction `json:"balance_transaction"`
BankAccount *BankAccount `json:"bank_account"`
Card *Card `json:"card"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Description *string `json:"description"`
Destination *PayoutDestination `json:"destination"`
FailureBalanceTransaction *BalanceTransaction `json:"failure_balance_transaction"`
FailureCode PayoutFailureCode `json:"failure_code"`
FailureMessage string `json:"failure_message"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Method PayoutMethodType `json:"method"`
SourceType PayoutSourceType `json:"source_type"`
StatementDescriptor string `json:"statement_descriptor"`
Status PayoutStatus `json:"status"`
Type PayoutType `json:"type"`
}
// PayoutList is a list of payouts as retrieved from a list endpoint.
type PayoutList struct {
ListMeta
Data []*Payout `json:"data"`
}
// UnmarshalJSON handles deserialization of a Payout.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (p *Payout) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
p.ID = id
return nil
}
type payout Payout
var v payout
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*p = Payout(v)
return nil
}
// UnmarshalJSON handles deserialization of a PayoutDestination.
// This custom unmarshaling is needed because the specific
// type of destination it refers to is specified in the JSON
func (d *PayoutDestination) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
d.ID = id
return nil
}
type payoutDestination PayoutDestination
var v payoutDestination
if err := json.Unmarshal(data, &v); err != nil {
return err
}
var err error
*d = PayoutDestination(v)
switch d.Type {
case PayoutDestinationTypeBankAccount:
err = json.Unmarshal(data, &d.BankAccount)
case PayoutDestinationTypeCard:
err = json.Unmarshal(data, &d.Card)
}
return err
}

216
vendor/github.com/stripe/stripe-go/person.go generated vendored Normal file
View file

@ -0,0 +1,216 @@
package stripe
import "encoding/json"
// VerificationDocumentDetailsCode is a machine-readable code specifying the verification state of
// a document associated with a person.
type VerificationDocumentDetailsCode string
// List of values that IdentityVerificationDetailsCode can take.
const (
VerificationDocumentDetailsCodeDocumentCorrupt VerificationDocumentDetailsCode = "document_corrupt"
VerificationDocumentDetailsCodeDocumentFailedCopy VerificationDocumentDetailsCode = "document_failed_copy"
VerificationDocumentDetailsCodeDocumentFailedGreyscale VerificationDocumentDetailsCode = "document_failed_greyscale"
VerificationDocumentDetailsCodeDocumentFailedOther VerificationDocumentDetailsCode = "document_failed_other"
VerificationDocumentDetailsCodeDocumentFailedTestMode VerificationDocumentDetailsCode = "document_failed_test_mode"
VerificationDocumentDetailsCodeDocumentFraudulent VerificationDocumentDetailsCode = "document_fraudulent"
VerificationDocumentDetailsCodeDocumentIDTypeNotSupported VerificationDocumentDetailsCode = "document_id_type_not_supported"
VerificationDocumentDetailsCodeDocumentIDCountryNotSupported VerificationDocumentDetailsCode = "document_id_country_not_supported"
VerificationDocumentDetailsCodeDocumentManipulated VerificationDocumentDetailsCode = "document_manipulated"
VerificationDocumentDetailsCodeDocumentMissingBack VerificationDocumentDetailsCode = "document_missing_back"
VerificationDocumentDetailsCodeDocumentMissingFront VerificationDocumentDetailsCode = "document_missing_front"
VerificationDocumentDetailsCodeDocumentNotReadable VerificationDocumentDetailsCode = "document_not_readable"
VerificationDocumentDetailsCodeDocumentNotUploaded VerificationDocumentDetailsCode = "document_not_uploaded"
VerificationDocumentDetailsCodeDocumentTooLarge VerificationDocumentDetailsCode = "document_too_large"
)
// PersonVerificationDetailsCode is a machine-readable code specifying the verification state of a
// person.
type PersonVerificationDetailsCode string
// List of values that IdentityVerificationDetailsCode can take.
const (
PersonVerificationDetailsCodeFailedKeyedIdentity PersonVerificationDetailsCode = "failed_keyed_identity"
PersonVerificationDetailsCodeFailedOther PersonVerificationDetailsCode = "failed_other"
PersonVerificationDetailsCodeScanNameMismatch PersonVerificationDetailsCode = "scan_name_mismatch"
)
// IdentityVerificationStatus describes the different statuses for identity verification.
type IdentityVerificationStatus string
// List of values that IdentityVerificationStatus can take.
const (
IdentityVerificationStatusPending IdentityVerificationStatus = "pending"
IdentityVerificationStatusUnverified IdentityVerificationStatus = "unverified"
IdentityVerificationStatusVerified IdentityVerificationStatus = "verified"
)
// DOBParams represents a DOB during account creation/updates.
type DOBParams struct {
Day *int64 `form:"day"`
Month *int64 `form:"month"`
Year *int64 `form:"year"`
}
// RelationshipParams is used to set the relationship between an account and a person.
type RelationshipParams struct {
Director *bool `form:"director"`
Executive *bool `form:"executive"`
Owner *bool `form:"owner"`
PercentOwnership *float64 `form:"percent_ownership"`
Representative *bool `form:"representative"`
Title *string `form:"title"`
}
// PersonVerificationDocumentParams represents the parameters available for the document verifying
// a person's identity.
type PersonVerificationDocumentParams struct {
Back *string `form:"back"`
Front *string `form:"front"`
}
// PersonVerificationParams is used to represent parameters associated with a person's verification
// details.
type PersonVerificationParams struct {
AdditionalDocument *PersonVerificationDocumentParams `form:"additional_document"`
Document *PersonVerificationDocumentParams `form:"document"`
}
// PersonParams is the set of parameters that can be used when creating or updating a person.
// For more details see https://stripe.com/docs/api#create_person.
type PersonParams struct {
Params `form:"*"`
Account *string `form:"-"` // Included in URL
Address *AccountAddressParams `form:"address"`
AddressKana *AccountAddressParams `form:"address_kana"`
AddressKanji *AccountAddressParams `form:"address_kanji"`
DOB *DOBParams `form:"dob"`
Email *string `form:"email"`
FirstName *string `form:"first_name"`
FirstNameKana *string `form:"first_name_kana"`
FirstNameKanji *string `form:"first_name_kanji"`
Gender *string `form:"gender"`
IDNumber *string `form:"id_number"`
LastName *string `form:"last_name"`
LastNameKana *string `form:"last_name_kana"`
LastNameKanji *string `form:"last_name_kanji"`
MaidenName *string `form:"maiden_name"`
PersonToken *string `form:"person_token"`
Phone *string `form:"phone"`
Relationship *RelationshipParams `form:"relationship"`
SSNLast4 *string `form:"ssn_last_4"`
Verification *PersonVerificationParams `form:"verification"`
}
// RelationshipListParams is used to filter persons by the relationship
type RelationshipListParams struct {
Director *bool `form:"director"`
Executive *bool `form:"executive"`
Owner *bool `form:"owner"`
Representative *bool `form:"representative"`
}
// PersonListParams is the set of parameters that can be used when listing persons.
// For more detail see https://stripe.com/docs/api#list_persons.
type PersonListParams struct {
ListParams `form:"*"`
Account *string `form:"-"` // Included in URL
Relationship *RelationshipListParams `form:"relationship"`
}
// DOB represents a Person's date of birth.
type DOB struct {
Day int64 `json:"day"`
Month int64 `json:"month"`
Year int64 `json:"year"`
}
// Relationship represents how the Person relates to the business.
type Relationship struct {
Director bool `json:"director"`
Executive bool `json:"executive"`
Owner bool `json:"owner"`
PercentOwnership float64 `json:"percent_ownership"`
Representative bool `json:"representative"`
Title string `json:"title"`
}
// Requirements represents what's missing to verify a Person.
type Requirements struct {
CurrentlyDue []string `json:"currently_due"`
Errors []*AccountRequirementsError `json:"errors"`
EventuallyDue []string `json:"eventually_due"`
PastDue []string `json:"past_due"`
PendingVerification []string `json:"pending_verification"`
}
// PersonVerificationDocument represents the documents associated with a Person.
type PersonVerificationDocument struct {
Back *File `json:"back"`
Details string `json:"details"`
DetailsCode VerificationDocumentDetailsCode `json:"details_code"`
Front *File `json:"front"`
}
// PersonVerification is the structure for a person's verification details.
type PersonVerification struct {
AdditionalDocument *PersonVerificationDocument `json:"additional_document"`
Details string `json:"details"`
DetailsCode PersonVerificationDetailsCode `json:"details_code"`
Document *PersonVerificationDocument `json:"document"`
Status IdentityVerificationStatus `json:"status"`
}
// Person is the resource representing a Stripe person.
// For more details see https://stripe.com/docs/api#persons.
type Person struct {
Account string `json:"account"`
Address *AccountAddress `json:"address"`
AddressKana *AccountAddress `json:"address_kana"`
AddressKanji *AccountAddress `json:"address_kanji"`
Deleted bool `json:"deleted"`
DOB *DOB `json:"dob"`
Email string `json:"email"`
FirstName string `json:"first_name"`
FirstNameKana string `json:"first_name_kana"`
FirstNameKanji string `json:"first_name_kanji"`
Gender string `json:"gender"`
ID string `json:"id"`
IDNumberProvided bool `json:"id_number_provided"`
LastName string `json:"last_name"`
LastNameKana string `json:"last_name_kana"`
LastNameKanji string `json:"last_name_kanji"`
MaidenName string `json:"maiden_name"`
Metadata map[string]string `json:"metadata"`
Object string `json:"object"`
Phone string `json:"phone"`
Relationship *Relationship `json:"relationship"`
Requirements *Requirements `json:"requirements"`
SSNLast4Provided bool `json:"ssn_last_4_provided"`
Verification *PersonVerification `json:"verification"`
}
// PersonList is a list of persons as retrieved from a list endpoint.
type PersonList struct {
ListMeta
Data []*Person `json:"data"`
}
// UnmarshalJSON handles deserialization of a Person.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *Person) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
c.ID = id
return nil
}
type person Person
var v person
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*c = Person(v)
return nil
}

202
vendor/github.com/stripe/stripe-go/plan.go generated vendored Normal file
View file

@ -0,0 +1,202 @@
package stripe
import (
"encoding/json"
"strconv"
"github.com/stripe/stripe-go/form"
)
// PlanInterval is the list of allowed values for a plan's interval.
type PlanInterval string
// List of values that PlanInterval can take.
const (
PlanIntervalDay PlanInterval = "day"
PlanIntervalWeek PlanInterval = "week"
PlanIntervalMonth PlanInterval = "month"
PlanIntervalYear PlanInterval = "year"
)
// PlanBillingScheme is the list of allowed values for a plan's billing scheme.
type PlanBillingScheme string
// List of values that PlanBillingScheme can take.
const (
PlanBillingSchemePerUnit PlanBillingScheme = "per_unit"
PlanBillingSchemeTiered PlanBillingScheme = "tiered"
)
// PlanUsageType is the list of allowed values for a plan's usage type.
type PlanUsageType string
// List of values that PlanUsageType can take.
const (
PlanUsageTypeLicensed PlanUsageType = "licensed"
PlanUsageTypeMetered PlanUsageType = "metered"
)
// PlanTiersMode is the list of allowed values for a plan's tiers mode.
type PlanTiersMode string
// List of values that PlanTiersMode can take.
const (
PlanTiersModeGraduated PlanTiersMode = "graduated"
PlanTiersModeVolume PlanTiersMode = "volume"
)
// PlanTransformUsageRound is the list of allowed values for a plan's transform usage round logic.
type PlanTransformUsageRound string
// List of values that PlanTransformUsageRound can take.
const (
PlanTransformUsageRoundDown PlanTransformUsageRound = "down"
PlanTransformUsageRoundUp PlanTransformUsageRound = "up"
)
// PlanAggregateUsage is the list of allowed values for a plan's aggregate usage.
type PlanAggregateUsage string
// List of values that PlanAggregateUsage can take.
const (
PlanAggregateUsageLastDuringPeriod PlanAggregateUsage = "last_during_period"
PlanAggregateUsageLastEver PlanAggregateUsage = "last_ever"
PlanAggregateUsageMax PlanAggregateUsage = "max"
PlanAggregateUsageSum PlanAggregateUsage = "sum"
)
// Plan is the resource representing a Stripe plan.
// For more details see https://stripe.com/docs/api#plans.
type Plan struct {
Active bool `json:"active"`
AggregateUsage string `json:"aggregate_usage"`
Amount int64 `json:"amount"`
AmountDecimal float64 `json:"amount_decimal,string"`
BillingScheme PlanBillingScheme `json:"billing_scheme"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Deleted bool `json:"deleted"`
ID string `json:"id"`
Interval PlanInterval `json:"interval"`
IntervalCount int64 `json:"interval_count"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Nickname string `json:"nickname"`
Product *Product `json:"product"`
Tiers []*PlanTier `json:"tiers"`
TiersMode string `json:"tiers_mode"`
TransformUsage *PlanTransformUsage `json:"transform_usage"`
TrialPeriodDays int64 `json:"trial_period_days"`
UsageType PlanUsageType `json:"usage_type"`
}
// PlanList is a list of plans as returned from a list endpoint.
type PlanList struct {
ListMeta
Data []*Plan `json:"data"`
}
// PlanListParams is the set of parameters that can be used when listing plans.
// For more details see https://stripe.com/docs/api#list_plans.
type PlanListParams struct {
ListParams `form:"*"`
Active *bool `form:"active"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
Product *string `form:"product"`
}
// PlanParams is the set of parameters that can be used when creating or updating a plan.
// For more details see https://stripe.com/docs/api#create_plan and https://stripe.com/docs/api#update_plan.
type PlanParams struct {
Params `form:"*"`
Active *bool `form:"active"`
AggregateUsage *string `form:"aggregate_usage"`
Amount *int64 `form:"amount"`
AmountDecimal *float64 `form:"amount_decimal,high_precision"`
BillingScheme *string `form:"billing_scheme"`
Currency *string `form:"currency"`
ID *string `form:"id"`
Interval *string `form:"interval"`
IntervalCount *int64 `form:"interval_count"`
Nickname *string `form:"nickname"`
Product *PlanProductParams `form:"product"`
ProductID *string `form:"product"`
Tiers []*PlanTierParams `form:"tiers"`
TiersMode *string `form:"tiers_mode"`
TransformUsage *PlanTransformUsageParams `form:"transform_usage"`
TrialPeriodDays *int64 `form:"trial_period_days"`
UsageType *string `form:"usage_type"`
}
// PlanTier configures tiered pricing
type PlanTier struct {
FlatAmount int64 `json:"flat_amount"`
FlatAmountDecimal float64 `json:"flat_amount_decimal,string"`
UnitAmount int64 `json:"unit_amount"`
UnitAmountDecimal float64 `json:"unit_amount_decimal,string"`
UpTo int64 `json:"up_to"`
}
// PlanTransformUsage represents the bucket billing configuration.
type PlanTransformUsage struct {
DivideBy int64 `json:"divide_by"`
Round PlanTransformUsageRound `json:"round"`
}
// PlanTransformUsageParams represents the bucket billing configuration.
type PlanTransformUsageParams struct {
DivideBy *int64 `form:"divide_by"`
Round *string `form:"round"`
}
// PlanTierParams configures tiered pricing
type PlanTierParams struct {
Params `form:"*"`
FlatAmount *int64 `form:"flat_amount"`
FlatAmountDecimal *float64 `form:"flat_amount_decimal,high_precision"`
UnitAmount *int64 `form:"unit_amount"`
UnitAmountDecimal *float64 `form:"unit_amount_decimal,high_precision"`
UpTo *int64 `form:"-"` // handled in custom AppendTo
UpToInf *bool `form:"-"` // handled in custom AppendTo
}
// AppendTo implements custom up_to serialisation logic for tiers configuration
func (p *PlanTierParams) AppendTo(body *form.Values, keyParts []string) {
if BoolValue(p.UpToInf) {
body.Add(form.FormatKey(append(keyParts, "up_to")), "inf")
} else {
body.Add(form.FormatKey(append(keyParts, "up_to")), strconv.FormatInt(Int64Value(p.UpTo), 10))
}
}
// PlanProductParams is the set of parameters that can be used when creating a product inside a plan
// This can only be used on plan creation and won't work on plan update.
// For more details see https://stripe.com/docs/api#create_plan-product and https://stripe.com/docs/api#update_plan-product
type PlanProductParams struct {
Active *bool `form:"active"`
ID *string `form:"id"`
Name *string `form:"name"`
Metadata map[string]string `form:"metadata"`
StatementDescriptor *string `form:"statement_descriptor"`
UnitLabel *string `form:"unit_label"`
}
// UnmarshalJSON handles deserialization of a Plan.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (s *Plan) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
s.ID = id
return nil
}
type plan Plan
var v plan
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*s = Plan(v)
return nil
}

109
vendor/github.com/stripe/stripe-go/product.go generated vendored Normal file
View file

@ -0,0 +1,109 @@
package stripe
import "encoding/json"
// ProductType is the type of a product.
type ProductType string
// List of values that ProductType can take.
const (
ProductTypeGood ProductType = "good"
ProductTypeService ProductType = "service"
)
// PackageDimensionsParams represents the set of parameters for the the dimension of a
// product or a SKU from the perspective of shipping .
type PackageDimensionsParams struct {
Height *float64 `form:"height"`
Length *float64 `form:"length"`
Weight *float64 `form:"weight"`
Width *float64 `form:"width"`
}
// ProductParams is the set of parameters that can be used when creating or updating a product.
type ProductParams struct {
Params `form:"*"`
Active *bool `form:"active"`
Attributes []*string `form:"attributes"`
Caption *string `form:"caption"`
DeactivateOn []*string `form:"deactivate_on"`
Description *string `form:"description"`
ID *string `form:"id"`
Images []*string `form:"images"`
Name *string `form:"name"`
PackageDimensions *PackageDimensionsParams `form:"package_dimensions"`
Shippable *bool `form:"shippable"`
StatementDescriptor *string `form:"statement_descriptor"`
Type *string `form:"type"`
UnitLabel *string `form:"unit_label"`
URL *string `form:"url"`
}
// PackageDimensions represents the dimension of a product or a SKU from the
// perspective of shipping.
type PackageDimensions struct {
Height float64 `json:"height"`
Length float64 `json:"length"`
Weight float64 `json:"weight"`
Width float64 `json:"width"`
}
// Product is the resource representing a Stripe product.
// For more details see https://stripe.com/docs/api#products.
type Product struct {
Active bool `json:"active"`
Attributes []string `json:"attributes"`
Caption string `json:"caption"`
Created int64 `json:"created"`
DeactivateOn []string `json:"deactivate_on"`
Description string `json:"description"`
ID string `json:"id"`
Images []string `json:"images"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
PackageDimensions *PackageDimensions `json:"package_dimensions"`
Shippable bool `json:"shippable"`
StatementDescriptor string `json:"statement_descriptor"`
Type ProductType `json:"type"`
UnitLabel string `json:"unit_label"`
URL string `json:"url"`
Updated int64 `json:"updated"`
}
// ProductList is a list of products as retrieved from a list endpoint.
type ProductList struct {
ListMeta
Data []*Product `json:"data"`
}
// ProductListParams is the set of parameters that can be used when listing products.
type ProductListParams struct {
ListParams `form:"*"`
Active *bool `form:"active"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
IDs []*string `form:"ids"`
Shippable *bool `form:"shippable"`
URL *string `form:"url"`
Type *string `form:"type"`
}
// UnmarshalJSON handles deserialization of a Product.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (p *Product) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
p.ID = id
return nil
}
type product Product
var v product
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*p = Product(v)
return nil
}

View file

@ -0,0 +1,48 @@
package stripe
// RadarEarlyFraudWarningFraudType are strings that map to the type of fraud labelled by the issuer.
type RadarEarlyFraudWarningFraudType string
// List of values that RadarEarlyFraudWarningFraudType can take.
const (
RadarEarlyFraudWarningFraudTypeCardNeverReceived RadarEarlyFraudWarningFraudType = "card_never_received"
RadarEarlyFraudWarningFraudTypeFraudulentCardApplication RadarEarlyFraudWarningFraudType = "fraudulent_card_application"
RadarEarlyFraudWarningFraudTypeMadeWithCounterfeitCard RadarEarlyFraudWarningFraudType = "made_with_counterfeit_card"
RadarEarlyFraudWarningFraudTypeMadeWithLostCard RadarEarlyFraudWarningFraudType = "made_with_lost_card"
RadarEarlyFraudWarningFraudTypeMadeWithStolenCard RadarEarlyFraudWarningFraudType = "made_with_stolen_card"
RadarEarlyFraudWarningFraudTypeMisc RadarEarlyFraudWarningFraudType = "misc"
RadarEarlyFraudWarningFraudTypeUnauthorizedUseOfCard RadarEarlyFraudWarningFraudType = "unauthorized_use_of_card"
)
// RadarEarlyFraudWarningParams is the set of parameters that can be used when
// retrieving early fraud warnings. For more details see
// https://stripe.com/docs/api/early_fraud_warnings/retrieve.
type RadarEarlyFraudWarningParams struct {
Params `form:"*"`
}
// RadarEarlyFraudWarningListParams is the set of parameters that can be used when
// listing early fraud warnings. For more details see
// https://stripe.com/docs/api/early_fraud_warnings/list.
type RadarEarlyFraudWarningListParams struct {
ListParams `form:"*"`
Charge *string `form:"charge"`
}
// RadarEarlyFraudWarningList is a list of early fraud warnings as retrieved from a
// list endpoint.
type RadarEarlyFraudWarningList struct {
ListMeta
Values []*RadarEarlyFraudWarning `json:"data"`
}
// RadarEarlyFraudWarning is the resource representing an early fraud warning. For
// more details see https://stripe.com/docs/api/early_fraud_warnings/object.
type RadarEarlyFraudWarning struct {
Actionable bool `json:"actionable"`
Charge *Charge `json:"charge"`
Created int64 `json:"created"`
FraudType RadarEarlyFraudWarningFraudType `json:"fraud_type"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
}

55
vendor/github.com/stripe/stripe-go/radar_valuelist.go generated vendored Normal file
View file

@ -0,0 +1,55 @@
package stripe
// RadarValueListItemType is the possible values for a type of value list items.
type RadarValueListItemType string
// List of values that RadarValueListItemType can take.
const (
RadarValueListItemTypeCardBin RadarValueListItemType = "card_bin"
RadarValueListItemTypeCardFingerprint RadarValueListItemType = "card_fingerprint"
RadarValueListItemTypeCountry RadarValueListItemType = "country"
RadarValueListItemTypeEmail RadarValueListItemType = "email"
RadarValueListItemTypeIPAddress RadarValueListItemType = "ip_address"
RadarValueListItemTypeString RadarValueListItemType = "string"
RadarValueListItemTypeCaseSensitiveString RadarValueListItemType = "case_sensitive_string"
)
// RadarValueListParams is the set of parameters that can be used when creating a value list.
type RadarValueListParams struct {
Params `form:"*"`
Alias *string `form:"alias"`
ItemType *string `form:"item_type"`
Name *string `form:"name"`
}
// RadarValueListListParams is the set of parameters that can be used when listing value lists.
type RadarValueListListParams struct {
ListParams `form:"*"`
Alias *string `form:"alias"`
Contains *string `form:"contains"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
}
// RadarValueList is the resource representing a value list.
type RadarValueList struct {
Alias string `json:"alias"`
Created int64 `json:"created"`
CreatedBy string `json:"created_by"`
Deleted bool `json:"deleted"`
ID string `json:"id"`
ItemType RadarValueListItemType `json:"item_type"`
ListItems *RadarValueListItemList `json:"list_items"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
Name string `json:"name"`
Object string `json:"object"`
Updated int64 `json:"updated"`
UpdatedBy string `json:"updated_by"`
}
// RadarValueListList is a list of value lists as retrieved from a list endpoint.
type RadarValueListList struct {
ListMeta
Data []*RadarValueList `json:"data"`
}

View file

@ -0,0 +1,36 @@
package stripe
// RadarValueListItemParams is the set of parameters that can be used when creating a value list item.
type RadarValueListItemParams struct {
Params `form:"*"`
Value *string `form:"value"`
RadarValueList *string `form:"value_list"`
}
// RadarValueListItemListParams is the set of parameters that can be used when listing value list items.
type RadarValueListItemListParams struct {
ListParams `form:"*"`
Created *int64 `form:"created"`
CreatedRange *RangeQueryParams `form:"created"`
RadarValueList *string `form:"value_list"`
Value *string `form:"value"`
}
// RadarValueListItem is the resource representing a value list item.
type RadarValueListItem struct {
Created int64 `json:"created"`
CreatedBy string `json:"created_by"`
Deleted bool `json:"deleted"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
Name string `json:"name"`
Object string `json:"object"`
Value string `json:"value"`
RadarValueList string `json:"value_list"`
}
// RadarValueListItemList is a list of value list items as retrieved from a list endpoint.
type RadarValueListItemList struct {
ListMeta
Data []*RadarValueListItem `json:"data"`
}

95
vendor/github.com/stripe/stripe-go/recipient.go generated vendored Normal file
View file

@ -0,0 +1,95 @@
package stripe
import (
"encoding/json"
"github.com/stripe/stripe-go/form"
)
// RecipientType is the list of allowed values for the recipient's type.
type RecipientType string
// List of values that RecipientType can take.
const (
RecipientTypeIndividual RecipientType = "individual"
RecipientTypeCorporation RecipientType = "corporation"
)
// RecipientParams is the set of parameters that can be used when creating or updating recipients.
// For more details see https://stripe.com/docs/api#create_recipient and https://stripe.com/docs/api#update_recipient.
type RecipientParams struct {
Params `form:"*"`
BankAccount *BankAccountParams `form:"-"` // Kind of an abberation because a bank account's token will be replace the rest of its data. Keep this in a custom AppendTo for now.
Card *CardParams `form:"card"`
DefaultCard *string `form:"default_card"`
Description *string `form:"description"`
Email *string `form:"email"`
Name *string `form:"name"`
TaxID *string `form:"tax_id"`
Token *string `form:"card"`
Type *string `form:"-"` // Doesn't seem to be used anywhere
}
// AppendTo implements some custom behavior around a recipient's bank account.
// This was probably the wrong way to go about this, but grandfather the
// behavior for the time being.
func (p *RecipientParams) AppendTo(body *form.Values, keyParts []string) {
if p.BankAccount != nil {
if p.BankAccount.Token != nil {
body.Add("bank_account", StringValue(p.BankAccount.Token))
} else {
form.AppendToPrefixed(body, p.BankAccount, append(keyParts, "bank_account"))
}
}
}
// RecipientListParams is the set of parameters that can be used when listing recipients.
// For more details see https://stripe.com/docs/api#list_recipients.
type RecipientListParams struct {
ListParams `form:"*"`
Verified *bool `form:"verified"`
}
// Recipient is the resource representing a Stripe recipient.
// For more details see https://stripe.com/docs/api#recipients.
type Recipient struct {
ActiveAccount *BankAccount `json:"active_account"`
Cards *CardList `json:"cards"`
Created int64 `json:"created"`
DefaultCard *Card `json:"default_card"`
Deleted bool `json:"deleted"`
Description string `json:"description"`
Email string `json:"email"`
ID string `json:"id"`
Livemode bool `json:"livemode"`
Metadata map[string]string `json:"metadata"`
MigratedTo *Account `json:"migrated_to"`
Name string `json:"name"`
Type RecipientType `json:"type"`
}
// RecipientList is a list of recipients as retrieved from a list endpoint.
type RecipientList struct {
ListMeta
Data []*Recipient `json:"data"`
}
// UnmarshalJSON handles deserialization of a Recipient.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (r *Recipient) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
r.ID = id
return nil
}
type recipient Recipient
var v recipient
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*r = Recipient(v)
return nil
}

Some files were not shown because too many files have changed in this diff Show more