From 92005bf2ae19e0d8c8d298acdc81dc08ae9a5151 Mon Sep 17 00:00:00 2001 From: Ruidy Nemausat Date: Fri, 20 Mar 2020 00:19:27 +0100 Subject: [PATCH] heroku db --- .env | 3 +- main.go | 4 +- vendor/github.com/joho/godotenv/.travis.yml | 8 + vendor/github.com/joho/godotenv/LICENCE | 23 + vendor/github.com/joho/godotenv/README.md | 163 ++ vendor/github.com/joho/godotenv/godotenv.go | 346 +++ vendor/github.com/lib/pq/.travis.sh | 73 + vendor/github.com/lib/pq/.travis.yml | 44 + vendor/github.com/lib/pq/CONTRIBUTING.md | 29 + vendor/github.com/lib/pq/LICENSE.md | 8 + vendor/github.com/lib/pq/README.md | 95 + vendor/github.com/lib/pq/TESTS.md | 33 + vendor/github.com/lib/pq/array.go | 756 +++++++ vendor/github.com/lib/pq/buf.go | 91 + vendor/github.com/lib/pq/conn.go | 1923 +++++++++++++++++ vendor/github.com/lib/pq/conn_go18.go | 149 ++ vendor/github.com/lib/pq/connector.go | 110 + vendor/github.com/lib/pq/copy.go | 282 +++ vendor/github.com/lib/pq/doc.go | 245 +++ vendor/github.com/lib/pq/encode.go | 602 ++++++ vendor/github.com/lib/pq/error.go | 515 +++++ vendor/github.com/lib/pq/go.mod | 1 + vendor/github.com/lib/pq/notify.go | 797 +++++++ vendor/github.com/lib/pq/oid/doc.go | 6 + vendor/github.com/lib/pq/oid/types.go | 343 +++ vendor/github.com/lib/pq/rows.go | 93 + vendor/github.com/lib/pq/scram/scram.go | 264 +++ vendor/github.com/lib/pq/ssl.go | 175 ++ vendor/github.com/lib/pq/ssl_permissions.go | 20 + vendor/github.com/lib/pq/ssl_windows.go | 9 + vendor/github.com/lib/pq/url.go | 76 + vendor/github.com/lib/pq/user_posix.go | 24 + vendor/github.com/lib/pq/user_windows.go | 27 + vendor/github.com/lib/pq/uuid.go | 23 + .../github.com/stripe/stripe-go/.travis.yml | 62 + vendor/github.com/stripe/stripe-go/CHANGELOG | 1 + .../github.com/stripe/stripe-go/CHANGELOG.md | 1624 ++++++++++++++ .../stripe/stripe-go/CODE_OF_CONDUCT.md | 77 + vendor/github.com/stripe/stripe-go/LICENSE | 21 + vendor/github.com/stripe/stripe-go/Makefile | 30 + vendor/github.com/stripe/stripe-go/README.md | 428 ++++ vendor/github.com/stripe/stripe-go/VERSION | 1 + vendor/github.com/stripe/stripe-go/account.go | 562 +++++ .../stripe/stripe-go/accountlink.go | 38 + vendor/github.com/stripe/stripe-go/address.go | 21 + .../stripe/stripe-go/applepaydomain.go | 27 + .../stripe/stripe-go/application.go | 28 + vendor/github.com/stripe/stripe-go/balance.go | 38 + .../stripe/stripe-go/balancetransaction.go | 222 ++ .../stripe/stripe-go/bankaccount.go | 184 ++ .../stripe/stripe-go/bitcoinreceiver.go | 63 + .../stripe/stripe-go/bitcointransaction.go | 49 + .../github.com/stripe/stripe-go/capability.go | 90 + vendor/github.com/stripe/stripe-go/card.go | 273 +++ vendor/github.com/stripe/stripe-go/charge.go | 586 +++++ .../stripe/stripe-go/checkout_session.go | 211 ++ .../stripe/stripe-go/countryspec.go | 39 + vendor/github.com/stripe/stripe-go/coupon.go | 81 + .../github.com/stripe/stripe-go/creditnote.go | 204 ++ .../github.com/stripe/stripe-go/currency.go | 148 ++ .../github.com/stripe/stripe-go/customer.go | 165 ++ .../stripe-go/customerbalancetransaction.go | 81 + .../github.com/stripe/stripe-go/discount.go | 17 + vendor/github.com/stripe/stripe-go/dispute.go | 172 ++ .../stripe/stripe-go/ephemeralkey.go | 50 + vendor/github.com/stripe/stripe-go/error.go | 297 +++ vendor/github.com/stripe/stripe-go/event.go | 125 ++ .../stripe/stripe-go/exchangerate.go | 25 + vendor/github.com/stripe/stripe-go/fee.go | 61 + .../github.com/stripe/stripe-go/feerefund.go | 57 + vendor/github.com/stripe/stripe-go/file.go | 150 ++ .../github.com/stripe/stripe-go/filelink.go | 60 + .../github.com/stripe/stripe-go/form/form.go | 623 ++++++ vendor/github.com/stripe/stripe-go/invoice.go | 379 ++++ .../stripe/stripe-go/invoiceitem.go | 87 + .../stripe/stripe-go/issuing_authorization.go | 262 +++ .../stripe/stripe-go/issuing_card.go | 270 +++ .../stripe/stripe-go/issuing_cardholder.go | 200 ++ .../stripe/stripe-go/issuing_dispute.go | 123 ++ .../stripe/stripe-go/issuing_transaction.go | 74 + vendor/github.com/stripe/stripe-go/iter.go | 133 ++ vendor/github.com/stripe/stripe-go/log.go | 221 ++ .../github.com/stripe/stripe-go/loginlink.go | 16 + vendor/github.com/stripe/stripe-go/mandate.go | 126 ++ vendor/github.com/stripe/stripe-go/oauth.go | 129 ++ vendor/github.com/stripe/stripe-go/order.go | 272 +++ .../stripe/stripe-go/orderreturn.go | 56 + vendor/github.com/stripe/stripe-go/params.go | 269 +++ .../stripe/stripe-go/paymentintent.go | 355 +++ .../stripe/stripe-go/paymentintent/client.go | 128 ++ .../stripe/stripe-go/paymentmethod.go | 276 +++ .../stripe/stripe-go/paymentsource.go | 202 ++ vendor/github.com/stripe/stripe-go/payout.go | 185 ++ vendor/github.com/stripe/stripe-go/person.go | 216 ++ vendor/github.com/stripe/stripe-go/plan.go | 202 ++ vendor/github.com/stripe/stripe-go/product.go | 109 + .../stripe-go/radar_earlyfraudwarning.go | 48 + .../stripe/stripe-go/radar_valuelist.go | 55 + .../stripe/stripe-go/radar_valuelistitem.go | 36 + .../github.com/stripe/stripe-go/recipient.go | 95 + .../stripe/stripe-go/recipienttransfer.go | 155 ++ vendor/github.com/stripe/stripe-go/refund.go | 103 + .../stripe/stripe-go/reporting_reportrun.go | 69 + .../stripe/stripe-go/reporting_reporttype.go | 30 + .../github.com/stripe/stripe-go/reversal.go | 57 + vendor/github.com/stripe/stripe-go/review.go | 71 + .../stripe/stripe-go/setupintent.go | 218 ++ .../stripe-go/sigma_scheduledqueryrun.go | 64 + vendor/github.com/stripe/stripe-go/sku.go | 106 + vendor/github.com/stripe/stripe-go/source.go | 352 +++ .../stripe/stripe-go/sourcetransaction.go | 55 + vendor/github.com/stripe/stripe-go/stripe.go | 1139 ++++++++++ vendor/github.com/stripe/stripe-go/sub.go | 272 +++ vendor/github.com/stripe/stripe-go/subitem.go | 60 + .../stripe/stripe-go/subschedule.go | 230 ++ vendor/github.com/stripe/stripe-go/taxid.go | 107 + vendor/github.com/stripe/stripe-go/taxrate.go | 76 + .../stripe-go/terminal_connectiontoken.go | 14 + .../stripe/stripe-go/terminal_location.go | 30 + .../stripe/stripe-go/terminal_reader.go | 46 + .../stripe/stripe-go/threedsecure.go | 29 + vendor/github.com/stripe/stripe-go/token.go | 51 + vendor/github.com/stripe/stripe-go/topup.go | 55 + .../github.com/stripe/stripe-go/transfer.go | 111 + .../stripe/stripe-go/usagerecord.go | 27 + .../stripe/stripe-go/usagerecordsummary.go | 25 + .../stripe/stripe-go/v32_migration_guide.md | 146 ++ .../stripe/stripe-go/webhookendpoint.go | 67 + vendor/modules.txt | 17 + 129 files changed, 22655 insertions(+), 2 deletions(-) create mode 100644 vendor/github.com/joho/godotenv/.travis.yml create mode 100644 vendor/github.com/joho/godotenv/LICENCE create mode 100644 vendor/github.com/joho/godotenv/README.md create mode 100644 vendor/github.com/joho/godotenv/godotenv.go create mode 100644 vendor/github.com/lib/pq/.travis.sh create mode 100644 vendor/github.com/lib/pq/.travis.yml create mode 100644 vendor/github.com/lib/pq/CONTRIBUTING.md create mode 100644 vendor/github.com/lib/pq/LICENSE.md create mode 100644 vendor/github.com/lib/pq/README.md create mode 100644 vendor/github.com/lib/pq/TESTS.md create mode 100644 vendor/github.com/lib/pq/array.go create mode 100644 vendor/github.com/lib/pq/buf.go create mode 100644 vendor/github.com/lib/pq/conn.go create mode 100644 vendor/github.com/lib/pq/conn_go18.go create mode 100644 vendor/github.com/lib/pq/connector.go create mode 100644 vendor/github.com/lib/pq/copy.go create mode 100644 vendor/github.com/lib/pq/doc.go create mode 100644 vendor/github.com/lib/pq/encode.go create mode 100644 vendor/github.com/lib/pq/error.go create mode 100644 vendor/github.com/lib/pq/go.mod create mode 100644 vendor/github.com/lib/pq/notify.go create mode 100644 vendor/github.com/lib/pq/oid/doc.go create mode 100644 vendor/github.com/lib/pq/oid/types.go create mode 100644 vendor/github.com/lib/pq/rows.go create mode 100644 vendor/github.com/lib/pq/scram/scram.go create mode 100644 vendor/github.com/lib/pq/ssl.go create mode 100644 vendor/github.com/lib/pq/ssl_permissions.go create mode 100644 vendor/github.com/lib/pq/ssl_windows.go create mode 100644 vendor/github.com/lib/pq/url.go create mode 100644 vendor/github.com/lib/pq/user_posix.go create mode 100644 vendor/github.com/lib/pq/user_windows.go create mode 100644 vendor/github.com/lib/pq/uuid.go create mode 100644 vendor/github.com/stripe/stripe-go/.travis.yml create mode 100644 vendor/github.com/stripe/stripe-go/CHANGELOG create mode 100644 vendor/github.com/stripe/stripe-go/CHANGELOG.md create mode 100644 vendor/github.com/stripe/stripe-go/CODE_OF_CONDUCT.md create mode 100644 vendor/github.com/stripe/stripe-go/LICENSE create mode 100644 vendor/github.com/stripe/stripe-go/Makefile create mode 100644 vendor/github.com/stripe/stripe-go/README.md create mode 100644 vendor/github.com/stripe/stripe-go/VERSION create mode 100644 vendor/github.com/stripe/stripe-go/account.go create mode 100644 vendor/github.com/stripe/stripe-go/accountlink.go create mode 100644 vendor/github.com/stripe/stripe-go/address.go create mode 100644 vendor/github.com/stripe/stripe-go/applepaydomain.go create mode 100644 vendor/github.com/stripe/stripe-go/application.go create mode 100644 vendor/github.com/stripe/stripe-go/balance.go create mode 100644 vendor/github.com/stripe/stripe-go/balancetransaction.go create mode 100644 vendor/github.com/stripe/stripe-go/bankaccount.go create mode 100644 vendor/github.com/stripe/stripe-go/bitcoinreceiver.go create mode 100644 vendor/github.com/stripe/stripe-go/bitcointransaction.go create mode 100644 vendor/github.com/stripe/stripe-go/capability.go create mode 100644 vendor/github.com/stripe/stripe-go/card.go create mode 100644 vendor/github.com/stripe/stripe-go/charge.go create mode 100644 vendor/github.com/stripe/stripe-go/checkout_session.go create mode 100644 vendor/github.com/stripe/stripe-go/countryspec.go create mode 100644 vendor/github.com/stripe/stripe-go/coupon.go create mode 100644 vendor/github.com/stripe/stripe-go/creditnote.go create mode 100644 vendor/github.com/stripe/stripe-go/currency.go create mode 100644 vendor/github.com/stripe/stripe-go/customer.go create mode 100644 vendor/github.com/stripe/stripe-go/customerbalancetransaction.go create mode 100644 vendor/github.com/stripe/stripe-go/discount.go create mode 100644 vendor/github.com/stripe/stripe-go/dispute.go create mode 100644 vendor/github.com/stripe/stripe-go/ephemeralkey.go create mode 100644 vendor/github.com/stripe/stripe-go/error.go create mode 100644 vendor/github.com/stripe/stripe-go/event.go create mode 100644 vendor/github.com/stripe/stripe-go/exchangerate.go create mode 100644 vendor/github.com/stripe/stripe-go/fee.go create mode 100644 vendor/github.com/stripe/stripe-go/feerefund.go create mode 100644 vendor/github.com/stripe/stripe-go/file.go create mode 100644 vendor/github.com/stripe/stripe-go/filelink.go create mode 100644 vendor/github.com/stripe/stripe-go/form/form.go create mode 100644 vendor/github.com/stripe/stripe-go/invoice.go create mode 100644 vendor/github.com/stripe/stripe-go/invoiceitem.go create mode 100644 vendor/github.com/stripe/stripe-go/issuing_authorization.go create mode 100644 vendor/github.com/stripe/stripe-go/issuing_card.go create mode 100644 vendor/github.com/stripe/stripe-go/issuing_cardholder.go create mode 100644 vendor/github.com/stripe/stripe-go/issuing_dispute.go create mode 100644 vendor/github.com/stripe/stripe-go/issuing_transaction.go create mode 100644 vendor/github.com/stripe/stripe-go/iter.go create mode 100644 vendor/github.com/stripe/stripe-go/log.go create mode 100644 vendor/github.com/stripe/stripe-go/loginlink.go create mode 100644 vendor/github.com/stripe/stripe-go/mandate.go create mode 100644 vendor/github.com/stripe/stripe-go/oauth.go create mode 100644 vendor/github.com/stripe/stripe-go/order.go create mode 100644 vendor/github.com/stripe/stripe-go/orderreturn.go create mode 100644 vendor/github.com/stripe/stripe-go/params.go create mode 100644 vendor/github.com/stripe/stripe-go/paymentintent.go create mode 100644 vendor/github.com/stripe/stripe-go/paymentintent/client.go create mode 100644 vendor/github.com/stripe/stripe-go/paymentmethod.go create mode 100644 vendor/github.com/stripe/stripe-go/paymentsource.go create mode 100644 vendor/github.com/stripe/stripe-go/payout.go create mode 100644 vendor/github.com/stripe/stripe-go/person.go create mode 100644 vendor/github.com/stripe/stripe-go/plan.go create mode 100644 vendor/github.com/stripe/stripe-go/product.go create mode 100644 vendor/github.com/stripe/stripe-go/radar_earlyfraudwarning.go create mode 100644 vendor/github.com/stripe/stripe-go/radar_valuelist.go create mode 100644 vendor/github.com/stripe/stripe-go/radar_valuelistitem.go create mode 100644 vendor/github.com/stripe/stripe-go/recipient.go create mode 100644 vendor/github.com/stripe/stripe-go/recipienttransfer.go create mode 100644 vendor/github.com/stripe/stripe-go/refund.go create mode 100644 vendor/github.com/stripe/stripe-go/reporting_reportrun.go create mode 100644 vendor/github.com/stripe/stripe-go/reporting_reporttype.go create mode 100644 vendor/github.com/stripe/stripe-go/reversal.go create mode 100644 vendor/github.com/stripe/stripe-go/review.go create mode 100644 vendor/github.com/stripe/stripe-go/setupintent.go create mode 100644 vendor/github.com/stripe/stripe-go/sigma_scheduledqueryrun.go create mode 100644 vendor/github.com/stripe/stripe-go/sku.go create mode 100644 vendor/github.com/stripe/stripe-go/source.go create mode 100644 vendor/github.com/stripe/stripe-go/sourcetransaction.go create mode 100644 vendor/github.com/stripe/stripe-go/stripe.go create mode 100644 vendor/github.com/stripe/stripe-go/sub.go create mode 100644 vendor/github.com/stripe/stripe-go/subitem.go create mode 100644 vendor/github.com/stripe/stripe-go/subschedule.go create mode 100644 vendor/github.com/stripe/stripe-go/taxid.go create mode 100644 vendor/github.com/stripe/stripe-go/taxrate.go create mode 100644 vendor/github.com/stripe/stripe-go/terminal_connectiontoken.go create mode 100644 vendor/github.com/stripe/stripe-go/terminal_location.go create mode 100644 vendor/github.com/stripe/stripe-go/terminal_reader.go create mode 100644 vendor/github.com/stripe/stripe-go/threedsecure.go create mode 100644 vendor/github.com/stripe/stripe-go/token.go create mode 100644 vendor/github.com/stripe/stripe-go/topup.go create mode 100644 vendor/github.com/stripe/stripe-go/transfer.go create mode 100644 vendor/github.com/stripe/stripe-go/usagerecord.go create mode 100644 vendor/github.com/stripe/stripe-go/usagerecordsummary.go create mode 100644 vendor/github.com/stripe/stripe-go/v32_migration_guide.md create mode 100644 vendor/github.com/stripe/stripe-go/webhookendpoint.go create mode 100644 vendor/modules.txt diff --git a/.env b/.env index 0bd7272..2c09604 100644 --- a/.env +++ b/.env @@ -1,3 +1,4 @@ PORT=8080 TMPLDIR=views/templates/ -ConnectionString=user=nemausat dbname=godb sslmode=disable \ No newline at end of file +ConnectionString=user=nemausat dbname=godb sslmode=disable +DATABASE_URL=postgres://oshiervtwfrqrr:f177bc7ff355c142931aeb3f39ca7a6cc1b9e37594892f0e64d152b7a6f76657@ec2-50-17-178-87.compute-1.amazonaws.com:5432/ddidqb9rq8ta6m \ No newline at end of file diff --git a/main.go b/main.go index f0ce899..0b4c334 100644 --- a/main.go +++ b/main.go @@ -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) } diff --git a/vendor/github.com/joho/godotenv/.travis.yml b/vendor/github.com/joho/godotenv/.travis.yml new file mode 100644 index 0000000..f0db1ad --- /dev/null +++ b/vendor/github.com/joho/godotenv/.travis.yml @@ -0,0 +1,8 @@ +language: go + +go: + - 1.x + +os: + - linux + - osx diff --git a/vendor/github.com/joho/godotenv/LICENCE b/vendor/github.com/joho/godotenv/LICENCE new file mode 100644 index 0000000..e7ddd51 --- /dev/null +++ b/vendor/github.com/joho/godotenv/LICENCE @@ -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. + diff --git a/vendor/github.com/joho/godotenv/README.md b/vendor/github.com/joho/godotenv/README.md new file mode 100644 index 0000000..4e8fcf2 --- /dev/null +++ b/vendor/github.com/joho/godotenv/README.md @@ -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 environments–such as resource handles for databases or credentials for external services–should 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. diff --git a/vendor/github.com/joho/godotenv/godotenv.go b/vendor/github.com/joho/godotenv/godotenv.go new file mode 100644 index 0000000..29b436c --- /dev/null +++ b/vendor/github.com/joho/godotenv/godotenv.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/.travis.sh b/vendor/github.com/lib/pq/.travis.sh new file mode 100644 index 0000000..ebf4470 --- /dev/null +++ b/vendor/github.com/lib/pq/.travis.sh @@ -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 diff --git a/vendor/github.com/lib/pq/.travis.yml b/vendor/github.com/lib/pq/.travis.yml new file mode 100644 index 0000000..8396f5d --- /dev/null +++ b/vendor/github.com/lib/pq/.travis.yml @@ -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 ./... diff --git a/vendor/github.com/lib/pq/CONTRIBUTING.md b/vendor/github.com/lib/pq/CONTRIBUTING.md new file mode 100644 index 0000000..84c937f --- /dev/null +++ b/vendor/github.com/lib/pq/CONTRIBUTING.md @@ -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. diff --git a/vendor/github.com/lib/pq/LICENSE.md b/vendor/github.com/lib/pq/LICENSE.md new file mode 100644 index 0000000..5773904 --- /dev/null +++ b/vendor/github.com/lib/pq/LICENSE.md @@ -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. diff --git a/vendor/github.com/lib/pq/README.md b/vendor/github.com/lib/pq/README.md new file mode 100644 index 0000000..385fe73 --- /dev/null +++ b/vendor/github.com/lib/pq/README.md @@ -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 . + +## 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) diff --git a/vendor/github.com/lib/pq/TESTS.md b/vendor/github.com/lib/pq/TESTS.md new file mode 100644 index 0000000..f050211 --- /dev/null +++ b/vendor/github.com/lib/pq/TESTS.md @@ -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 +``` diff --git a/vendor/github.com/lib/pq/array.go b/vendor/github.com/lib/pq/array.go new file mode 100644 index 0000000..e4933e2 --- /dev/null +++ b/vendor/github.com/lib/pq/array.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/buf.go b/vendor/github.com/lib/pq/buf.go new file mode 100644 index 0000000..4b0a0a8 --- /dev/null +++ b/vendor/github.com/lib/pq/buf.go @@ -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) +} diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go new file mode 100644 index 0000000..55152b1 --- /dev/null +++ b/vendor/github.com/lib/pq/conn.go @@ -0,0 +1,1923 @@ +package pq + +import ( + "bufio" + "context" + "crypto/md5" + "crypto/sha256" + "database/sql" + "database/sql/driver" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "os" + "os/user" + "path" + "path/filepath" + "strconv" + "strings" + "time" + "unicode" + + "github.com/lib/pq/oid" + "github.com/lib/pq/scram" +) + +// Common error types +var ( + ErrNotSupported = errors.New("pq: Unsupported command") + ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction") + ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") + ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less") + ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly") + + errUnexpectedReady = errors.New("unexpected ReadyForQuery") + errNoRowsAffected = errors.New("no RowsAffected available after the empty statement") + errNoLastInsertID = errors.New("no LastInsertId available after the empty statement") +) + +// Driver is the Postgres database driver. +type Driver struct{} + +// Open opens a new connection to the database. name is a connection string. +// Most users should only use it through database/sql package from the standard +// library. +func (d *Driver) Open(name string) (driver.Conn, error) { + return Open(name) +} + +func init() { + sql.Register("postgres", &Driver{}) +} + +type parameterStatus struct { + // server version in the same format as server_version_num, or 0 if + // unavailable + serverVersion int + + // the current location based on the TimeZone value of the session, if + // available + currentLocation *time.Location +} + +type transactionStatus byte + +const ( + txnStatusIdle transactionStatus = 'I' + txnStatusIdleInTransaction transactionStatus = 'T' + txnStatusInFailedTransaction transactionStatus = 'E' +) + +func (s transactionStatus) String() string { + switch s { + case txnStatusIdle: + return "idle" + case txnStatusIdleInTransaction: + return "idle in transaction" + case txnStatusInFailedTransaction: + return "in a failed transaction" + default: + errorf("unknown transactionStatus %d", s) + } + + panic("not reached") +} + +// Dialer is the dialer interface. It can be used to obtain more control over +// how pq creates network connections. +type Dialer interface { + Dial(network, address string) (net.Conn, error) + DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) +} + +// DialerContext is the context-aware dialer interface. +type DialerContext interface { + DialContext(ctx context.Context, network, address string) (net.Conn, error) +} + +type defaultDialer struct { + d net.Dialer +} + +func (d defaultDialer) Dial(network, address string) (net.Conn, error) { + return d.d.Dial(network, address) +} +func (d defaultDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return d.DialContext(ctx, network, address) +} +func (d defaultDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { + return d.d.DialContext(ctx, network, address) +} + +type conn struct { + c net.Conn + buf *bufio.Reader + namei int + scratch [512]byte + txnStatus transactionStatus + txnFinish func() + + // Save connection arguments to use during CancelRequest. + dialer Dialer + opts values + + // Cancellation key data for use with CancelRequest messages. + processID int + secretKey int + + parameterStatus parameterStatus + + saveMessageType byte + saveMessageBuffer []byte + + // If true, this connection is bad and all public-facing functions should + // return ErrBadConn. + bad bool + + // If set, this connection should never use the binary format when + // receiving query results from prepared statements. Only provided for + // debugging. + disablePreparedBinaryResult bool + + // Whether to always send []byte parameters over as binary. Enables single + // round-trip mode for non-prepared Query calls. + binaryParameters bool + + // If true this connection is in the middle of a COPY + inCopy bool +} + +// Handle driver-side settings in parsed connection string. +func (cn *conn) handleDriverSettings(o values) (err error) { + boolSetting := func(key string, val *bool) error { + if value, ok := o[key]; ok { + if value == "yes" { + *val = true + } else if value == "no" { + *val = false + } else { + return fmt.Errorf("unrecognized value %q for %s", value, key) + } + } + return nil + } + + err = boolSetting("disable_prepared_binary_result", &cn.disablePreparedBinaryResult) + if err != nil { + return err + } + return boolSetting("binary_parameters", &cn.binaryParameters) +} + +func (cn *conn) handlePgpass(o values) { + // if a password was supplied, do not process .pgpass + if _, ok := o["password"]; ok { + return + } + filename := os.Getenv("PGPASSFILE") + if filename == "" { + // XXX this code doesn't work on Windows where the default filename is + // XXX %APPDATA%\postgresql\pgpass.conf + // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470 + userHome := os.Getenv("HOME") + if userHome == "" { + user, err := user.Current() + if err != nil { + return + } + userHome = user.HomeDir + } + filename = filepath.Join(userHome, ".pgpass") + } + fileinfo, err := os.Stat(filename) + if err != nil { + return + } + mode := fileinfo.Mode() + if mode&(0x77) != 0 { + // XXX should warn about incorrect .pgpass permissions as psql does + return + } + file, err := os.Open(filename) + if err != nil { + return + } + defer file.Close() + scanner := bufio.NewScanner(io.Reader(file)) + hostname := o["host"] + ntw, _ := network(o) + port := o["port"] + db := o["dbname"] + username := o["user"] + // From: https://github.com/tg/pgpass/blob/master/reader.go + getFields := func(s string) []string { + fs := make([]string, 0, 5) + f := make([]rune, 0, len(s)) + + var esc bool + for _, c := range s { + switch { + case esc: + f = append(f, c) + esc = false + case c == '\\': + esc = true + case c == ':': + fs = append(fs, string(f)) + f = f[:0] + default: + f = append(f, c) + } + } + return append(fs, string(f)) + } + for scanner.Scan() { + line := scanner.Text() + if len(line) == 0 || line[0] == '#' { + continue + } + split := getFields(line) + if len(split) != 5 { + continue + } + if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) { + o["password"] = split[4] + return + } + } +} + +func (cn *conn) writeBuf(b byte) *writeBuf { + cn.scratch[0] = b + return &writeBuf{ + buf: cn.scratch[:5], + pos: 1, + } +} + +// Open opens a new connection to the database. dsn is a connection string. +// Most users should only use it through database/sql package from the standard +// library. +func Open(dsn string) (_ driver.Conn, err error) { + return DialOpen(defaultDialer{}, dsn) +} + +// DialOpen opens a new connection to the database using a dialer. +func DialOpen(d Dialer, dsn string) (_ driver.Conn, err error) { + c, err := NewConnector(dsn) + if err != nil { + return nil, err + } + c.dialer = d + return c.open(context.Background()) +} + +func (c *Connector) open(ctx context.Context) (cn *conn, err error) { + // Handle any panics during connection initialization. Note that we + // specifically do *not* want to use errRecover(), as that would turn any + // connection errors into ErrBadConns, hiding the real error message from + // the user. + defer errRecoverNoErrBadConn(&err) + + o := c.opts + + cn = &conn{ + opts: o, + dialer: c.dialer, + } + err = cn.handleDriverSettings(o) + if err != nil { + return nil, err + } + cn.handlePgpass(o) + + cn.c, err = dial(ctx, c.dialer, o) + if err != nil { + return nil, err + } + + err = cn.ssl(o) + if err != nil { + if cn.c != nil { + cn.c.Close() + } + return nil, err + } + + // cn.startup panics on error. Make sure we don't leak cn.c. + panicking := true + defer func() { + if panicking { + cn.c.Close() + } + }() + + cn.buf = bufio.NewReader(cn.c) + cn.startup(o) + + // reset the deadline, in case one was set (see dial) + if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { + err = cn.c.SetDeadline(time.Time{}) + } + panicking = false + return cn, err +} + +func dial(ctx context.Context, d Dialer, o values) (net.Conn, error) { + network, address := network(o) + // SSL is not necessary or supported over UNIX domain sockets + if network == "unix" { + o["sslmode"] = "disable" + } + + // Zero or not specified means wait indefinitely. + if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { + seconds, err := strconv.ParseInt(timeout, 10, 0) + if err != nil { + return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err) + } + duration := time.Duration(seconds) * time.Second + + // connect_timeout should apply to the entire connection establishment + // procedure, so we both use a timeout for the TCP connection + // establishment and set a deadline for doing the initial handshake. + // The deadline is then reset after startup() is done. + deadline := time.Now().Add(duration) + var conn net.Conn + if dctx, ok := d.(DialerContext); ok { + ctx, cancel := context.WithTimeout(ctx, duration) + defer cancel() + conn, err = dctx.DialContext(ctx, network, address) + } else { + conn, err = d.DialTimeout(network, address, duration) + } + if err != nil { + return nil, err + } + err = conn.SetDeadline(deadline) + return conn, err + } + if dctx, ok := d.(DialerContext); ok { + return dctx.DialContext(ctx, network, address) + } + return d.Dial(network, address) +} + +func network(o values) (string, string) { + host := o["host"] + + if strings.HasPrefix(host, "/") { + sockPath := path.Join(host, ".s.PGSQL."+o["port"]) + return "unix", sockPath + } + + return "tcp", net.JoinHostPort(host, o["port"]) +} + +type values map[string]string + +// scanner implements a tokenizer for libpq-style option strings. +type scanner struct { + s []rune + i int +} + +// newScanner returns a new scanner initialized with the option string s. +func newScanner(s string) *scanner { + return &scanner{[]rune(s), 0} +} + +// Next returns the next rune. +// It returns 0, false if the end of the text has been reached. +func (s *scanner) Next() (rune, bool) { + if s.i >= len(s.s) { + return 0, false + } + r := s.s[s.i] + s.i++ + return r, true +} + +// SkipSpaces returns the next non-whitespace rune. +// It returns 0, false if the end of the text has been reached. +func (s *scanner) SkipSpaces() (rune, bool) { + r, ok := s.Next() + for unicode.IsSpace(r) && ok { + r, ok = s.Next() + } + return r, ok +} + +// parseOpts parses the options from name and adds them to the values. +// +// The parsing code is based on conninfo_parse from libpq's fe-connect.c +func parseOpts(name string, o values) error { + s := newScanner(name) + + for { + var ( + keyRunes, valRunes []rune + r rune + ok bool + ) + + if r, ok = s.SkipSpaces(); !ok { + break + } + + // Scan the key + for !unicode.IsSpace(r) && r != '=' { + keyRunes = append(keyRunes, r) + if r, ok = s.Next(); !ok { + break + } + } + + // Skip any whitespace if we're not at the = yet + if r != '=' { + r, ok = s.SkipSpaces() + } + + // The current character should be = + if r != '=' || !ok { + return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes)) + } + + // Skip any whitespace after the = + if r, ok = s.SkipSpaces(); !ok { + // If we reach the end here, the last value is just an empty string as per libpq. + o[string(keyRunes)] = "" + break + } + + if r != '\'' { + for !unicode.IsSpace(r) { + if r == '\\' { + if r, ok = s.Next(); !ok { + return fmt.Errorf(`missing character after backslash`) + } + } + valRunes = append(valRunes, r) + + if r, ok = s.Next(); !ok { + break + } + } + } else { + quote: + for { + if r, ok = s.Next(); !ok { + return fmt.Errorf(`unterminated quoted string literal in connection string`) + } + switch r { + case '\'': + break quote + case '\\': + r, _ = s.Next() + fallthrough + default: + valRunes = append(valRunes, r) + } + } + } + + o[string(keyRunes)] = string(valRunes) + } + + return nil +} + +func (cn *conn) isInTransaction() bool { + return cn.txnStatus == txnStatusIdleInTransaction || + cn.txnStatus == txnStatusInFailedTransaction +} + +func (cn *conn) checkIsInTransaction(intxn bool) { + if cn.isInTransaction() != intxn { + cn.bad = true + errorf("unexpected transaction status %v", cn.txnStatus) + } +} + +func (cn *conn) Begin() (_ driver.Tx, err error) { + return cn.begin("") +} + +func (cn *conn) begin(mode string) (_ driver.Tx, err error) { + if cn.bad { + return nil, driver.ErrBadConn + } + defer cn.errRecover(&err) + + cn.checkIsInTransaction(false) + _, commandTag, err := cn.simpleExec("BEGIN" + mode) + if err != nil { + return nil, err + } + if commandTag != "BEGIN" { + cn.bad = true + return nil, fmt.Errorf("unexpected command tag %s", commandTag) + } + if cn.txnStatus != txnStatusIdleInTransaction { + cn.bad = true + return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus) + } + return cn, nil +} + +func (cn *conn) closeTxn() { + if finish := cn.txnFinish; finish != nil { + finish() + } +} + +func (cn *conn) Commit() (err error) { + defer cn.closeTxn() + if cn.bad { + return driver.ErrBadConn + } + defer cn.errRecover(&err) + + cn.checkIsInTransaction(true) + // We don't want the client to think that everything is okay if it tries + // to commit a failed transaction. However, no matter what we return, + // database/sql will release this connection back into the free connection + // pool so we have to abort the current transaction here. Note that you + // would get the same behaviour if you issued a COMMIT in a failed + // transaction, so it's also the least surprising thing to do here. + if cn.txnStatus == txnStatusInFailedTransaction { + if err := cn.rollback(); err != nil { + return err + } + return ErrInFailedTransaction + } + + _, commandTag, err := cn.simpleExec("COMMIT") + if err != nil { + if cn.isInTransaction() { + cn.bad = true + } + return err + } + if commandTag != "COMMIT" { + cn.bad = true + return fmt.Errorf("unexpected command tag %s", commandTag) + } + cn.checkIsInTransaction(false) + return nil +} + +func (cn *conn) Rollback() (err error) { + defer cn.closeTxn() + if cn.bad { + return driver.ErrBadConn + } + defer cn.errRecover(&err) + return cn.rollback() +} + +func (cn *conn) rollback() (err error) { + cn.checkIsInTransaction(true) + _, commandTag, err := cn.simpleExec("ROLLBACK") + if err != nil { + if cn.isInTransaction() { + cn.bad = true + } + return err + } + if commandTag != "ROLLBACK" { + return fmt.Errorf("unexpected command tag %s", commandTag) + } + cn.checkIsInTransaction(false) + return nil +} + +func (cn *conn) gname() string { + cn.namei++ + return strconv.FormatInt(int64(cn.namei), 10) +} + +func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) { + b := cn.writeBuf('Q') + b.string(q) + cn.send(b) + + for { + t, r := cn.recv1() + switch t { + case 'C': + res, commandTag = cn.parseComplete(r.string()) + case 'Z': + cn.processReadyForQuery(r) + if res == nil && err == nil { + err = errUnexpectedReady + } + // done + return + case 'E': + err = parseError(r) + case 'I': + res = emptyRows + case 'T', 'D': + // ignore any results + default: + cn.bad = true + errorf("unknown response for simple query: %q", t) + } + } +} + +func (cn *conn) simpleQuery(q string) (res *rows, err error) { + defer cn.errRecover(&err) + + b := cn.writeBuf('Q') + b.string(q) + cn.send(b) + + for { + t, r := cn.recv1() + switch t { + case 'C', 'I': + // We allow queries which don't return any results through Query as + // well as Exec. We still have to give database/sql a rows object + // the user can close, though, to avoid connections from being + // leaked. A "rows" with done=true works fine for that purpose. + if err != nil { + cn.bad = true + errorf("unexpected message %q in simple query execution", t) + } + if res == nil { + res = &rows{ + cn: cn, + } + } + // Set the result and tag to the last command complete if there wasn't a + // query already run. Although queries usually return from here and cede + // control to Next, a query with zero results does not. + if t == 'C' && res.colNames == nil { + res.result, res.tag = cn.parseComplete(r.string()) + } + res.done = true + case 'Z': + cn.processReadyForQuery(r) + // done + return + case 'E': + res = nil + err = parseError(r) + case 'D': + if res == nil { + cn.bad = true + errorf("unexpected DataRow in simple query execution") + } + // the query didn't fail; kick off to Next + cn.saveMessage(t, r) + return + case 'T': + // res might be non-nil here if we received a previous + // CommandComplete, but that's fine; just overwrite it + res = &rows{cn: cn} + res.rowsHeader = parsePortalRowDescribe(r) + + // To work around a bug in QueryRow in Go 1.2 and earlier, wait + // until the first DataRow has been received. + default: + cn.bad = true + errorf("unknown response for simple query: %q", t) + } + } +} + +type noRows struct{} + +var emptyRows noRows + +var _ driver.Result = noRows{} + +func (noRows) LastInsertId() (int64, error) { + return 0, errNoLastInsertID +} + +func (noRows) RowsAffected() (int64, error) { + return 0, errNoRowsAffected +} + +// Decides which column formats to use for a prepared statement. The input is +// an array of type oids, one element per result column. +func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte) { + if len(colTyps) == 0 { + return nil, colFmtDataAllText + } + + colFmts = make([]format, len(colTyps)) + if forceText { + return colFmts, colFmtDataAllText + } + + allBinary := true + allText := true + for i, t := range colTyps { + switch t.OID { + // This is the list of types to use binary mode for when receiving them + // through a prepared statement. If a type appears in this list, it + // must also be implemented in binaryDecode in encode.go. + case oid.T_bytea: + fallthrough + case oid.T_int8: + fallthrough + case oid.T_int4: + fallthrough + case oid.T_int2: + fallthrough + case oid.T_uuid: + colFmts[i] = formatBinary + allText = false + + default: + allBinary = false + } + } + + if allBinary { + return colFmts, colFmtDataAllBinary + } else if allText { + return colFmts, colFmtDataAllText + } else { + colFmtData = make([]byte, 2+len(colFmts)*2) + binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts))) + for i, v := range colFmts { + binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v)) + } + return colFmts, colFmtData + } +} + +func (cn *conn) prepareTo(q, stmtName string) *stmt { + st := &stmt{cn: cn, name: stmtName} + + b := cn.writeBuf('P') + b.string(st.name) + b.string(q) + b.int16(0) + + b.next('D') + b.byte('S') + b.string(st.name) + + b.next('S') + cn.send(b) + + cn.readParseResponse() + st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse() + st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult) + cn.readReadyForQuery() + return st +} + +func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) { + if cn.bad { + return nil, driver.ErrBadConn + } + defer cn.errRecover(&err) + + if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") { + s, err := cn.prepareCopyIn(q) + if err == nil { + cn.inCopy = true + } + return s, err + } + return cn.prepareTo(q, cn.gname()), nil +} + +func (cn *conn) Close() (err error) { + // Skip cn.bad return here because we always want to close a connection. + defer cn.errRecover(&err) + + // Ensure that cn.c.Close is always run. Since error handling is done with + // panics and cn.errRecover, the Close must be in a defer. + defer func() { + cerr := cn.c.Close() + if err == nil { + err = cerr + } + }() + + // Don't go through send(); ListenerConn relies on us not scribbling on the + // scratch buffer of this connection. + return cn.sendSimpleMessage('X') +} + +// Implement the "Queryer" interface +func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) { + return cn.query(query, args) +} + +func (cn *conn) query(query string, args []driver.Value) (_ *rows, err error) { + if cn.bad { + return nil, driver.ErrBadConn + } + if cn.inCopy { + return nil, errCopyInProgress + } + defer cn.errRecover(&err) + + // Check to see if we can use the "simpleQuery" interface, which is + // *much* faster than going through prepare/exec + if len(args) == 0 { + return cn.simpleQuery(query) + } + + if cn.binaryParameters { + cn.sendBinaryModeQuery(query, args) + + cn.readParseResponse() + cn.readBindResponse() + rows := &rows{cn: cn} + rows.rowsHeader = cn.readPortalDescribeResponse() + cn.postExecuteWorkaround() + return rows, nil + } + st := cn.prepareTo(query, "") + st.exec(args) + return &rows{ + cn: cn, + rowsHeader: st.rowsHeader, + }, nil +} + +// Implement the optional "Execer" interface for one-shot queries +func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) { + if cn.bad { + return nil, driver.ErrBadConn + } + defer cn.errRecover(&err) + + // Check to see if we can use the "simpleExec" interface, which is + // *much* faster than going through prepare/exec + if len(args) == 0 { + // ignore commandTag, our caller doesn't care + r, _, err := cn.simpleExec(query) + return r, err + } + + if cn.binaryParameters { + cn.sendBinaryModeQuery(query, args) + + cn.readParseResponse() + cn.readBindResponse() + cn.readPortalDescribeResponse() + cn.postExecuteWorkaround() + res, _, err = cn.readExecuteResponse("Execute") + return res, err + } + // Use the unnamed statement to defer planning until bind + // time, or else value-based selectivity estimates cannot be + // used. + st := cn.prepareTo(query, "") + r, err := st.Exec(args) + if err != nil { + panic(err) + } + return r, err +} + +func (cn *conn) send(m *writeBuf) { + _, err := cn.c.Write(m.wrap()) + if err != nil { + panic(err) + } +} + +func (cn *conn) sendStartupPacket(m *writeBuf) error { + _, err := cn.c.Write((m.wrap())[1:]) + return err +} + +// Send a message of type typ to the server on the other end of cn. The +// message should have no payload. This method does not use the scratch +// buffer. +func (cn *conn) sendSimpleMessage(typ byte) (err error) { + _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'}) + return err +} + +// saveMessage memorizes a message and its buffer in the conn struct. +// recvMessage will then return these values on the next call to it. This +// method is useful in cases where you have to see what the next message is +// going to be (e.g. to see whether it's an error or not) but you can't handle +// the message yourself. +func (cn *conn) saveMessage(typ byte, buf *readBuf) { + if cn.saveMessageType != 0 { + cn.bad = true + errorf("unexpected saveMessageType %d", cn.saveMessageType) + } + cn.saveMessageType = typ + cn.saveMessageBuffer = *buf +} + +// recvMessage receives any message from the backend, or returns an error if +// a problem occurred while reading the message. +func (cn *conn) recvMessage(r *readBuf) (byte, error) { + // workaround for a QueryRow bug, see exec + if cn.saveMessageType != 0 { + t := cn.saveMessageType + *r = cn.saveMessageBuffer + cn.saveMessageType = 0 + cn.saveMessageBuffer = nil + return t, nil + } + + x := cn.scratch[:5] + _, err := io.ReadFull(cn.buf, x) + if err != nil { + return 0, err + } + + // read the type and length of the message that follows + t := x[0] + n := int(binary.BigEndian.Uint32(x[1:])) - 4 + var y []byte + if n <= len(cn.scratch) { + y = cn.scratch[:n] + } else { + y = make([]byte, n) + } + _, err = io.ReadFull(cn.buf, y) + if err != nil { + return 0, err + } + *r = y + return t, nil +} + +// recv receives a message from the backend, but if an error happened while +// reading the message or the received message was an ErrorResponse, it panics. +// NoticeResponses are ignored. This function should generally be used only +// during the startup sequence. +func (cn *conn) recv() (t byte, r *readBuf) { + for { + var err error + r = &readBuf{} + t, err = cn.recvMessage(r) + if err != nil { + panic(err) + } + switch t { + case 'E': + panic(parseError(r)) + case 'N': + // ignore + default: + return + } + } +} + +// recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by +// the caller to avoid an allocation. +func (cn *conn) recv1Buf(r *readBuf) byte { + for { + t, err := cn.recvMessage(r) + if err != nil { + panic(err) + } + + switch t { + case 'A', 'N': + // ignore + case 'S': + cn.processParameterStatus(r) + default: + return t + } + } +} + +// recv1 receives a message from the backend, panicking if an error occurs +// while attempting to read it. All asynchronous messages are ignored, with +// the exception of ErrorResponse. +func (cn *conn) recv1() (t byte, r *readBuf) { + r = &readBuf{} + t = cn.recv1Buf(r) + return t, r +} + +func (cn *conn) ssl(o values) error { + upgrade, err := ssl(o) + if err != nil { + return err + } + + if upgrade == nil { + // Nothing to do + return nil + } + + w := cn.writeBuf(0) + w.int32(80877103) + if err = cn.sendStartupPacket(w); err != nil { + return err + } + + b := cn.scratch[:1] + _, err = io.ReadFull(cn.c, b) + if err != nil { + return err + } + + if b[0] != 'S' { + return ErrSSLNotSupported + } + + cn.c, err = upgrade(cn.c) + return err +} + +// isDriverSetting returns true iff a setting is purely for configuring the +// driver's options and should not be sent to the server in the connection +// startup packet. +func isDriverSetting(key string) bool { + switch key { + case "host", "port": + return true + case "password": + return true + case "sslmode", "sslcert", "sslkey", "sslrootcert": + return true + case "fallback_application_name": + return true + case "connect_timeout": + return true + case "disable_prepared_binary_result": + return true + case "binary_parameters": + return true + + default: + return false + } +} + +func (cn *conn) startup(o values) { + w := cn.writeBuf(0) + w.int32(196608) + // Send the backend the name of the database we want to connect to, and the + // user we want to connect as. Additionally, we send over any run-time + // parameters potentially included in the connection string. If the server + // doesn't recognize any of them, it will reply with an error. + for k, v := range o { + if isDriverSetting(k) { + // skip options which can't be run-time parameters + continue + } + // The protocol requires us to supply the database name as "database" + // instead of "dbname". + if k == "dbname" { + k = "database" + } + w.string(k) + w.string(v) + } + w.string("") + if err := cn.sendStartupPacket(w); err != nil { + panic(err) + } + + for { + t, r := cn.recv() + switch t { + case 'K': + cn.processBackendKeyData(r) + case 'S': + cn.processParameterStatus(r) + case 'R': + cn.auth(r, o) + case 'Z': + cn.processReadyForQuery(r) + return + default: + errorf("unknown response for startup: %q", t) + } + } +} + +func (cn *conn) auth(r *readBuf, o values) { + switch code := r.int32(); code { + case 0: + // OK + case 3: + w := cn.writeBuf('p') + w.string(o["password"]) + cn.send(w) + + t, r := cn.recv() + if t != 'R' { + errorf("unexpected password response: %q", t) + } + + if r.int32() != 0 { + errorf("unexpected authentication response: %q", t) + } + case 5: + s := string(r.next(4)) + w := cn.writeBuf('p') + w.string("md5" + md5s(md5s(o["password"]+o["user"])+s)) + cn.send(w) + + t, r := cn.recv() + if t != 'R' { + errorf("unexpected password response: %q", t) + } + + if r.int32() != 0 { + errorf("unexpected authentication response: %q", t) + } + case 10: + sc := scram.NewClient(sha256.New, o["user"], o["password"]) + sc.Step(nil) + if sc.Err() != nil { + errorf("SCRAM-SHA-256 error: %s", sc.Err().Error()) + } + scOut := sc.Out() + + w := cn.writeBuf('p') + w.string("SCRAM-SHA-256") + w.int32(len(scOut)) + w.bytes(scOut) + cn.send(w) + + t, r := cn.recv() + if t != 'R' { + errorf("unexpected password response: %q", t) + } + + if r.int32() != 11 { + errorf("unexpected authentication response: %q", t) + } + + nextStep := r.next(len(*r)) + sc.Step(nextStep) + if sc.Err() != nil { + errorf("SCRAM-SHA-256 error: %s", sc.Err().Error()) + } + + scOut = sc.Out() + w = cn.writeBuf('p') + w.bytes(scOut) + cn.send(w) + + t, r = cn.recv() + if t != 'R' { + errorf("unexpected password response: %q", t) + } + + if r.int32() != 12 { + errorf("unexpected authentication response: %q", t) + } + + nextStep = r.next(len(*r)) + sc.Step(nextStep) + if sc.Err() != nil { + errorf("SCRAM-SHA-256 error: %s", sc.Err().Error()) + } + + default: + errorf("unknown authentication response: %d", code) + } +} + +type format int + +const formatText format = 0 +const formatBinary format = 1 + +// One result-column format code with the value 1 (i.e. all binary). +var colFmtDataAllBinary = []byte{0, 1, 0, 1} + +// No result-column format codes (i.e. all text). +var colFmtDataAllText = []byte{0, 0} + +type stmt struct { + cn *conn + name string + rowsHeader + colFmtData []byte + paramTyps []oid.Oid + closed bool +} + +func (st *stmt) Close() (err error) { + if st.closed { + return nil + } + if st.cn.bad { + return driver.ErrBadConn + } + defer st.cn.errRecover(&err) + + w := st.cn.writeBuf('C') + w.byte('S') + w.string(st.name) + st.cn.send(w) + + st.cn.send(st.cn.writeBuf('S')) + + t, _ := st.cn.recv1() + if t != '3' { + st.cn.bad = true + errorf("unexpected close response: %q", t) + } + st.closed = true + + t, r := st.cn.recv1() + if t != 'Z' { + st.cn.bad = true + errorf("expected ready for query, but got: %q", t) + } + st.cn.processReadyForQuery(r) + + return nil +} + +func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { + if st.cn.bad { + return nil, driver.ErrBadConn + } + defer st.cn.errRecover(&err) + + st.exec(v) + return &rows{ + cn: st.cn, + rowsHeader: st.rowsHeader, + }, nil +} + +func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) { + if st.cn.bad { + return nil, driver.ErrBadConn + } + defer st.cn.errRecover(&err) + + st.exec(v) + res, _, err = st.cn.readExecuteResponse("simple query") + return res, err +} + +func (st *stmt) exec(v []driver.Value) { + if len(v) >= 65536 { + errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v)) + } + if len(v) != len(st.paramTyps) { + errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps)) + } + + cn := st.cn + w := cn.writeBuf('B') + w.byte(0) // unnamed portal + w.string(st.name) + + if cn.binaryParameters { + cn.sendBinaryParameters(w, v) + } else { + w.int16(0) + w.int16(len(v)) + for i, x := range v { + if x == nil { + w.int32(-1) + } else { + b := encode(&cn.parameterStatus, x, st.paramTyps[i]) + w.int32(len(b)) + w.bytes(b) + } + } + } + w.bytes(st.colFmtData) + + w.next('E') + w.byte(0) + w.int32(0) + + w.next('S') + cn.send(w) + + cn.readBindResponse() + cn.postExecuteWorkaround() + +} + +func (st *stmt) NumInput() int { + return len(st.paramTyps) +} + +// parseComplete parses the "command tag" from a CommandComplete message, and +// returns the number of rows affected (if applicable) and a string +// identifying only the command that was executed, e.g. "ALTER TABLE". If the +// command tag could not be parsed, parseComplete panics. +func (cn *conn) parseComplete(commandTag string) (driver.Result, string) { + commandsWithAffectedRows := []string{ + "SELECT ", + // INSERT is handled below + "UPDATE ", + "DELETE ", + "FETCH ", + "MOVE ", + "COPY ", + } + + var affectedRows *string + for _, tag := range commandsWithAffectedRows { + if strings.HasPrefix(commandTag, tag) { + t := commandTag[len(tag):] + affectedRows = &t + commandTag = tag[:len(tag)-1] + break + } + } + // INSERT also includes the oid of the inserted row in its command tag. + // Oids in user tables are deprecated, and the oid is only returned when + // exactly one row is inserted, so it's unlikely to be of value to any + // real-world application and we can ignore it. + if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") { + parts := strings.Split(commandTag, " ") + if len(parts) != 3 { + cn.bad = true + errorf("unexpected INSERT command tag %s", commandTag) + } + affectedRows = &parts[len(parts)-1] + commandTag = "INSERT" + } + // There should be no affected rows attached to the tag, just return it + if affectedRows == nil { + return driver.RowsAffected(0), commandTag + } + n, err := strconv.ParseInt(*affectedRows, 10, 64) + if err != nil { + cn.bad = true + errorf("could not parse commandTag: %s", err) + } + return driver.RowsAffected(n), commandTag +} + +type rowsHeader struct { + colNames []string + colTyps []fieldDesc + colFmts []format +} + +type rows struct { + cn *conn + finish func() + rowsHeader + done bool + rb readBuf + result driver.Result + tag string + + next *rowsHeader +} + +func (rs *rows) Close() error { + if finish := rs.finish; finish != nil { + defer finish() + } + // no need to look at cn.bad as Next() will + for { + err := rs.Next(nil) + switch err { + case nil: + case io.EOF: + // rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row + // description, used with HasNextResultSet). We need to fetch messages until + // we hit a 'Z', which is done by waiting for done to be set. + if rs.done { + return nil + } + default: + return err + } + } +} + +func (rs *rows) Columns() []string { + return rs.colNames +} + +func (rs *rows) Result() driver.Result { + if rs.result == nil { + return emptyRows + } + return rs.result +} + +func (rs *rows) Tag() string { + return rs.tag +} + +func (rs *rows) Next(dest []driver.Value) (err error) { + if rs.done { + return io.EOF + } + + conn := rs.cn + if conn.bad { + return driver.ErrBadConn + } + defer conn.errRecover(&err) + + for { + t := conn.recv1Buf(&rs.rb) + switch t { + case 'E': + err = parseError(&rs.rb) + case 'C', 'I': + if t == 'C' { + rs.result, rs.tag = conn.parseComplete(rs.rb.string()) + } + continue + case 'Z': + conn.processReadyForQuery(&rs.rb) + rs.done = true + if err != nil { + return err + } + return io.EOF + case 'D': + n := rs.rb.int16() + if err != nil { + conn.bad = true + errorf("unexpected DataRow after error %s", err) + } + if n < len(dest) { + dest = dest[:n] + } + for i := range dest { + l := rs.rb.int32() + if l == -1 { + dest[i] = nil + continue + } + dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i]) + } + return + case 'T': + next := parsePortalRowDescribe(&rs.rb) + rs.next = &next + return io.EOF + default: + errorf("unexpected message after execute: %q", t) + } + } +} + +func (rs *rows) HasNextResultSet() bool { + hasNext := rs.next != nil && !rs.done + return hasNext +} + +func (rs *rows) NextResultSet() error { + if rs.next == nil { + return io.EOF + } + rs.rowsHeader = *rs.next + rs.next = nil + return nil +} + +// QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be +// used as part of an SQL statement. For example: +// +// tblname := "my_table" +// data := "my_data" +// quoted := pq.QuoteIdentifier(tblname) +// err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data) +// +// Any double quotes in name will be escaped. The quoted identifier will be +// case sensitive when used in a query. If the input string contains a zero +// byte, the result will be truncated immediately before it. +func QuoteIdentifier(name string) string { + end := strings.IndexRune(name, 0) + if end > -1 { + name = name[:end] + } + return `"` + strings.Replace(name, `"`, `""`, -1) + `"` +} + +// QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literal +// to DDL and other statements that do not accept parameters) to be used as part +// of an SQL statement. For example: +// +// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z") +// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date)) +// +// Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be +// replaced by two backslashes (i.e. "\\") and the C-style escape identifier +// that PostgreSQL provides ('E') will be prepended to the string. +func QuoteLiteral(literal string) string { + // This follows the PostgreSQL internal algorithm for handling quoted literals + // from libpq, which can be found in the "PQEscapeStringInternal" function, + // which is found in the libpq/fe-exec.c source file: + // https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/interfaces/libpq/fe-exec.c + // + // substitute any single-quotes (') with two single-quotes ('') + literal = strings.Replace(literal, `'`, `''`, -1) + // determine if the string has any backslashes (\) in it. + // if it does, replace any backslashes (\) with two backslashes (\\) + // then, we need to wrap the entire string with a PostgreSQL + // C-style escape. Per how "PQEscapeStringInternal" handles this case, we + // also add a space before the "E" + if strings.Contains(literal, `\`) { + literal = strings.Replace(literal, `\`, `\\`, -1) + literal = ` E'` + literal + `'` + } else { + // otherwise, we can just wrap the literal with a pair of single quotes + literal = `'` + literal + `'` + } + return literal +} + +func md5s(s string) string { + h := md5.New() + h.Write([]byte(s)) + return fmt.Sprintf("%x", h.Sum(nil)) +} + +func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) { + // Do one pass over the parameters to see if we're going to send any of + // them over in binary. If we are, create a paramFormats array at the + // same time. + var paramFormats []int + for i, x := range args { + _, ok := x.([]byte) + if ok { + if paramFormats == nil { + paramFormats = make([]int, len(args)) + } + paramFormats[i] = 1 + } + } + if paramFormats == nil { + b.int16(0) + } else { + b.int16(len(paramFormats)) + for _, x := range paramFormats { + b.int16(x) + } + } + + b.int16(len(args)) + for _, x := range args { + if x == nil { + b.int32(-1) + } else { + datum := binaryEncode(&cn.parameterStatus, x) + b.int32(len(datum)) + b.bytes(datum) + } + } +} + +func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) { + if len(args) >= 65536 { + errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args)) + } + + b := cn.writeBuf('P') + b.byte(0) // unnamed statement + b.string(query) + b.int16(0) + + b.next('B') + b.int16(0) // unnamed portal and statement + cn.sendBinaryParameters(b, args) + b.bytes(colFmtDataAllText) + + b.next('D') + b.byte('P') + b.byte(0) // unnamed portal + + b.next('E') + b.byte(0) + b.int32(0) + + b.next('S') + cn.send(b) +} + +func (cn *conn) processParameterStatus(r *readBuf) { + var err error + + param := r.string() + switch param { + case "server_version": + var major1 int + var major2 int + var minor int + _, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor) + if err == nil { + cn.parameterStatus.serverVersion = major1*10000 + major2*100 + minor + } + + case "TimeZone": + cn.parameterStatus.currentLocation, err = time.LoadLocation(r.string()) + if err != nil { + cn.parameterStatus.currentLocation = nil + } + + default: + // ignore + } +} + +func (cn *conn) processReadyForQuery(r *readBuf) { + cn.txnStatus = transactionStatus(r.byte()) +} + +func (cn *conn) readReadyForQuery() { + t, r := cn.recv1() + switch t { + case 'Z': + cn.processReadyForQuery(r) + return + default: + cn.bad = true + errorf("unexpected message %q; expected ReadyForQuery", t) + } +} + +func (cn *conn) processBackendKeyData(r *readBuf) { + cn.processID = r.int32() + cn.secretKey = r.int32() +} + +func (cn *conn) readParseResponse() { + t, r := cn.recv1() + switch t { + case '1': + return + case 'E': + err := parseError(r) + cn.readReadyForQuery() + panic(err) + default: + cn.bad = true + errorf("unexpected Parse response %q", t) + } +} + +func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []fieldDesc) { + for { + t, r := cn.recv1() + switch t { + case 't': + nparams := r.int16() + paramTyps = make([]oid.Oid, nparams) + for i := range paramTyps { + paramTyps[i] = r.oid() + } + case 'n': + return paramTyps, nil, nil + case 'T': + colNames, colTyps = parseStatementRowDescribe(r) + return paramTyps, colNames, colTyps + case 'E': + err := parseError(r) + cn.readReadyForQuery() + panic(err) + default: + cn.bad = true + errorf("unexpected Describe statement response %q", t) + } + } +} + +func (cn *conn) readPortalDescribeResponse() rowsHeader { + t, r := cn.recv1() + switch t { + case 'T': + return parsePortalRowDescribe(r) + case 'n': + return rowsHeader{} + case 'E': + err := parseError(r) + cn.readReadyForQuery() + panic(err) + default: + cn.bad = true + errorf("unexpected Describe response %q", t) + } + panic("not reached") +} + +func (cn *conn) readBindResponse() { + t, r := cn.recv1() + switch t { + case '2': + return + case 'E': + err := parseError(r) + cn.readReadyForQuery() + panic(err) + default: + cn.bad = true + errorf("unexpected Bind response %q", t) + } +} + +func (cn *conn) postExecuteWorkaround() { + // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores + // any errors from rows.Next, which masks errors that happened during the + // execution of the query. To avoid the problem in common cases, we wait + // here for one more message from the database. If it's not an error the + // query will likely succeed (or perhaps has already, if it's a + // CommandComplete), so we push the message into the conn struct; recv1 + // will return it as the next message for rows.Next or rows.Close. + // However, if it's an error, we wait until ReadyForQuery and then return + // the error to our caller. + for { + t, r := cn.recv1() + switch t { + case 'E': + err := parseError(r) + cn.readReadyForQuery() + panic(err) + case 'C', 'D', 'I': + // the query didn't fail, but we can't process this message + cn.saveMessage(t, r) + return + default: + cn.bad = true + errorf("unexpected message during extended query execution: %q", t) + } + } +} + +// Only for Exec(), since we ignore the returned data +func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) { + for { + t, r := cn.recv1() + switch t { + case 'C': + if err != nil { + cn.bad = true + errorf("unexpected CommandComplete after error %s", err) + } + res, commandTag = cn.parseComplete(r.string()) + case 'Z': + cn.processReadyForQuery(r) + if res == nil && err == nil { + err = errUnexpectedReady + } + return res, commandTag, err + case 'E': + err = parseError(r) + case 'T', 'D', 'I': + if err != nil { + cn.bad = true + errorf("unexpected %q after error %s", t, err) + } + if t == 'I' { + res = emptyRows + } + // ignore any results + default: + cn.bad = true + errorf("unknown %s response: %q", protocolState, t) + } + } +} + +func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) { + n := r.int16() + colNames = make([]string, n) + colTyps = make([]fieldDesc, n) + for i := range colNames { + colNames[i] = r.string() + r.next(6) + colTyps[i].OID = r.oid() + colTyps[i].Len = r.int16() + colTyps[i].Mod = r.int32() + // format code not known when describing a statement; always 0 + r.next(2) + } + return +} + +func parsePortalRowDescribe(r *readBuf) rowsHeader { + n := r.int16() + colNames := make([]string, n) + colFmts := make([]format, n) + colTyps := make([]fieldDesc, n) + for i := range colNames { + colNames[i] = r.string() + r.next(6) + colTyps[i].OID = r.oid() + colTyps[i].Len = r.int16() + colTyps[i].Mod = r.int32() + colFmts[i] = format(r.int16()) + } + return rowsHeader{ + colNames: colNames, + colFmts: colFmts, + colTyps: colTyps, + } +} + +// parseEnviron tries to mimic some of libpq's environment handling +// +// To ease testing, it does not directly reference os.Environ, but is +// designed to accept its output. +// +// Environment-set connection information is intended to have a higher +// precedence than a library default but lower than any explicitly +// passed information (such as in the URL or connection string). +func parseEnviron(env []string) (out map[string]string) { + out = make(map[string]string) + + for _, v := range env { + parts := strings.SplitN(v, "=", 2) + + accrue := func(keyname string) { + out[keyname] = parts[1] + } + unsupported := func() { + panic(fmt.Sprintf("setting %v not supported", parts[0])) + } + + // The order of these is the same as is seen in the + // PostgreSQL 9.1 manual. Unsupported but well-defined + // keys cause a panic; these should be unset prior to + // execution. Options which pq expects to be set to a + // certain value are allowed, but must be set to that + // value if present (they can, of course, be absent). + switch parts[0] { + case "PGHOST": + accrue("host") + case "PGHOSTADDR": + unsupported() + case "PGPORT": + accrue("port") + case "PGDATABASE": + accrue("dbname") + case "PGUSER": + accrue("user") + case "PGPASSWORD": + accrue("password") + case "PGSERVICE", "PGSERVICEFILE", "PGREALM": + unsupported() + case "PGOPTIONS": + accrue("options") + case "PGAPPNAME": + accrue("application_name") + case "PGSSLMODE": + accrue("sslmode") + case "PGSSLCERT": + accrue("sslcert") + case "PGSSLKEY": + accrue("sslkey") + case "PGSSLROOTCERT": + accrue("sslrootcert") + case "PGREQUIRESSL", "PGSSLCRL": + unsupported() + case "PGREQUIREPEER": + unsupported() + case "PGKRBSRVNAME", "PGGSSLIB": + unsupported() + case "PGCONNECT_TIMEOUT": + accrue("connect_timeout") + case "PGCLIENTENCODING": + accrue("client_encoding") + case "PGDATESTYLE": + accrue("datestyle") + case "PGTZ": + accrue("timezone") + case "PGGEQO": + accrue("geqo") + case "PGSYSCONFDIR", "PGLOCALEDIR": + unsupported() + } + } + + return out +} + +// isUTF8 returns whether name is a fuzzy variation of the string "UTF-8". +func isUTF8(name string) bool { + // Recognize all sorts of silly things as "UTF-8", like Postgres does + s := strings.Map(alnumLowerASCII, name) + return s == "utf8" || s == "unicode" +} + +func alnumLowerASCII(ch rune) rune { + if 'A' <= ch && ch <= 'Z' { + return ch + ('a' - 'A') + } + if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' { + return ch + } + return -1 // discard +} diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go new file mode 100644 index 0000000..09e2ea4 --- /dev/null +++ b/vendor/github.com/lib/pq/conn_go18.go @@ -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 + } +} diff --git a/vendor/github.com/lib/pq/connector.go b/vendor/github.com/lib/pq/connector.go new file mode 100644 index 0000000..2f8ced6 --- /dev/null +++ b/vendor/github.com/lib/pq/connector.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/copy.go b/vendor/github.com/lib/pq/copy.go new file mode 100644 index 0000000..55378d5 --- /dev/null +++ b/vendor/github.com/lib/pq/copy.go @@ -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 := ©in{ + 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 +} diff --git a/vendor/github.com/lib/pq/doc.go b/vendor/github.com/lib/pq/doc.go new file mode 100644 index 0000000..2a60054 --- /dev/null +++ b/vendor/github.com/lib/pq/doc.go @@ -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 diff --git a/vendor/github.com/lib/pq/encode.go b/vendor/github.com/lib/pq/encode.go new file mode 100644 index 0000000..73cafb8 --- /dev/null +++ b/vendor/github.com/lib/pq/encode.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/error.go b/vendor/github.com/lib/pq/error.go new file mode 100644 index 0000000..3d66ba7 --- /dev/null +++ b/vendor/github.com/lib/pq/error.go @@ -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 + } +} diff --git a/vendor/github.com/lib/pq/go.mod b/vendor/github.com/lib/pq/go.mod new file mode 100644 index 0000000..edf0b34 --- /dev/null +++ b/vendor/github.com/lib/pq/go.mod @@ -0,0 +1 @@ +module github.com/lib/pq diff --git a/vendor/github.com/lib/pq/notify.go b/vendor/github.com/lib/pq/notify.go new file mode 100644 index 0000000..850bb90 --- /dev/null +++ b/vendor/github.com/lib/pq/notify.go @@ -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) +} diff --git a/vendor/github.com/lib/pq/oid/doc.go b/vendor/github.com/lib/pq/oid/doc.go new file mode 100644 index 0000000..caaede2 --- /dev/null +++ b/vendor/github.com/lib/pq/oid/doc.go @@ -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 diff --git a/vendor/github.com/lib/pq/oid/types.go b/vendor/github.com/lib/pq/oid/types.go new file mode 100644 index 0000000..ecc84c2 --- /dev/null +++ b/vendor/github.com/lib/pq/oid/types.go @@ -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", +} diff --git a/vendor/github.com/lib/pq/rows.go b/vendor/github.com/lib/pq/rows.go new file mode 100644 index 0000000..c6aa5b9 --- /dev/null +++ b/vendor/github.com/lib/pq/rows.go @@ -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() +} diff --git a/vendor/github.com/lib/pq/scram/scram.go b/vendor/github.com/lib/pq/scram/scram.go new file mode 100644 index 0000000..477216b --- /dev/null +++ b/vendor/github.com/lib/pq/scram/scram.go @@ -0,0 +1,264 @@ +// Copyright (c) 2014 - Gustavo Niemeyer +// +// 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 +} diff --git a/vendor/github.com/lib/pq/ssl.go b/vendor/github.com/lib/pq/ssl.go new file mode 100644 index 0000000..d902084 --- /dev/null +++ b/vendor/github.com/lib/pq/ssl.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/ssl_permissions.go b/vendor/github.com/lib/pq/ssl_permissions.go new file mode 100644 index 0000000..3b7c3a2 --- /dev/null +++ b/vendor/github.com/lib/pq/ssl_permissions.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/ssl_windows.go b/vendor/github.com/lib/pq/ssl_windows.go new file mode 100644 index 0000000..5d2c763 --- /dev/null +++ b/vendor/github.com/lib/pq/ssl_windows.go @@ -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 } diff --git a/vendor/github.com/lib/pq/url.go b/vendor/github.com/lib/pq/url.go new file mode 100644 index 0000000..f4d8a7c --- /dev/null +++ b/vendor/github.com/lib/pq/url.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/user_posix.go b/vendor/github.com/lib/pq/user_posix.go new file mode 100644 index 0000000..bf98252 --- /dev/null +++ b/vendor/github.com/lib/pq/user_posix.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/user_windows.go b/vendor/github.com/lib/pq/user_windows.go new file mode 100644 index 0000000..2b69126 --- /dev/null +++ b/vendor/github.com/lib/pq/user_windows.go @@ -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 +} diff --git a/vendor/github.com/lib/pq/uuid.go b/vendor/github.com/lib/pq/uuid.go new file mode 100644 index 0000000..9a1b9e0 --- /dev/null +++ b/vendor/github.com/lib/pq/uuid.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/.travis.yml b/vendor/github.com/stripe/stripe-go/.travis.yml new file mode 100644 index 0000000..e55ae4f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/.travis.yml @@ -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 diff --git a/vendor/github.com/stripe/stripe-go/CHANGELOG b/vendor/github.com/stripe/stripe-go/CHANGELOG new file mode 100644 index 0000000..1d38c0c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/CHANGELOG @@ -0,0 +1 @@ +CHANGELOG has changed to be Markdown-formatted. Please see CHANGELOG.md. diff --git a/vendor/github.com/stripe/stripe-go/CHANGELOG.md b/vendor/github.com/stripe/stripe-go/CHANGELOG.md new file mode 100644 index 0000000..63c347d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/CHANGELOG.md @@ -0,0 +1,1624 @@ +# Changelog + +## 70.5.0 - 2020-03-13 +* [#1044](https://github.com/stripe/stripe-go/pull/1044) Multiple changes for Issuing APIs + * Rename `Speed` to `Service` on Issuing `Card` + * Rename `WalletProvider` to `Wallet` and `AddressZipCheck` to `AddressPostalCodeCheck` on Issuing `Authorization` + * Mark `IsDefault` as deprecated on Issuing `Cardholder` + +## 70.4.0 - 2020-03-12 +* [#1043](https://github.com/stripe/stripe-go/pull/1043) Add support for `Shipping` and `ShippingAddressCollection` on Checkout `Session` + +## 70.3.0 - 2020-03-12 +* [#1042](https://github.com/stripe/stripe-go/pull/1042) Add support for `ThreeDSecure` on Issuing `Authorization` + +## 70.2.0 - 2020-03-04 +* [#1041](https://github.com/stripe/stripe-go/pull/1041) Add new reason values and `ExpiryCheck` for Issuing `authorization + +## 70.1.0 - 2020-03-04 +* [#1040](https://github.com/stripe/stripe-go/pull/1040) Add support for `Errors` in `Requirements` on `Account`, `Capability` and `Person` + +## 70.0.0 - 2020-03-03 +* [#1039](https://github.com/stripe/stripe-go/pull/1039) Multiple API changes: + * Move to latest API version `2020-03-02` + * Add support for `NextInvoiceSequence` on `Customer` + +## 69.4.0 - 2020-02-28 +* [#1038](https://github.com/stripe/stripe-go/pull/1038) Add `TaxIDTypeMYSST` for `TaxId` + +## 69.3.0 - 2020-02-24 +* [#1037](https://github.com/stripe/stripe-go/pull/1037) Add new enum values for `IssuingDisputeReason` + +## 69.2.0 - 2020-02-24 +* [#1036](https://github.com/stripe/stripe-go/pull/1036) Add support for listing Checkout `Session` and passing tax rate information + +## 69.1.0 - 2020-02-21 +* [#1035](https://github.com/stripe/stripe-go/pull/1035) Add support for `ProrationBehavior` on `SubscriptionSchedule` +* [#1034](https://github.com/stripe/stripe-go/pull/1034) Add support for `Timezone` on `ReportRun` + +## 69.0.0 - 2020-02-20 +* [#1033](https://github.com/stripe/stripe-go/pull/1033) Make `Subscription` expandable on `Invoice` + +## 68.20.0 - 2020-02-12 +* [#1029](https://github.com/stripe/stripe-go/pull/1029) Add support for `Amount` in `CheckoutSessionPaymentIntentDataTransferDataParams` + +## 68.19.0 - 2020-02-10 +* [#1027](https://github.com/stripe/stripe-go/pull/1027) Add new constants for `TaxIDType` +* [#1028](https://github.com/stripe/stripe-go/pull/1028) Add support for `StatementDescriptorSuffix` on Checkout `Session` + +## 68.18.0 - 2020-02-05 +* [#1026](https://github.com/stripe/stripe-go/pull/1026) Multiple changes on the `Balance` resource: + * Add support for `ConnectReserved` + * Add support for `SourceTypes` for a given type of balance. + * Add support for FPX balance as a constant. + +## 68.17.0 - 2020-02-03 +* [#1024](https://github.com/stripe/stripe-go/pull/1024) Add `FilePurposeAdditionalVerification` and `FilePurposeBusinessIcon` on `File` +* [#1018](https://github.com/stripe/stripe-go/pull/1018) Add support for `ErrorOnRequiresAction` on `PaymentIntent` + +## 68.16.0 - 2020-01-31 +* [#1023](https://github.com/stripe/stripe-go/pull/1023) Add support for `TaxIDTypeTHVAT` and `TaxIDTypeTWVAT` on `TaxId` + +## 68.15.0 - 2020-01-30 +* [#1022](https://github.com/stripe/stripe-go/pull/1022) Add support for `Structure` on `Account` + +## 68.14.0 - 2020-01-28 +* [#1021](https://github.com/stripe/stripe-go/pull/1021) Add support for `TaxIDTypeESCIF` on `TaxId` + +## 68.13.0 - 2020-01-24 +* [#1019](https://github.com/stripe/stripe-go/pull/1019) Add support for `Shipping.Speed` and `Shipping.TrackingURL` on `IssuingCard` + +## 68.12.0 - 2020-01-23 +* [#1017](https://github.com/stripe/stripe-go/pull/1017) Add new values for `TaxIDType` and fix `TaxIDTypeCHVAT` +* [#1015](https://github.com/stripe/stripe-go/pull/1015) Replace duplicate code in GetBackend method + +## 68.11.0 - 2020-01-17 +* [#1014](https://github.com/stripe/stripe-go/pull/1014) Add `Metadata` support on Checkout `Session` + +## 68.10.0 - 2020-01-15 +* [#1012](https://github.com/stripe/stripe-go/pull/1012) Adds `PendingUpdate` to `Subscription` + +## 68.9.0 - 2020-01-14 +* [#1013](https://github.com/stripe/stripe-go/pull/1013) Add support for `CreditNoteLineItem` + +## 68.8.0 - 2020-01-08 +* [#1011](https://github.com/stripe/stripe-go/pull/1011) Add support for `InvoiceItem` and fix `Livemode` on `InvoiceLine` + +## 68.7.0 - 2020-01-07 +* [#1008](https://github.com/stripe/stripe-go/pull/1008) Add `ReportingCategory` to `BalanceTransaction` + +## 68.6.0 - 2020-01-06 +* [#1009](https://github.com/stripe/stripe-go/pull/1009) Add constant for `TaxIDTypeSGUEN` on `TaxId` + +## 68.5.0 - 2020-01-03 +* [#1007](https://github.com/stripe/stripe-go/pull/1007) Add support for `SpendingLimitsCurrency` on Issuing `Card` and `Cardholder` + +## 68.4.0 - 2019-12-20 +* [#1006](https://github.com/stripe/stripe-go/pull/1006) Adds `ExecutivesProvided` to `Account` + +## 68.3.0 - 2019-12-19 +* [#1005](https://github.com/stripe/stripe-go/pull/1005) Add `Metadata` and `Livemode` to Terminal `Reader` and `Location' + +## 68.2.0 - 2019-12-09 +* [#1002](https://github.com/stripe/stripe-go/pull/1002) Add support for AU BECS Debit on PaymentMethod + +## 68.1.0 - 2019-12-04 +* [#1001](https://github.com/stripe/stripe-go/pull/1001) Add support for `Network` on `Charge` + +## 68.0.0 - 2019-12-03 +* [#1000](https://github.com/stripe/stripe-go/pull/1000) Multiple breaking changes: + * Pin to API version `2019-12-03` + * Rename `InvoiceBillingStatus` to `InvoiceStatus` for consistency + * Remove typo-ed field `OutOfBankdAmount` on `CreditNote` + * Remove deprecated `PaymentIntentPaymentMethodOptionsCardRequestThreeDSecureChallengeOnly` and `SetupIntentPaymentMethodOptionsCardRequestThreeDSecureChallengeOnly` from `PaymentIntent` and `SetupIntent`. + * Remove `OperatorAccount` on `TerminalLocationListParams` + +## 67.10.0 - 2019-12-02 +* [#999](https://github.com/stripe/stripe-go/pull/999) Add support for `Status` filter when listing `Invoice`s. + +## 67.9.0 - 2019-11-26 +* [#997](https://github.com/stripe/stripe-go/pull/997) Add new refund reason `RefundReasonExpiredUncapturedCharge` + +## 67.8.0 - 2019-11-26 +* [#998](https://github.com/stripe/stripe-go/pull/998) Add support for `CreditNote` preview + +## 67.7.0 - 2019-11-25 +* [#996](https://github.com/stripe/stripe-go/pull/996) Add support for `OutOfBandAmount` on `CreditNote` creation +* [#995](https://github.com/stripe/stripe-go/pull/995) Fix comment typos + +## 67.6.0 - 2019-11-22 +* [#994](https://github.com/stripe/stripe-go/pull/994) Support for the `now` on `StartDate` on Subscription Schedule creation + +## 67.5.0 - 2019-11-21 +* [#993](https://github.com/stripe/stripe-go/pull/993) Add `PaymentIntent` filter when listing `Dispute`s + +## 67.4.1 - 2019-11-19 +* [#991](https://github.com/stripe/stripe-go/pull/991) Add missing constant for PaymentMethod of type FPX + +## 67.4.0 - 2019-11-18 +* [#989](https://github.com/stripe/stripe-go/pull/989) Add support for `ViolatedAuthorizationControls` on Issuing `Authorization` + +## 67.3.0 - 2019-11-07 +* [#988](https://github.com/stripe/stripe-go/pull/988) Add `Company` and `Individual` to Issuing `Cardholder` + +## 67.2.0 - 2019-11-06 +* [#985](https://github.com/stripe/stripe-go/pull/985) Multiple API changes + * Add `Disputed` to `Charge` + * Add `PaymentIntent` to `Refund` and `Dispute` + * Add `Charge` to `DisputeListParams` + * Add `PaymentIntent` to `RefundListParams` and `RefundParams` + +## 67.1.0 - 2019-11-06 +* [#986](https://github.com/stripe/stripe-go/pull/986) Add support for iDEAL and SEPA debit on `PaymentMethod` + +## 67.0.0 - 2019-11-05 +* [#987](https://github.com/stripe/stripe-go/pull/987) Move to the latest API version and add new changes + * Move to API version `2019-11-05` + * Add `DefaultSettings` on `SubscritionSchedule` + * Remove `BillingThresholds`, `CollectionMethod`, `DefaultPaymentMethod` and `DefaultSource` and `invoice_settings` from `SubscriptionSchedule` + * `OffSession` on `PaymentIntent` is now always a boolean + +## 66.3.0 - 2019-11-04 +* [#984](https://github.com/stripe/stripe-go/pull/984) Add support for `UseStripeSDK` on `PaymentIntent` create and confirm + +## 66.2.0 - 2019-11-04 +* [#983](https://github.com/stripe/stripe-go/pull/983) Add support for cloning saved PaymentMethods +* [#980](https://github.com/stripe/stripe-go/pull/980) Improve docs for ephemeral keys + +## 66.1.1 - 2019-10-24 +* [#978](https://github.com/stripe/stripe-go/pull/978) Properly pass `Type` in `PaymentIntentPaymentMethodOptionsCardInstallmentsPlanParams` + * Note that this is technically a breaking change, however we've chosen to release it as a patch version as this shipped yesterday and is a new feature +* [#977](https://github.com/stripe/stripe-go/pull/977) Contributor Convenant + +## 66.1.0 - 2019-10-23 +* [#974](https://github.com/stripe/stripe-go/pull/974) Add support for installments on `PaymentIntent` and `Charge` +* [#975](https://github.com/stripe/stripe-go/pull/975) Add support for `PendingInvoiceItemInterval` on `Subscription` +* [#976](https://github.com/stripe/stripe-go/pull/976) Add `TaxIDTypeMXRFC` constant to `TaxIDType` + +## 66.0.0 - 2019-10-18 +* [#973](https://github.com/stripe/stripe-go/pull/973) Multiple breaking changes + * Pin to the latest API version `2019-10-17` + * Remove `RenewalBehavior` on `SubscriptionSchedule` + * Remove `RenewalBehavior` and `RenewalInterval` as parameters on `SubscriptionSchedule` + +## 65.2.0 - 2019-10-17 +* [#972](https://github.com/stripe/stripe-go/pull/972) Various API changes + * `Requirements` on Issuing `Cardholder` + * `PaymentMethodDetails.AuBecsDebit.Mandate` on `Charge` + * `PaymentBehavior` on `Subscription` creation can now take the value `pending_if_incomplete` + * `PaymentBehavior` on `SubscriptionItem` creation is now supported + * `SubscriptionData.TrialFromPlan` is now supported on Checkout `Session` creation + * New values for `TaxIDType` + +## 65.1.1 - 2019-10-11 +* [#970](https://github.com/stripe/stripe-go/pull/970) Properly deserialize `Fulfilled` on `StatusTransitions` in the `order` package + +## 65.1.0 - 2019-10-09 +* [#969](https://github.com/stripe/stripe-go/pull/969) Add `DeviceType` filter when listing Terminal `Reader`s + +## 65.0.0 - 2019-10-09 +* [#951](https://github.com/stripe/stripe-go/pull/951) Move to API version [`2019-10-08`](https://stripe.com/docs/upgrades#2019-10-08) and other changes + * [#950](https://github.com/stripe/stripe-go/pull/950) Remove lossy "MarshalJSON" implementations + * [#962](https://github.com/stripe/stripe-go/pull/962) Removed deprecated properties and most todos + * Removed `GetBalanceTransaction` and `List` from the `balance` package. Prefer using `Get` and `List` in the `balancetransaction` package. + * Removed `ApplicationFee` from the `charge` and `paymentintent` packages. Prefer using `ApplicationFeeAmount`. + * Removed `TaxInfo` and related fields from the `customer` packager. Prefer using the `customertaxid` package. + * Removed unsupported `Customer` parameter on `PaymentMethodParams` and `PaymentMethodDetachParams` in the `paymentmethod` package. + * Removed `Billing` properties in the `invoice`, `sub` and `subschedule` packages. Prefer using `CollectionMethod`. + * Removed the `InvoiceBilling` type from the `invoice` package. Prefer using `InvoiceCollectionMethod`. + * Removed the `SubscriptionBilling` type from the `sub` package. Prefer using `SubscriptionCollectionMethod`. + * Removed deprecated constants for `PaymentIntentConfirmationMethod` in `paymentintent` package. + * Removed `OperatorAccount` from Terminal APIs. + * [#960](https://github.com/stripe/stripe-go/pull/960) Remove `issuerfraudrecord` package. Prefer using `earlyfraudwarning` + * [#968](https://github.com/stripe/stripe-go/pull/968) Rename `AccountOpener` to `Representative` and update to latest API version + +## 64.1.0 - 2019-10-09 +* [#967](https://github.com/stripe/stripe-go/pull/967) Add `Get` method to `OrderReturn` + +## 64.0.0 - 2019-10-08 +* ~[#968](https://github.com/stripe/stripe-go/pull/968) Update to latest API version [`2019-10-08`](https://stripe.com/docs/upgrades#2019-10-08)~ + * **Note:** This release is actually a no-op as we failed to merge the changes. Please use 65.0.0 instead. + +## 63.5.0 - 2019-10-03 +* [#955](https://github.com/stripe/stripe-go/pull/955) Add FPX `PaymentMethod` Support +* [#966](https://github.com/stripe/stripe-go/pull/966) Add the `Account` field to `BankAccount` + +## 63.4.0 - 2019-09-30 +* [#952](https://github.com/stripe/stripe-go/pull/952) Add AU BECS Debit Support + +## 63.3.0 - 2019-09-30 +* [#964](https://github.com/stripe/stripe-go/pull/964) Add support for `Status` and `Location` filters when listing `Reader`s + +## 63.2.2 - 2019-09-26 +* [#963](https://github.com/stripe/stripe-go/pull/963) Update `SourceSourceOrder` `Items` field to fix unmarshalling errors + +## 63.2.1 - 2019-09-25 +* [#961](https://github.com/stripe/stripe-go/pull/961) Properly tag `Customer` as deprecated in `PaymentMethodDetachParams` + +## 63.2.0 - 2019-09-25 +* [#959](https://github.com/stripe/stripe-go/pull/959) Mark `Customer` on `PaymentMethodDetachParams` as deprecated +* [#957](https://github.com/stripe/stripe-go/pull/957) Add missing error code + +## 63.1.1 - 2019-09-23 +* [#954](https://github.com/stripe/stripe-go/pull/954) Add support for `Stripe-Should-Retry` header + +## 63.1.0 - 2019-09-13 +* [#949](https://github.com/stripe/stripe-go/pull/949) Add support for `DeclineCode` on `Error` top-level + +## 63.0.0 - 2019-09-10 +* [#947](https://github.com/stripe/stripe-go/pull/947) Bump API version to [`2019-09-09`](https://stripe.com/docs/upgrades#2019-09-09) + +## 62.10.0 - 2019-09-09 +* [#945](https://github.com/stripe/stripe-go/pull/945) Changes to `Account` and `Person` to represent identity verification state + +## 62.9.0 - 2019-09-04 +* [#943](https://github.com/stripe/stripe-go/pull/943) Add support for `Authentication` and `URL` on Issuing `Authorization` + +## 62.8.2 - 2019-08-29 +* [#939](https://github.com/stripe/stripe-go/pull/939) Also log error in case of non-`stripe.Error` + +## 62.8.1 - 2019-08-29 +* [#938](https://github.com/stripe/stripe-go/pull/938) Rearrange error logging so that 402 doesn't log an error + +## 62.8.0 - 2019-08-29 +* [#937](https://github.com/stripe/stripe-go/pull/937) Add support for `EndBehavior` on `SubscriptionSchedule` + +## 62.7.0 - 2019-08-27 +* [#935](https://github.com/stripe/stripe-go/pull/935) Retry requests on a 429 that's a lock timeout + +## 62.6.0 - 2019-08-26 +* [#934](https://github.com/stripe/stripe-go/pull/934) Add support for `SubscriptionBillingCycleAnchorNow` and `SubscriptionBillingCycleAnchorUnchanged` on `Invoice` +* [#933](https://github.com/stripe/stripe-go/pull/933) Add `PendingVerification` on `Account`, `Person` and `Capability` + +## 62.5.0 - 2019-08-23 +* [#930](https://github.com/stripe/stripe-go/pull/930) Add `FailureReason` to `Refund` + +## 62.4.0 - 2019-08-22 +* [#926](https://github.com/stripe/stripe-go/pull/926) Add support for decimal amounts on Billing resources + +## 62.3.0 - 2019-08-22 +* [#928](https://github.com/stripe/stripe-go/pull/928) Bring retry code in-line with current best practices + +## 62.2.0 - 2019-08-21 +* [#922](https://github.com/stripe/stripe-go/pull/922) A few Billing changes + * Add `Schedule` to `Subscription` + * Add missing parameters for the Upcoming Invoice API: `Schedule`, `SubscriptionCancelAt`, `SubscriptionCancelNow` + * Add missing properties and parameters for a `SubscriptionSchedule` phase: `BillingThresholds`, `CollectionMethod`, `DefaultPaymentMethod`, `InvoiceSettings` +* [#923](https://github.com/stripe/stripe-go/pull/923) Add support for `Mode` on Checkout `Session` + +## 62.1.2 - 2019-08-19 +* [#921](https://github.com/stripe/stripe-go/pull/921) Mark `Customer` as an invalid parameter on PaymentMethod creation + +## 62.1.1 - 2019-08-15 +* [#918](https://github.com/stripe/stripe-go/pull/918) Fix `RadarEarlyFraudWarnings` to use the proper API endpoint + +## 62.1.0 - 2019-08-15 +* [#916](https://github.com/stripe/stripe-go/pull/916) + * Add support for `PIN` on Issuing `Card` to reflect the status of a card's PIN + * Add support for `Executive` on Person create, update and list + +## 62.0.0 - 2019-08-14 +* [#915](https://github.com/stripe/stripe-go/pull/915) Move to API version [`2019-08-14`](https://stripe.com/docs/upgrades#2019-08-14) and other changes + * Pin to API version `2019-08-14` + * Rename `AccountCapabilityPlatformPayments` to `AccountCapabilityTransfers` + * Add `Executive` in `PersonRelationship` + * Remove `PayentMethodOptions` as there was a typo which was fixed + * Make `OffSession` only support booleans on `PaymentIntent` + * Remove `PaymentIntentLastPaymentError` and use `Error` instead + * Move `DeclineCode` on `Error` to the `DeclineCode` type instead of `string` +* [#914](https://github.com/stripe/stripe-go/pull/914) Update webhook handler example to use `http.MaxBytesReader` + +## 61.27.0 - 2019-08-09 +* [#913](https://github.com/stripe/stripe-go/pull/913) Remove `SubscriptionScheduleRevision` + * Note that this is technically a breaking change, however we've chosen to release it as a minor version in light of the fact that this resource and its API methods were virtually unused. + +## 61.26.0 - 2019-08-08 +* [#911](https://github.com/stripe/stripe-go/pull/911) + * Add support for `PaymentMethodDetails.Card.Moto` on `Charge` + * Add support `StatementDescriptorSuffix` on `Charge` and `PaymentIntent` + * Add support `SubscriptionData.ApplicationFeePercent` on Checkout `Session` + +## 61.25.0 - 2019-07-30 +* [#910](https://github.com/stripe/stripe-go/pull/910) Add `balancetransaction` package with a `Get` and `List` methods + +## 61.24.0 - 2019-07-30 +* [#906](https://github.com/stripe/stripe-go/pull/906) Add decline code type and constants (for use with card errors) + +## 61.23.0 - 2019-07-29 +* [#879](https://github.com/stripe/stripe-go/pull/879) Add support for OAuth API endpoints + +## 61.22.0 - 2019-07-29 +* [#909](https://github.com/stripe/stripe-go/pull/909) Rename `PayentMethodOptions` to `PaymentMethodOptions` on `PaymentIntent` and `SetupIntent`. Keep the old name until the next major version for backwards-compatibility + +## 61.21.0 - 2019-07-26 +* [#904](https://github.com/stripe/stripe-go/pull/904) Add support for Klarna and source orders + +## 61.20.0 - 2019-07-25 +* [#897](https://github.com/stripe/stripe-go/pull/897) Add all missing error codes +* [#903](https://github.com/stripe/stripe-go/pull/903) Disable HTTP/2 by default (until underlying bug in Go's implementation is fixed) +* [#905](https://github.com/stripe/stripe-go/pull/905) Add missing `Authenticated` field for 3DS charges + +## 61.19.0 - 2019-07-22 +* [#902](https://github.com/stripe/stripe-go/pull/902) Add support for `StatementDescriptor` when capturing a `PaymentIntent` + +## 61.18.0 - 2019-07-19 +* [#898](https://github.com/stripe/stripe-go/pull/898) Add `Customer` filter when listing `CreditNote` +* [#899](https://github.com/stripe/stripe-go/pull/899) Add `OffSession` parameter when updating `SubscriptionItem` + +## 61.17.0 - 2019-07-17 +* [#895](https://github.com/stripe/stripe-go/pull/895) Add `VoidedAt` on `CreditNote` + +## 61.16.0 - 2019-07-16 +* [#894](https://github.com/stripe/stripe-go/pull/894) Introduce encoding for high precision decimal fields + +## 61.15.0 - 2019-07-15 +* [#893](https://github.com/stripe/stripe-go/pull/893) + * Add support for `PaymentMethodOptions` on `PaymentIntent` and `SetupIntent` + * Add missing parameters to `PaymentIntentConfirmParams` + +## 61.14.0 - 2019-07-15 +* [#891](https://github.com/stripe/stripe-go/pull/891) Various changes relaed to SCA for Billing + * Add support for `PendingSetupIntent` on `Subscription` + * Add support for `PaymentBehavior` on `Subscription` creation and update + * Add support for `PaymentBehavior` on `SubscriptionItem` update + * Add support for `OffSession` when paying an `Invoice` + * Add support for `OffSession` on `Subscription` creation and update + +## 61.13.0 - 2019-07-05 +* [#888](https://github.com/stripe/stripe-go/pull/888) Add support for `SetupFutureUsage` on `PaymentIntent` update and confirm +* [#890](https://github.com/stripe/stripe-go/pull/890) Add support for `SetupFutureUsage` on Checkout `Session` + +## 61.12.0 - 2019-07-01 +* [#887](https://github.com/stripe/stripe-go/pull/887) Allow `OffSession` to be a bool on `PaymentIntent` creation and confirmation + +## 61.11.0 - 2019-07-01 +* [#886](https://github.com/stripe/stripe-go/pull/886) Add `CardVerificationUnavailable` constant value + +## 61.10.0 - 2019-07-01 +* [#884](https://github.com/stripe/stripe-go/pull/884) Add support for the `SetupIntent` resource and APIs +* [#885](https://github.com/stripe/stripe-go/pull/885) Quick fix to the `NextAction` property on `SetupIntent` + +## 61.9.0 - 2019-06-27 +* [#882](https://github.com/stripe/stripe-go/pull/882) Add `DefaultPaymentMethod` and `DefaultSource` to `SubscriptionSchedule` + +## 61.8.0 - 2019-06-27 +* **Note:** This release was deleted after we merged some bad code. Please use 61.9.0 instead. + +## 61.7.1 - 2019-06-25 +* [#881](https://github.com/stripe/stripe-go/pull/881) Documentation fixes + +## 61.7.0 - 2019-06-25 +* [#880](https://github.com/stripe/stripe-go/pull/880) + * Add support for `CollectionMethod` on `Invoice`, `Subscription` and `SubscriptionSchedule` + * Add support for `UnifiedProration` on `InvoiceLine` + +## 61.6.0 - 2019-06-24 +* [#878](https://github.com/stripe/stripe-go/pull/878) Enable request latency telemetry by default + +## 61.5.0 - 2019-06-20 +* [#877](https://github.com/stripe/stripe-go/pull/877) Add `CancellationReason` to `PaymentIntent` + +## 61.4.0 - 2019-06-18 +* [#845](https://github.com/stripe/stripe-go/pull/845) Add support for `CustomerBalanceTransaction` resource and APIs +* [#875](https://github.com/stripe/stripe-go/pull/875) Add missing `Account` settings + +## 61.3.0 - 2019-06-18 +* [#874](https://github.com/stripe/stripe-go/pull/874) Log only to info on 402 errors from Stripe + +## 61.2.0 - 2019-06-14 +* [#870](https://github.com/stripe/stripe-go/pull/870) Add support for `MerchantAmount` `MerchantCurrency` to Issuing `Transaction` +* [#871](https://github.com/stripe/stripe-go/pull/871) Add support for `SubmitType` to Checkout `Session` + +## 61.1.0 - 2019-06-06 +* [#867](https://github.com/stripe/stripe-go/pull/867) Add support for `Location` on Terminal `ConnectionToken` +* [#868](https://github.com/stripe/stripe-go/pull/868) Add support for `Balance` and deprecate `AccountBalance` on Customer + +## 61.0.1 - 2019-05-24 +* [#865](https://github.com/stripe/stripe-go/pull/865) Fix `earlyfraudwarning` client + +## 61.0.0 - 2019-05-24 +* [#864](https://github.com/stripe/stripe-go/pull/864) Pin library to API version `2019-05-16` + +## 60.19.0 - 2019-05-24 +* [#862](https://github.com/stripe/stripe-go/pull/862) Add support for `radar.early_fraud_warning` resource + +## 60.18.0 - 2019-05-22 +* [#861](https://github.com/stripe/stripe-go/pull/861) Add new tax ID types: `TaxIDTypeINGST` and `TaxIDTypeNOVAT` + +## 60.17.0 - 2019-05-16 +* [#860](https://github.com/stripe/stripe-go/pull/860) Add `OffSession` parameter to payment intents + +## 60.16.0 - 2019-05-14 +* [#859](https://github.com/stripe/stripe-go/pull/859) Add missing `InvoiceSettings` to `Customer` + +## 60.15.0 - 2019-05-14 +* [#855](https://github.com/stripe/stripe-go/pull/855) Add support for the capability resource and APIs + +## 60.14.0 - 2019-05-10 +* [#858](https://github.com/stripe/stripe-go/pull/858) Add `StartDate` to `Subscription` + +## 60.13.2 - 2019-05-10 +* [#857](https://github.com/stripe/stripe-go/pull/857) Fix invoice's `PaymentIntent` so its JSON tag uses API snakecase + +## 60.13.1 - 2019-05-08 +* [#853](https://github.com/stripe/stripe-go/pull/853) Add paymentmethod package to the clients list + +## 60.13.0 - 2019-05-07 +* [#850](https://github.com/stripe/stripe-go/pull/850) `OperatorAccount` is now deprecated across all Terminal endpoints +* [#851](https://github.com/stripe/stripe-go/pull/851) Add `Customer` on the `Source` object + +## 60.12.2 - 2019-05-06 +* [#843](https://github.com/stripe/stripe-go/pull/843) Lock mutex while in `SetBackends` + +## 60.12.1 - 2019-05-06 +* [#848](https://github.com/stripe/stripe-go/pull/848) Fix `Items` on `CheckoutSessionSubscriptionDataParams` to be a slice + +## 60.12.0 - 2019-05-05 +* [#846](https://github.com/stripe/stripe-go/pull/846) Add support for the `PaymentIntent` filter on `ChargeListParams` + +## 60.11.0 - 2019-05-02 +* [#841](https://github.com/stripe/stripe-go/pull/841) Add support for the `Customer` filter on `PaymentIntentListParams` +* [#842](https://github.com/stripe/stripe-go/pull/842) Add support for replacing another Issuing `Card` on creation + +## 60.10.0 - 2019-04-30 +* [#839](https://github.com/stripe/stripe-go/pull/839) Add support for ACSS Debit in `PaymentMethodDetails` on `Charge` +* [#840](https://github.com/stripe/stripe-go/pull/840) Add support for `FileLinkData` on `File` creation + +## 60.9.0 - 2019-04-24 +* [#828](https://github.com/stripe/stripe-go/pull/828) Add support for the `TaxRate` resource and APIs + +## 60.8.0 - 2019-04-23 +* [#834](https://github.com/stripe/stripe-go/pull/834) Add support for the `TaxId` resource and APIs + +## 60.7.0 - 2019-04-18 +* [#823](https://github.com/stripe/stripe-go/pull/823) Add support for the `CreditNote` resource and APIs +* [#829](https://github.com/stripe/stripe-go/pull/829) Add support for `Address`, `Name`, `Phone` and `PreferredLocales` on `Customer` and related fields on `Invoice` + +## 60.6.0 - 2019-04-18 +* [#837](https://github.com/stripe/stripe-go/pull/837) Add helpers to go from `[]T` to `[]*T` for `string`, `int64`, `float64`, `bool` + +## 60.5.1 - 2019-04-16 +* [#836](https://github.com/stripe/stripe-go/pull/836) Fix `SpendingLimits` on `AuthorizationControlsParams` and `AuthorizationControls` to be a slice on Issuing `Card` and `Cardholder` + +## 60.5.0 - 2019-04-16 +* [#740](https://github.com/stripe/stripe-go/pull/740) Add support for the Checkout `Session` resource and APIs +* [#832](https://github.com/stripe/stripe-go/pull/832) Add support for `version` and `succeeded` properties in the `payment_method_details[card][three_d_secure]` hash for `Charge`. +* [#835](https://github.com/stripe/stripe-go/pull/835) Add support for passing `payment_method` on `Customer` creation + +## 60.4.0 - 2019-04-15 +* [#833](https://github.com/stripe/stripe-go/pull/833) Add more context when failing to unmarshal JSON + +## 60.3.0 - 2019-04-12 +* [#831](https://github.com/stripe/stripe-go/pull/831) Add support for `authorization_controls` on `Cardholder` and `authorization_controls[spending_limits]` added to `Card` too for Issuing resources + +## 60.2.0 - 2019-04-09 +* [#827](https://github.com/stripe/stripe-go/pull/827) Add support for `confirmation_method` on `PaymentIntent` creation + +## 60.1.0 - 2019-04-09 +* [#824](https://github.com/stripe/stripe-go/pull/824) Add support for `PaymentIntent` and `PaymentMethod` on `Customer`, `Subscription` and `Invoice`. + +## 60.0.1 - 2019-04-02 +* [#825](https://github.com/stripe/stripe-go/pull/825) Fix the API for usage record summary listing + +## 60.0.0 - 2019-03-27 +* [#820](https://github.com/stripe/stripe-go/pull/820) Add various missing parameters + * On `PIIParams` the previous `PersonalIDNumber` is fixed to `IDNumber` which we're releasing as a minor breaking change even though the old version probably didn't work correctly + +## 59.1.0 - 2019-03-22 +* [#819](https://github.com/stripe/stripe-go/pull/819) Add default level prefixes in messages from `LeveledLogger` + +## 59.0.0 - 2019-03-22 +* [#818](https://github.com/stripe/stripe-go/pull/818) Implement leveled logging (very minor breaking change -- only a couple properties were removed from the internal `BackendImplementation`) + +## 58.1.0 - 2019-03-19 +* [#815](https://github.com/stripe/stripe-go/pull/815) Add support for passing token on account or person creation + +## 58.0.0 - 2019-03-19 +* [#811](https://github.com/stripe/stripe-go/pull/811) Add support for API version 2019-03-14 +* [#814](https://github.com/stripe/stripe-go/pull/814) Properly override API version if it's set in the request + +## 57.8.0 - 2019-03-18 +* [#806](https://github.com/stripe/stripe-go/pull/806) Add support for the `PaymentMethod` resource and APIs +* [#812](https://github.com/stripe/stripe-go/pull/812) Add support for deleting a Terminal `Location` and `Reader` + +## 57.7.0 - 2019-03-13 +* [#810](https://github.com/stripe/stripe-go/pull/810) Add support for `columns` on `ReportRun` and `default_columns` on `ReportType`. + +## 57.6.0 - 2019-03-06 +* [#808](https://github.com/stripe/stripe-go/pull/808) Add support for `backdate_start_date` and `cancel_at` on `Subscription`. + +## 57.5.0 - 2019-03-05 +* [#807](https://github.com/stripe/stripe-go/pull/807) Add support for `current_period_end` and `current_period_start` filters when listing `Invoice`. + +## 57.4.0 - 2019-03-04 +* [#798](https://github.com/stripe/stripe-go/pull/798) Properly support serialization of `Event`. + +## 57.3.0 - 2019-02-28 +* [#803](https://github.com/stripe/stripe-go/pull/803) Add support for `api_version` on `WebhookEndpoint`. + +## 57.2.0 - 2019-02-27 +* [#795](https://github.com/stripe/stripe-go/pull/795) Add support for `created` and `status_transitions` on `Invoice` +* [#802](https://github.com/stripe/stripe-go/pull/802) Add support for `latest_invoice` on `Subscription` + +## 57.1.1 - 2019-02-26 +* [#800](https://github.com/stripe/stripe-go/pull/800) Add `UsageRecordSummaries` to the list of clients. + +## 57.1.0 - 2019-02-22 +* [#796](https://github.com/stripe/stripe-go/pull/796) Correct `InvoiceItems` in `InvoiceParams` to be a slice of structs instead of a struct (this is technically a breaking change, but the previous implementation was non-functional, so we're releasing it as a minor version) + +## 57.0.1 - 2019-02-20 +* [#794](https://github.com/stripe/stripe-go/pull/794) Properly pin to API version `2019-02-19`. The previous major version incorrectly stayed on API version `2019-02-11` which prevented requests to manage Connected accounts from working and charges to have the new statement descriptor behavior. + +## 57.0.0 - 2019-02-19 +**Important:** This version is non-functional and has been yanked in favor of 57.0.1. +* [#782](https://github.com/stripe/stripe-go/pull/782) Changes related to the new API version `2019-02-19`: + * The library is now pinned to API version `2019-02-19` + * Numerous changes to the `Account` resource and APIs: + * The `legal_entity` property on the Account API resource has been replaced with `individual`, `company`, and `business_type` + * The `verification` hash has been replaced with a `requirements` hash + * Multiple top-level properties were moved to the `settings` hash + * The `keys` property on `Account` has been removed. Platforms should authenticate as their connected accounts with their own key via the `Stripe-Account` [header](https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header) + * The `requested_capabilities` property on `Account` creation is now required for accounts in the US + * The deprecated parameter `save_source_to_customer` on `PaymentIntent` has now been removed. Use `save_payment_method` instead + +## 56.1.0 - 2019-02-18 +* [#737](https://github.com/stripe/stripe-go/pull/737) Add support for setting `request_capabilities` and retrieving `capabilities` on `Account` +* [#793](https://github.com/stripe/stripe-go/pull/793) Add support for `save_payment_method` on `PaymentIntent` + +## 56.0.0 - 2019-02-13 +* [#785](https://github.com/stripe/stripe-go/pull/785) Changes to the Payment Intent APIs for the next API version +* [#789](https://github.com/stripe/stripe-go/pull/789) Allow API arrays to be emptied by setting an empty array + +## 55.15.0 - 2019-02-12 +* [#764](https://github.com/stripe/stripe-go/pull/764) Add support for `transfer_data[destination]` on `Invoice` and `Subscription` +* [#784](https://github.com/stripe/stripe-go/pull/784) + * Add support for `SubscriptionSchedule` and `SubscriptionScheduleRevision` + * Add support for `payment_method_types` on `PaymentIntent` +* [#787](https://github.com/stripe/stripe-go/pull/787) Add support for `transfer_data[amount]` on `Charge` + +## 55.14.0 - 2019-01-25 +* [#765](https://github.com/stripe/stripe-go/pull/765) Add support for `destination_payment_refund` and `source_refund` on the `Reversal` resource + +## 55.13.0 - 2019-01-17 +* [#779](https://github.com/stripe/stripe-go/pull/779) Add support for `receipt_url` on `Charge` + +## 55.12.0 - 2019-01-17 +* [#766](https://github.com/stripe/stripe-go/pull/766) Add optional support for sending request telemetry to Stripe + +## 55.11.0 - 2019-01-17 +* [#776](https://github.com/stripe/stripe-go/pull/776) Add support for billing thresholds + +## 55.10.0 - 2019-01-16 +* [#773](https://github.com/stripe/stripe-go/pull/773) Add support for `custom_fields` and `footer` on `Invoice` +* [#774](https://github.com/stripe/stripe-go/pull/774) Revert Go module support + +## 55.9.0 - 2019-01-15 +* [#769](https://github.com/stripe/stripe-go/pull/769) Add field `Amount` to `IssuingTransaction` + +## 55.8.0 - 2019-01-09 +* [#763](https://github.com/stripe/stripe-go/pull/763) Add `application_fee_amount` to `Charge` and on charge create and capture params + +## 55.7.0 - 2019-01-09 +* [#738](https://github.com/stripe/stripe-go/pull/738) Add support for the account link resource + +## 55.6.0 - 2019-01-09 +* [#762](https://github.com/stripe/stripe-go/pull/762) Add support for new invoice items parameters when retrieving an upcoming invoice + +## 55.5.0 - 2019-01-07 +* [#744](https://github.com/stripe/stripe-go/pull/744) Add support for `transfer_data[destination]` on Charge struct and params +* [#746](https://github.com/stripe/stripe-go/pull/746) Add support for `wallet_provider` on the Issuing Authorization + +## 55.4.0 - 2019-01-07 +* [#745](https://github.com/stripe/stripe-go/pull/745) Add support for `pending` parameter when listing invoice items + +## 55.3.0 - 2019-01-02 +* [#742](https://github.com/stripe/stripe-go/pull/742) Add field `FraudType` to `IssuerFraudRecord` + +## 55.2.0 - 2018-12-31 +* [#741](https://github.com/stripe/stripe-go/pull/741) Add missing parameters `InvoiceNow` and `Prorate` for subscription cancellation + +## 55.1.0 - 2018-12-27 +* [#743](https://github.com/stripe/stripe-go/pull/743) Add support for `clear_usage` on `SubscriptionItem` deletion + +## 55.0.0 - 2018-12-13 +* [#739](https://github.com/stripe/stripe-go/pull/739) Use `ApplicationFee` struct for `FeeRefund.Fee` (minor breaking change) + +## 54.2.0 - 2018-11-30 +* [#734](https://github.com/stripe/stripe-go/pull/734) Put `/v1/` prefix as part of all paths instead of URL + +## 54.1.1 - 2018-11-30 +* [#733](https://github.com/stripe/stripe-go/pull/733) Fix malformed URL generated for the uploads API when using `NewBackends` + +## 54.1.0 - 2018-11-28 +* [#730](https://github.com/stripe/stripe-go/pull/730) Add support for the Review resource +* [#731](https://github.com/stripe/stripe-go/pull/731) Add missing properties on the Refund resource + +## 54.0.0 - 2018-11-27 +* [#721](https://github.com/stripe/stripe-go/pull/721) Add support for `RadarValueList` and `RadarValueListItem` +* [#721](https://github.com/stripe/stripe-go/pull/721) Remove `Closed` and `Forgiven` from `InvoiceParams` +* [#721](https://github.com/stripe/stripe-go/pull/721) Add `PaidOutOfBand` to `InvoicePayParams` + +## 53.4.0 - 2018-11-26 +* [#728](https://github.com/stripe/stripe-go/pull/728) Add `IssuingCard` to `EphemeralKeyParams` + +## 53.3.0 - 2018-11-26 +* [#727](https://github.com/stripe/stripe-go/pull/727) Add support for `TransferData` on payment intent create and update + +## 53.2.0 - 2018-11-21 +* [#725](https://github.com/stripe/stripe-go/pull/725) Improved error deserialization + +## 53.1.0 - 2018-11-15 +* [#723](https://github.com/stripe/stripe-go/pull/723) Add support for `last_payment_error` on `PaymentIntent`. +* [#724](https://github.com/stripe/stripe-go/pull/724) Add support for `transfer_data[destination]` on `PaymentIntent`. + +## 53.0.1 - 2018-11-12 +* [#714](https://github.com/stripe/stripe-go/pull/714) Fix bug in retry logic that would cause the client to panic + +## 53.0.0 - 2018-11-08 +* [#716](https://github.com/stripe/stripe-go/pull/716) Drop support for Go 1.8. +* [#715](https://github.com/stripe/stripe-go/pull/715) Ship changes to the `PaymentIntent` resource to match the final layout. +* [#717](https://github.com/stripe/stripe-go/pull/717) Add support for `flat_amount` on `Plan` tiers. +* [#718](https://github.com/stripe/stripe-go/pull/718) Add support for `supported_transfer_countries` on `CountrySpec`. +* [#720](https://github.com/stripe/stripe-go/pull/720) Add support for `review` on `PaymentIntent`. +* [#707](https://github.com/stripe/stripe-go/pull/707) Add new invoice methods and fixes to the Issuing Cardholder resource (multiple breaking changes) + * Move to API version 2018-11-08. + * Add support for new API methods, properties and parameters for `Invoice`. + * Add support for `default_source` on `Subscription` and `Invoice`. + +## 52.1.0 - 2018-10-31 +* [#705](https://github.com/stripe/stripe-go/pull/705) Add support for the `Person` resource +* [#706](https://github.com/stripe/stripe-go/pull/706) Add support for the `WebhookEndpoint` resource + +## 52.0.0 - 2018-10-29 +* [#711](https://github.com/stripe/stripe-go/pull/711) Set `Request.GetBody` when making requests +* [#711](https://github.com/stripe/stripe-go/pull/711) Drop support for Go 1.7 (hasn't been supported by Go core since the release of Go 1.9 in August 2017) + +## 51.4.0 - 2018-10-19 +* [#708](https://github.com/stripe/stripe-go/pull/708) Add Stripe Terminal endpoints to master to `client.API` + +## 51.3.0 - 2018-10-09 +* [#704](https://github.com/stripe/stripe-go/pull/704) Add support for `subscription_cancel_at_period_end` on the Upcoming Invoice API. + +## 51.2.0 - 2018-10-09 +* [#702](https://github.com/stripe/stripe-go/pull/702) Add support for `delivery_success` filter when listing Events. + +## 51.1.0 - 2018-10-03 +* [#700](https://github.com/stripe/stripe-go/pull/700) Add support for `on_behalf_of` on Subscription and Charge resources. + +## 51.0.0 - 2018-09-27 +* [#698](https://github.com/stripe/stripe-go/pull/698) Move to API version 2018-09-24 + * Rename `FileUpload` to `File` (and all `FileUpload*` structs to `File*`) + * Fix file links client + +## 50.0.0 - 2018-09-24 +* [#695](https://github.com/stripe/stripe-go/pull/695) Rename `Transaction` to `DisputedTransaction` in `IssuingDisputeParams` (minor breaking change) +* [#695](https://github.com/stripe/stripe-go/pull/695) Add support for Stripe Terminal + +## 49.2.0 - 2018-09-24 +* [#697](https://github.com/stripe/stripe-go/pull/697) Fix `number` JSON tag on the `IssuingCardDetails` resource. + +## 49.1.0 - 2018-09-11 +* [#694](https://github.com/stripe/stripe-go/pull/694) Add `ErrorCodeResourceMissing` error code constant + +## 49.0.0 - 2018-09-11 +* [#693](https://github.com/stripe/stripe-go/pull/693) Change `Product` under `Plan` from a string to a full `Product` struct pointer (this is a minor breaking change -- upgrade by changing to `plan.Product.ID`) + +## 48.3.0 - 2018-09-06 +* [#691](https://github.com/stripe/stripe-go/pull/691) Add `InvoicePrefix` to `Customer` and `CustomerParams` + +## 48.2.0 - 2018-09-05 +* [#690](https://github.com/stripe/stripe-go/pull/690) Add support for reporting resources + +## 48.1.0 - 2018-09-05 +* [#683](https://github.com/stripe/stripe-go/pull/683) Add `StatusTransitions` filter parameters to `OrderListParams` + +## 48.0.0 - 2018-09-05 +* [#681](https://github.com/stripe/stripe-go/pull/681) Handle deserialization of `OrderItem` parent into an object if expanded (minor breaking change) + +## 47.0.0 - 2018-09-04 +* New major version for better compatibility with Go's new module system (no breaking changes) + +## 46.1.0 - 2018-09-04 +* [#688](https://github.com/stripe/stripe-go/pull/688) Encode `Params` in `AppendToAsSourceOrExternalAccount` (bug fix) +* [#689](https://github.com/stripe/stripe-go/pull/689) Add `go.mod` for the new module system + +## 46.0.0 - 2018-09-04 +* [#686](https://github.com/stripe/stripe-go/pull/686) Add `Mandate` and `Receiver` to `SourceObjectParams` and change `Date` on `SourceMandateAcceptance` to `int64` (minor breaking change) + +## 45.0.0 - 2018-08-30 +* [#680](https://github.com/stripe/stripe-go/pull/680) Change `SubscriptionTaxPercent` on `Invoice` from `int64` to `float64` (minor breaking change) + +## 44.0.0 - 2018-08-28 +* [#678](https://github.com/stripe/stripe-go/pull/678) Allow payment intent capture to take its own parameters + +## 43.1.1 - 2018-08-28 +* [#675](https://github.com/stripe/stripe-go/pull/675) Fix incorrectly encoded parameter in `UsageRecordSummaryListParams` + +## 43.1.0 - 2018-08-28 +* [#669](https://github.com/stripe/stripe-go/pull/669) Add `AuthorizationCode` to `Charge` +* [#671](https://github.com/stripe/stripe-go/pull/671) Fix deserialization of `TaxID` on `CustomerTaxInfo` + +## 43.0.0 - 2018-08-23 +* [#668](https://github.com/stripe/stripe-go/pull/668) Move to API version 2018-08-23 + * Add `TaxInfo` and `TaxInfoVerification` to `Customer` + * Rename `Amount` to `UnitAmount` on `PlanTierParams` + * Remove `BusinessVATID` from `Customer` + * Remove `AtPeriodEnd` from `SubscriptionCancelParams` + +## 42.3.0 - 2018-08-23 +* [#667](https://github.com/stripe/stripe-go/pull/667) Add `Forgive` to `InvoicePayParams` + +## 42.2.0 - 2018-08-22 +* [#666](https://github.com/stripe/stripe-go/pull/666) Add `Subscription` to `SubscriptionItem` + +## 42.1.0 - 2018-08-22 +* [#664](https://github.com/stripe/stripe-go/pull/664) Add `AvailablePayoutMethods` to `Card` + +## 42.0.0 - 2018-08-20 +* [#663](https://github.com/stripe/stripe-go/pull/663) Add support for usage record summaries and rename `Live` on `IssuerFraudRecord, `SourceTransaction`, and `UsageRecord` to `Livemode` (a minor breaking change) + +## 41.0.0 - 2018-08-17 +* [#659](https://github.com/stripe/stripe-go/pull/659) Remove mutating Bitcoin receiver API calls (these were no longer functional anyway) +* [#661](https://github.com/stripe/stripe-go/pull/661) Correct `IssuingCardShipping`'s type to `int64` +* [#662](https://github.com/stripe/stripe-go/pull/662) Rename `IssuingCardShipping`'s `Eta` to `ETA` + +## 40.2.0 - 2018-08-15 +* [#657](https://github.com/stripe/stripe-go/pull/657) Use integer-indexed encoding for all arrays + +## 40.1.0 - 2018-08-10 +* [#656](https://github.com/stripe/stripe-go/pull/656) Expose new `ValidatePayload` functions for validating incoming payloads without constructing an event + +## 40.0.2 - 2018-08-07 +* [#652](https://github.com/stripe/stripe-go/pull/652) Change the type of `FileUpload.Links` to `FileLinkList` (this is a bug fix given that the previous type would never have worked) + +## 40.0.1 - 2018-08-07 +* [#653](https://github.com/stripe/stripe-go/pull/653) All `BackendImplementation`s should sleep by default on retries + +## 40.0.0 - 2018-08-06 +* [#648](https://github.com/stripe/stripe-go/pull/648) Introduce buffers so a request's body can be read multiple times (this modifies the interface of a few exported internal functions so it's technically breaking, but it will probably not be breaking for most users) +* [#649](https://github.com/stripe/stripe-go/pull/649) Rename `BackendConfiguration` to `BackendImplementation` (likewise, technically breaking, but minor) +* [#650](https://github.com/stripe/stripe-go/pull/650) Export `webhook.ComputeSignature` + +## 39.0.0 - 2018-08-04 +* [#646](https://github.com/stripe/stripe-go/pull/646) Set request body before every retry (this modifies the interface of a few exported internal functions so it's technically breaking, but it will probably not be breaking for most users) + +## 38.2.0 - 2018-08-03 +* [#644](https://github.com/stripe/stripe-go/pull/644) Add support for file links +* [#645](https://github.com/stripe/stripe-go/pull/645) Add support for `Cancel` to topups + +## 38.1.0 - 2018-08-01 +* [#643](https://github.com/stripe/stripe-go/pull/643) Bug fix and various code/logging improvements to retry code + +## 38.0.0 - 2018-07-30 +* [#641](https://github.com/stripe/stripe-go/pull/641) Minor breaking changes to correct a few naming inconsistencies: + * `IdentityVerificationDetailsCodeScanIdCountryNotSupported` becomes `IdentityVerificationDetailsCodeScanIDCountryNotSupported` + * `IdentityVerificationDetailsCodeScanIdTypeNotSupported` becomes `IdentityVerificationDetailsCodeScanIDTypeNotSupported` + * `BitcoinUri` on `BitcoinReceiver` becomes `BitcoinURI` + * `NetworkId` on `IssuingAuthorization` becomes `NetworkID` + +## 37.0.0 - 2018-07-30 +* [#637](https://github.com/stripe/stripe-go/pull/637) Add support for Sigma scheduled query runs +* [#639](https://github.com/stripe/stripe-go/pull/639) Move to API version `2018-07-27` (breaking) + * Remove `SKUs` from `Product` + * Subscription creation and update can no longer take a source + * Change `PercentOff` on coupon struct and params from integer to float +* [#640](https://github.com/stripe/stripe-go/pull/640) Add missing field `Created` to `Account` + +## 36.3.0 - 2018-07-27 +* [#636](https://github.com/stripe/stripe-go/pull/636) Add `RiskScore` to `ChargeOutcome` + +## 36.2.0 - 2018-07-26 +* [#635](https://github.com/stripe/stripe-go/pull/635) Add support for Stripe Issuing + +## 36.1.2 - 2018-07-24 +* [#633](https://github.com/stripe/stripe-go/pull/633) Fix encoding of list params for bank accounts and cards + +## 36.1.1 - 2018-07-17 +* [#627](https://github.com/stripe/stripe-go/pull/627) Wire an `http.Client` from `NewBackends` through to backends + +## 36.1.0 - 2018-07-11 +* [#624](https://github.com/stripe/stripe-go/pull/624) Add `AutoAdvance` for `Invoice` + +## 36.0.0 - 2018-07-09 +* [#606](https://github.com/stripe/stripe-go/pull/606) Add support for payment intents +* [#623](https://github.com/stripe/stripe-go/pull/623) Changed `Payout.Destination` from `string` to `*PayoutDestination` to support expanding (minor breaking change) + +## 35.13.0 - 2018-07-06 +* [#622](https://github.com/stripe/stripe-go/pull/622) Correct position of `DeclineChargeOn` (it was added accidentally on `LegalEntityParams` when it should have been on `AccountParams`) + +## 35.12.0 - 2018-07-05 +* [#620](https://github.com/stripe/stripe-go/pull/620) Add support for `Quantity` and `UnitAmount` to `InvoiceItemParams` and `Quantity` to `InvoiceItem` + +## 35.11.0 - 2018-07-05 +* [#618](https://github.com/stripe/stripe-go/pull/618) Add support for `DeclineChargeOn` to `Account` and `AccountParams` + +## 35.10.0 - 2018-07-04 +* [#616](https://github.com/stripe/stripe-go/pull/616) Adding missing clients to the `API` struct including a `UsageRecords` entry + +## 35.9.0 - 2018-07-03 +* [#611](https://github.com/stripe/stripe-go/pull/611) Introduce `GetBackendWithConfig` and make logging configurable per backend + +## 35.8.0 - 2018-06-28 +* [#607](https://github.com/stripe/stripe-go/pull/607) Add support for `PartnerID` from `stripe.SetAppInfo` + +## 35.7.0 - 2018-06-26 +* [#604](https://github.com/stripe/stripe-go/pull/604) Add extra parameters `CustomerReference` and `ShippingFromZip` to `ChargeLevel3Params` and `ChargeLevel3` + +## 35.6.0 - 2018-06-25 +* [#603](https://github.com/stripe/stripe-go/pull/603) Add support for Level III data on charge creation + +## 35.5.0 - 2018-06-22 +* [#601](https://github.com/stripe/stripe-go/pull/601) Add missing parameters for retrieving an upcoming invoice + +## 35.4.0 - 2018-06-21 +* [#599](https://github.com/stripe/stripe-go/pull/599) Add `ExchangeRate` to `BalanceTransaction` + +## 35.3.0 - 2018-06-20 +* [#596](https://github.com/stripe/stripe-go/pull/596) Add `Type` to `ProductListParams` so that products can be listed by type + +## 35.2.0 - 2018-06-19 +* [#595](https://github.com/stripe/stripe-go/pull/595) Add `Product` to `PlanListParams` so that plans can be listed by product + +## 35.1.0 - 2018-06-17 +* [#592](https://github.com/stripe/stripe-go/pull/592) Add `Name` field to `Coupon` and `CouponParams` + +## 35.0.0 - 2018-06-15 +* [#557](https://github.com/stripe/stripe-go/pull/557) Add automatic retries for intermittent errors (enabling using `BackendConfiguration.SetMaxNetworkRetries`) +* [#589](https://github.com/stripe/stripe-go/pull/589) Fix all `Get` methods to support standardized parameter structs + remove some deprecated functions + * `IssuerFraudRecordListParams` now uses `*string` for `Charge` (set it using `stripe.String` like elsewhere) + * `event.Get` now takes `stripe.EventParams` instead of `Params` for consistency + * The `Get` method for `countryspec`, `exchangerate`, `issuerfraudrecord` now take an extra params struct parameter to be consistent and allow setting a connected account (use `stripe.CountrySpecParams`, `stripe.ExchangeRateParams`, and `IssuerFraudRecordParams`) + * `charge.MarkFraudulent` and `charge.MarkSafe` have been removed; use `charge.Update` instead + * `charge.CloseDispute` and `charge.UpdateDispute` have been removed; use `dispute.Update` or `dispute.Close` instead + * `loginlink.New` now properly passes its params struct into its API call + +## 34.3.0 - 2018-06-14 +* [#587](https://github.com/stripe/stripe-go/pull/587) Use `net/http` constants instead of string literals for HTTP verbs (this is an internal cleanup and should not affect library behavior) + +## 34.2.0 - 2018-06-14 +* [#581](https://github.com/stripe/stripe-go/pull/581) Push parameter encoding into `BackendConfiguration.Call` (this is an internal cleanup and should not affect library behavior) + +## 34.1.0 - 2018-06-13 +* [#586](https://github.com/stripe/stripe-go/pull/586) Add `AmountPaid`, `AmountRemaining`, `BillingReason` (including new `InvoiceBillingReason` and constants), and `SubscriptionProrationDate` to `Invoice` + +## 34.0.0 - 2018-06-12 +* [#585](https://github.com/stripe/stripe-go/pull/585) Remove `File` in favor of `FileUpload`, and consolidating both classes which were already nearly identical except `MIMEType` has been replaced by `Type` (this is technically a breaking change, but quite a small one) + +## 33.1.0 - 2018-06-12 +* [#578](https://github.com/stripe/stripe-go/pull/578) Improve expansion parsing by not discarding unmarshal errors + +## 33.0.0 - 2018-06-11 +* [#583](https://github.com/stripe/stripe-go/pull/583) Add new account constants, rename one, and fix `DueBy` (this is technically a breaking change, but quite a small one) + +## 32.4.1 - 2018-06-11 +* [#582](https://github.com/stripe/stripe-go/pull/582) Fix unmarshaling of `LegalEntity` (specifically when we have `legal_entity[additional_owners][][verification]`) so that it comes out as a struct + +## 32.4.0 - 2018-06-07 +* [#577](https://github.com/stripe/stripe-go/pull/577) Add `DocumentBack` to account legal entity identity verification parameters and response + +## 32.3.0 - 2018-06-07 +* [#576](https://github.com/stripe/stripe-go/pull/576) Fix plan transform usage to use `BucketSize` instead of `DivideBy`; note this is technically a breaking API change, but we've released it as a minor because the previous manifestation didn't work + +## 32.2.0 - 2018-06-06 +* [#571](https://github.com/stripe/stripe-go/pull/571) Add `HostedInvoiceURL` and `InvoicePDF` to `Invoice` +* [#573](https://github.com/stripe/stripe-go/pull/573) Add `FormatURLPath` helper to allow safer URL path building + +## 32.1.0 - 2018-06-06 +* [#572](https://github.com/stripe/stripe-go/pull/572) Add `Active` to plan parameters and response + +## 32.0.1 - 2018-06-06 +* [#569](https://github.com/stripe/stripe-go/pull/569) Fix unmarshaling of expanded transaction sources in balance transactions + +## 32.0.0 - 2018-06-06 +* [#544](https://github.com/stripe/stripe-go/pull/544) **MAJOR** changes that make all fields on parameter structs pointers, and rename many fields on parameter and response structs to be consistent with naming in the REST API; we've written [a migration guide with complete details](https://github.com/stripe/stripe-go/blob/master/v32_migration_guide.md) to help with the upgrade + +## 31.0.0 - 2018-06-06 +* [#566](https://github.com/stripe/stripe-go/pull/566) Support `DisputeParams` in `dispute.Close` + +## 30.8.1 - 2018-05-24 +* [#562](https://github.com/stripe/stripe-go/pull/562) Add `go.mod` for vgo support + +## 30.8.0 - 2018-05-22 +* [#558](https://github.com/stripe/stripe-go/pull/558) Add `SubscriptionItem` to `InvoiceLine` + +## 30.7.0 - 2018-05-09 +* [#552](https://github.com/stripe/stripe-go/pull/552) Add support for issuer fraud records + +## 30.6.1 - 2018-05-04 +* [#550](https://github.com/stripe/stripe-go/pull/550) Append standard `Params` as well as card options when encoding `CardParams` + +## 30.6.0 - 2018-04-17 +* [#546](https://github.com/stripe/stripe-go/pull/546) Add `SubParams.TrialFromPlan` and `SubItemsParams.ClearUsage` + +## 30.5.0 - 2018-04-09 +* [#543](https://github.com/stripe/stripe-go/pull/543) Support listing orders by customer (add `Customer` to `OrderListParams`) + +## 30.4.0 - 2018-04-06 +* [#541](https://github.com/stripe/stripe-go/pull/541) Add `Mandate` on `Source` (and associated mandate structs) + +## 30.3.0 - 2018-04-02 +* [#538](https://github.com/stripe/stripe-go/pull/538) Introduce flexible billing primitives for subscriptions + +## 30.2.0 - 2018-03-23 +* [#535](https://github.com/stripe/stripe-go/pull/535) Add constant for redirect status `not_required` (`RedirectFlowStatusNotRequired`) + +## 30.1.0 - 2018-03-17 +* [#534](https://github.com/stripe/stripe-go/pull/534) Add `AmountZero` to `InvoiceItemParams` + +## 30.0.0 - 2018-03-14 +* [#533](https://github.com/stripe/stripe-go/pull/533) Make `DestPayment` under `Transfer` expandable by changing it from a string to a `Charge` + +## 29.3.1 - 2018-03-08 +* [#530](https://github.com/stripe/stripe-go/pull/530) Fix mixed up types in `CountrySpec.SupportedBankAccountCurrencies` + +## 29.3.0 - 2018-03-01 +* [#527](https://github.com/stripe/stripe-go/pull/527) Add `MaidenName`, `PersonalIDNumber`, `PersonalIDNumberProvided` fields to `Owner` struct + +## 29.2.0 - 2018-02-26 +* [#525](https://github.com/stripe/stripe-go/pull/525) Support shipping carrier and tracking number in orders +* [#526](https://github.com/stripe/stripe-go/pull/526) Fix ignored `commonParams` when returning an order + +## 29.1.1 - 2018-02-21 +* [#522](https://github.com/stripe/stripe-go/pull/522) Bump API version and fix creating plans with a product + +## 29.1.0 - 2018-02-21 +* [#520](https://github.com/stripe/stripe-go/pull/520) Add support for topups + +## 29.0.1 - 2018-02-16 +**WARNING:** Please use 29.1.1 instead. +* [#519](https://github.com/stripe/stripe-go/pull/519) Correct the implementation of `PaymentSource.MarshalJSON` to also handle bank account sources + +## 29.0.0 - 2018-02-14 +**WARNING:** Please use 29.1.1 instead. +* [#518](https://github.com/stripe/stripe-go/pull/518) Bump API version to 2018-02-06 and add support for Product & Plan API + +## 28.12.0 - 2018-02-09 +* [#517](https://github.com/stripe/stripe-go/pull/517) Add `BillingCycleAnchor` to `Sub` and `BillingCycleAnchorUnchanged` to `SubParams` + +## 28.11.0 - 2018-01-29 +* [#516](https://github.com/stripe/stripe-go/pull/516) Add `AmountZero` to `PlanParams` to it's possible to send zero values when creating or updating a plan + +## 28.10.1 - 2018-01-18 +* [#512](https://github.com/stripe/stripe-go/pull/512) Encode empty values found in maps (like `Meta`) + +## 28.10.0 - 2018-01-09 +* [#509](https://github.com/stripe/stripe-go/pull/509) Plumb through additional possible errors when unmarshaling polymorphic types (please test your integrations while upgrading) + +## 28.9.0 - 2018-01-08 +* [#506](https://github.com/stripe/stripe-go/pull/506) Add support for recursing into slices in `event.GetObjValue` + +## 28.8.0 - 2017-12-12 +* [#500](https://github.com/stripe/stripe-go/pull/500) Support sharing for bank accounts and cards (adds `ID` field to bank account and charge parameters) + +## 28.7.0 - 2017-12-05 +* [#494](https://github.com/stripe/stripe-go/pull/494) Add `Automatic` to `Payout` struct + +## 28.6.1 - 2017-11-02 +* [#492](https://github.com/stripe/stripe-go/pull/492) Correct name of user agent header used to send Go version to Stripe's API + +## 28.6.0 - 2017-10-31 +* [#491](https://github.com/stripe/stripe-go/pull/491) Support for exchange rates APIs + +## 28.5.0 - 2017-10-27 +* [#488](https://github.com/stripe/stripe-go/pull/488) Support for listing source transactions + +## 28.4.2 - 2017-10-25 +* [#486](https://github.com/stripe/stripe-go/pull/486) Send the required `object=bank_account` parameter when adding a bank account through an account +* [#487](https://github.com/stripe/stripe-go/pull/487) Make bank account's `account_holder_name` and `account_holder_type` parameters truly optional + +## 28.4.1 - 2017-10-24 +* [#484](https://github.com/stripe/stripe-go/pull/484) Error early when params not specified for card-related API calls + +## 28.4.0 - 2017-10-19 +* [#477](https://github.com/stripe/stripe-go/pull/477) Support context on API requests with `Params.Context` and `ListParams.Context` + +## 28.3.2 - 2017-10-19 +* [#479](https://github.com/stripe/stripe-go/pull/479) Pass token in only one of `external_account` *or* source when appending card + +## 28.3.1 - 2017-10-17 +* [#476](https://github.com/stripe/stripe-go/pull/476) Make initializing new backends concurrency-safe + +## 28.3.0 - 2017-10-10 +* [#359](https://github.com/stripe/stripe-go/pull/359) Add support for verify sources (added `Values` on `SourceVerifyParams`) + +## 28.2.0 - 2017-10-09 +* [#472](https://github.com/stripe/stripe-go/pull/472) Add support for `statement_descriptor` in source objects +* [#473](https://github.com/stripe/stripe-go/pull/473) Add support for detaching sources from customers + +## 28.1.0 - 2017-10-05 +* [#471](https://github.com/stripe/stripe-go/pull/471) Add support for `RedirectFlow.FailureReason` for sources + +## 28.0.1 - 2017-10-03 +* [#468](https://github.com/stripe/stripe-go/pull/468) Fix encoding of pointer-based scalars (e.g. `Active *bool` in `Product`) +* [#470](https://github.com/stripe/stripe-go/pull/470) Fix concurrent race in `form` package's encoding caches + +## 28.0.0 - 2017-09-27 +* [#467](https://github.com/stripe/stripe-go/pull/467) Change `Product.Get` to include `ProductParams` for request metadata +* [#467](https://github.com/stripe/stripe-go/pull/467) Fix sending extra parameters on product and SKU requests + +## 27.0.2 - 2017-09-26 +* [#465](https://github.com/stripe/stripe-go/pull/465) Fix encoding of `CVC` parameter in `CardParams` + +## 27.0.1 - 2017-09-20 +* [#461](https://github.com/stripe/stripe-go/pull/461) Fix encoding of `TypeData` under sources + +## 27.0.0 - 2017-09-19 +* [#458](https://github.com/stripe/stripe-go/pull/458) Remove `ChargeParams.Token` (this seems like it was added accidentally) + +## 26.0.0 - 2017-09-17 +* Introduce `form` package so it's no longer necessary to build conditional structures to encode parameters -- this may result in parameters that were set but previously not encoded to now be encoded so **PLEASE TEST CAREFULLY WHEN UPGRADING**! +* Alphabetize all struct fields -- this may result in position-based struct initialization to fail if it was being used +* Switch to stripe-mock for testing (test suite now runs completely!) +* Remote Displayer interface and Display implementations +* Add `FraudDetails` to `ChargeParams` +* Remove `FraudReport` from `ChargeParams` (use `FraudDetails` instead) + +## 25.2.0 - 2017-09-13 +* Add `OnBehalfOf` to charge parameters. +* Add `OnBehalfOf` to subscription parameters. + +## 25.1.0 - 2017-09-06 +* Use bearer token authentication for API requests + +## 25.0.0 - 2017-08-21 +* All `Del` methods now take params as second argument (which may be `nil`) +* Product `Delete` has been renamed to `Del` for consistency +* Product `Delete` now returns `(*Product, error)` for consistency +* SKU `Delete` has been renamed to `Del` for consistency +* SKU `Delete` now returns `(*SKU, error)` for consistency + +## 24.3.0 - 2017-08-08 +* Add `FeeZero` to invoice and `TaxPercentZero` to subscription for zeroing values + +## 24.2.0 - 2017-07-25 +* Add "range queries" for supported parameters (e.g. `created[gte]=123`) + +## 24.1.0 - 2017-07-17 +* Add metadata to subscription items + +## 24.0.0 - 2017-06-27 + `Pay` on invoice now takes specific pay parameters + +## 23.2.1 - 2017-06-26 +* Fix bank account retrieval when using a customer ID + +## 23.2.0 - 2017-06-26 +* Support sharing path while creating a source + +## 23.1.0 - 2017-06-26 +* Add LoginLinks to client list + +## 23.0.0 - 2017-06-23 + plan.Del now takes `stripe.PlanParams` as a second argument + +## 22.6.0 - 2017-06-19 +* Support for ephemeral keys + +## 22.5.0 - 2017-06-15 +* Support for checking webhook signatures + +## 22.4.1 - 2017-06-15 +* Fix returned type of subscription items list +* Note: I meant to release this as 22.3.1, but I'm leaving it as it was released + +## 22.3.0 - 2017-06-14 +* Fix parameters for subscription items list + +## 22.2.0 - 2017-06-13 +* Support subscription items when getting upcoming invoice +* Support setting subscription's quantity to zero when getting upcoming invoice + +## 22.1.1 - 2017-06-12 +* Handle `deleted` parameter when updating subscription items in a subscription + +## 22.1.0 - 2017-05-25 +* Change `Logger` to a `log.Logger`-like interface so other loggers are usable + +## 22.0.0 - 2017-05-25 +* Add support for login links +* Add support for new `Type` for accounts +* Make `Event` `Request` (renamed from `Req`) a struct with a new idempotency key +* Rename `Event` `UserID` to `Account` + +## 21.5.1 - 2017-05-23 +* Fix plan update so `TrialPeriod` parameter is sent + +## 21.5.0 - 2017-05-15 +* Implement `Get` for `RequestValues` + +## 21.4.1 - 2017-05-11 +* Pass extra parameters to API calls on bank account deletion + +## 21.4.0 - 2017-05-04 +* Add `Billing` and `DueDate` filters to invoice listing +* Add `Billing` filter to subscription listing + +## 21.3.0 - 2017-05-02 +* Add `DetailsCode` to `IdentityVerification` + +## 21.2.0 - 2017-04-19 +* Send user agent information with `X-Stripe-Client-User-Agent` +* Add `stripe.SetAppInfo` for plugin authors to register app information + +## 21.1.0 - 2017-04-12 +* Allow coupon to be specified when creating orders +* No longer require that items have descriptions when creating orders + +## 21.0.0 - 2017-04-07 +* Balances are now retrieved by payout instead of by transfer + +## 20.0.0 - 2017-04-06 +* Bump API version to 2017-04-06: https://stripe.com/docs/upgrades#2017-04-06 +* Add support for payouts and recipient transfers +* Change the transfer resource to support its new format +* Deprecate recipient creation +* Disputes under charges are now expandable and collapsed by default +* Rules under charge outcomes are now expandable and collapsed by default + +## 19.17.0 - 2017-04-06 +* Please see 20.0.0 (bad release) + +## 19.16.0 - 2017-03-23 +* Allow the ID of an identity document to be passed into an account owner update + +## 19.15.0 - 2017-03-22 +* Add `ShippingCarrier` to dispute evidence + +## 19.14.0 - 2017-03-20 +* Add `Period`, `Plan`, and `Quantity` to `InvoiceItem` + +## 19.13.0 - 2017-03-20 +* Add `AdditionalOwnersEmpty` to allow additional owners to be unset + +## 19.12.0 - 2017-03-17 +* Add new form of file upload using `io.FileReader` and filename + +## 19.11.0 - 2017-03-13 +* Add `Token` to `SourceObjectParams` + +## 19.10.0 - 2017-03-13 +* Add `CouponEmpty` (allowing a coupon to be cleared) to customer parameters +* Add `CouponEmpty` (allowing a coupon to be cleared) to subscription parameters + +## 19.9.0 - 2017-03-08 +* Add missing value "all" to subscription statuses + +## 19.8.0 - 2017-03-02 +* Add subscription items client to main `client.API` struct + +## 19.7.0 - 2017-03-01 +* Add `Statement` (statement descriptor) to `CaptureParams` + +## 19.6.0 - 2017-02-22 +* Add new parameters for invoices and subscriptions + +## 19.5.0 - 2017-02-13 +* Add new rich `Destination` type to `ChargeParams` + +## 19.4.0 - 2017-02-03 +* Support Connect account as payment source + +## 19.3.0 - 2017-02-02 +* Add transfer group to charges and transfers + +## 19.2.0 - 2017-01-23 +* Add `Rule` to `ChargeOutcome` + +## 19.1.0 - 2017-01-18 +* Add support for updating sources + +## 19.0.2 - 2017-01-04 +* Fix subscription `trial_period_days` to be populated by the right value + +## 19.0.1 - 2016-12-08 +* Include verification document details when persisting `LegalEntity` + +## 19.0.0 - 2016-12-07 +* Remote `SubProrationDateNow` field from `InvoiceParams` + +## 18.14.1 - 2016-12-05 +* Truncate `tax_percent` at four decimals (e.g. 3.9750%) instead of two + +## 18.14.0 - 2016-11-23 +* Add retrieve method for 3-D Secure resources + +## 18.13.0 - 2016-11-15 +* Add `PaymentSource` to `API` + +## 18.12.0 - 2016-11-14 +* Allow bank accounts to be created as a customer source + +## 18.11.0 - 2016-11-14 +* Add `TrialPeriodEnd` to `SubParams` + +## 18.10.0 - 2016-11-09 +* Add `StatusTransitions` to `Order` + +## 18.9.0 - 2016-11-04 +* Add `Application` to `Charge` + +## 18.8.0 - 2016-10-24 +* Add `Review` to `Charge` for the charge reviews + +## 18.7.0 - 2016-10-18 +* Add `RiskLevel` to `ChargeOutcome` + +## 18.6.0 - 2016-10-18 +* Support for 403 status codes (permission denied) + +## 18.5.0 - 2016-10-18 +* Add `Status` to `SubListParams` to allow filtering subscriptions by status + +## 18.4.0 - 2016-10-14 +* Add `HasEvidence` and `PastDue` to `EvidenceDetails` + +## 18.3.0 - 2016-10-10 +* Add `NoDiscountable` to `InvoiceItemParams` + +## 18.2.0 - 2016-10-10 +* Add `BusinessLogo` to `Account` +* Add `ReceiptNumber` to `Charge` +* Add `DestPayment` to `Transfer` + +## 18.1.0 - 2016-10-04 +* Support for Apple Pay domains + +## 18.0.0 - 2016-10-03 +* Support for subscription items +* Correct `SourceTx` on `Transfer` to be a `SourceTransaction` +* Change `Charge` on `Resource` to be expandable (now a struct instead of string) + +## 17.5.0 - 2016-09-22 +* Support customer-related operations for bank accounts + +## 17.4.2 - 2016-09-19 +* Fix but where some parameters were not being included on order update + +## 17.4.1 - 2016-09-15 +* Fix bug that required a date of birth to be included on account update + +## 17.4.0 - 2016-09-13 +* Add missing Kana and Kanji address and name fields to account's legal entity +* Add `ReceiptNumber` and `Status` to `Refund` + +## 17.3.0 - 2016-09-07 +* Add support for sources endpoint + +## 17.2.0 - 2016-08-29 +* Add order returns to `API` + +## 17.1.0 - 2016-08-22 +* Add `DeactiveOn` to `Product` + +## 17.0.0 - 2016-08-18 +* Allow expansion of destination on transfers +* Allow expansion of sources on balance transactions + +## 16.8.0 - 2016-08-17 +* Add `OriginatingTransaction` to `Fee` + +## 16.7.1 - 2016-08-17 +* Allow params to be nil when retrieving a refund + +## 16.7.0 - 2016-08-11 +* Add support for 3-D Secure + +## 16.6.0 - 2016-08-09 +* Add `ReceiptNumber` to `Invoice` + +## 16.5.0 - 2016-08-08 +* Add `Meta` to `Account` + +## 16.4.0 - 2016-08-05 +* Allow the migration of recipients to accounts +* Add `MigratedTo` to `Recipient` + +## 16.3.1 - 2016-07-25 +* URL-escape the IDs of coupons and plans when making API requests + +## 16.3.0 - 2016-07-19 +* Add `NoClosed` to `InvoiceParams` to allow an invoice to be reopened + +## 16.2.1 - 2016-07-11 +* Consider `SubParams.QuantityZero` when updating a subscription + +## 16.2.0 - 2016-07-07 +* Upgrade API version to 2016-07-06 + +## 16.1.0 - 2016-07-07 +* Add `Returns` field to `Order` + +## 16.0.0 - 2016-06-30 +* Remove `Name` field on `SKU`; it's not actually supported +* Support updating `Product` on `SKU` + +## 15.6.0 - 2016-06-24 +* Allow product and SKU attributes to be updated + +## 15.5.0 - 2016-06-24 +* Add `TaxPercent` and `TaxPercentZero` to `CustomerParams` + +## 15.4.0 - 2016-06-20 +* Add `TokenizationMethod` to `Card` struct + +## 15.3.0 - 2016-06-15 +* Add `BalanceZero` to `CustomerParams` so that balance can be zeroed out + +## 15.2.0 - 2016-06-03 +* Add `ToValues` to `RequestValues` struct + +## 15.1.0 - 2016-05-26 +* Add `BusinessVatID` to customer creation parameters + +## 15.0.0 - 2016-05-24 +* Fix handling of nested objects in arrays in request parameters + +## 14.4.0 - 2016-05-24 +* Add granular error types in new `Err` field on `stripe.Error` + +## 14.3.0 - 2016-05-20 +* Allow Relay orders to be returned and add associated types + +## 14.2.3 - 2016-05-20 +* When creating a bank account token, only send routing number if it's been set + +## 14.2.2 - 2016-05-17 +* When creating a bank account, only send routing number if it's been set + +## 14.2.1 - 2016-05-17 +* Add missing SKU clinet to client API type + +## 14.2.0 - 2016-05-11 +* Add `Reversed` and `AmountReversed` fields to `Transfer` + +## 14.1.0 - 2016-05-05 +* Allow `default_for_currency` to be set when creating a card + +## 14.0.0 - 2016-05-04 +* Change the signature for `sub.Delete`. The customer ID is no longer required. + +## 13.12.0 - 2016-04-28 +* Add `Currency` to `Card` + +## 13.11.1 - 2016-04-22 +* Fix bug where new external accounts could not be marked default from token + +## 13.11.0 - 2016-04-21 +* Expose a number of list types that were previously internal (full list below) +* Expose `stripe.AccountList` +* Expose `stripe.TransactionList` +* Expose `stripe.BitcoinReceiverList` +* Expose `stripe.ChargeList` +* Expose `stripe.CountrySpecList` +* Expose `stripe.CouponList` +* Expose `stripe.CustomerList` +* Expose `stripe.DisputeList` +* Expose `stripe.EventList` +* Expose `stripe.FeeList` +* Expose `stripe.FileUploadList` +* Expose `stripe.InvoiceList` +* Expose `stripe.OrderList` +* Expose `stripe.ProductList` +* Expose `stripe.RecipientList` +* Expose `stripe.TransferList` +* Switch to use of `stripe.BitcoinTransactionList` +* Switch to use of `stripe.SKUList` + +## 13.10.1 - 2016-04-20 +* Add support for `TaxPercentZero` to invoice and subscription updates + +## 13.10.0 - 2016-04-19 +* Expose `stripe.PlanList` (previously an internal type) + +## 13.9.0 - 2016-04-18 +* Add `TaxPercentZero` struct to `InvoiceParams` +* Add `TaxPercentZero` to `SubParams` + +## 13.8.0 - 2016-04-12 +* Add `Outcome` struct to `Charge` + +## 13.7.0 - 2016-04-06 +* Add `Description`, `IIN`, and `Issuer` to `Card` + +## 13.6.0 - 2016-04-05 +* Add `SourceType` (and associated constants) to `Transfer` + +## 13.5.0 - 2016-03-29 +* Add `Meta` (metadata) to `BankAccount` + +## 13.4.0 - 2016-03-29 +* Add `Meta` (metadata) to `Card` + +## 13.3.0 - 2016-03-29 +* Add `DefaultCurrency` to `CountrySpec` + +## 13.2.0 - 2016-03-18 +* Add `SourceTransfer` to `Charge` +* Add `SourceTx` to `Transfer` + +## 13.1.0 - 2016-03-15 +* Add `Reject` on `Account` to support the new API feature + +## 13.0.0 - 2016-03-15 +* Upgrade API version to 2016-03-07 +* Remove `Account.BankAccounts` in favor of `ExternalAccounts` +* Remove `Account.Currencies` in favor of `CountrySpec` + +## 12.1.0 - 2016-02-04 +* Add `ListParams.StripeAccount` for making list calls on behalf of connected accounts +* Add `Params.StripeAccount` for symmetry with `ListParams.StripeAccount` +* Deprecate `Params.Account` in favor of `Params.StripeAccount` + +## 12.0.0 - 2016-02-02 +* Add support for fetching events for managed accounts (`event.Get` now takes `Params`) + +## 11.5.0 - 2016-02-26 +* Allow a `PII.PersonalIDNumber` number to be used to create a token + +## 11.4.0 - 2016-02-24 +* Add missing subscription fields to `InvoiceParams` for use with `invoice.GetNext` + +## 11.3.0 - 2016-02-19 +* Add `AccountHolderName` and `AccountHolderType` to bank accounts + +## 11.2.0 - 2016-02-11 +* Add support for `CountrySpec` +* Add `SSNProvided`, `PersonalIDProvided` and `BusinessTaxIDProvided` to `LegalEntity` + +## 11.1.2 - 2016-02-02 +* Fix card update method to correctly take expiration date + +## 11.1.1 - 2016-02-01 +* Fix recipient update so that it can take a bank token (like create) + +## 11.0.1 - 2016-01-11 +* Add missing field `country` to shipping details of `Charge` and `Customer` + +## 11.0.0 - 2016-01-07 +* Add missing field `Default` to `BankAccount` +* Add `OrderParams` parameter to `Order` retrieval +* Fix parameter bug when creating a new `Order` +* Support special value of 'now' for trial end when updating subscriptions + +## 10.3.0 - 2015-12-10 +* Allow an account to be referenced when creating a card + +## 10.2.0 - 2015-12-04 +* Add `Update` function on `Coupon` client so that metadata can be set + +## 10.1.0 - 2015-12-01 +* Add a verification routine for external accounts + +## 10.0.0 - 2015-11-30 +* Return models along with `error` when deleting resources with `Del` +* Fix bug where country parameter wasn't included for some account creation + +## 9.0.0 - 2015-11-13 +* Return model (`Sub`) when cancelling a subscription (`sub.Cancel`) + +## 8.0.0 - 2015-08-17 +* Add ability to list and retrieve refunds without a Charge + +## 7.0.0 - 2015-08-03 +* Add ability to list and retrieve disputes + +## 6.8.0 - 2015-07-29 +* Add ability to delete an account + +## 6.7.1 - 2015-07-17 +* Bug fixes + +## 6.7.0 - 2015-07-16 +* Expand logging object +* Move proration date to subscription update +* Send country when creating/updating account + +## 6.6.0 - 2015-07-06 +* Add request ID to errors + +## 6.5.0 - 2015-07-06 +* Update bank account creation API +* Add destination, application fee, transfer to Charge struct +* Add missing fields to invoice line item +* Rename deprecated customer param value + +## 6.4.2 - 2015-06-23 +* Add BusinessUrl, BusinessUrl, BusinessPrimaryColor, SupportEmail, and +* SupportUrl to Account. + +## 6.4.1 - 2015-06-16 +* Change card.dynamic_last_four to card.dynamic_last4 + +## 6.4.0 - 2015-05-28 +* Rename customer.default_card -> default_source + +## 6.3.0 - 2015-05-19 +* Add shipping address to charges +* Expose card.dynamic_last_four +* Expose account.tos_acceptance +* Bug fixes +* Bump API version to most recent one + +## 6.2.0 - 2015-04-09 +* Bug fixes +* Add Extra to parameters + +## 6.1.0 - 2015-03-17 +* Add TaxPercent for subscriptions +* Event bug fixes + +## 6.0.0 - 2015-03-15 +* Add more operations for /accounts endpoint +* Add /transfers/reversals endpoint +* Add /accounts/bank_accounts endpoint +* Add support for Stripe-Account header + +## 5.1.0 - 2015-02-25 +* Add new dispute status `warning_closed` +* Add SubParams.TrialEndNow to support `trial_end = "now"` + +## 5.0.1 - 2015-02-25 +* Fix URL for upcoming invoices + +## 5.0.0 - 2015-02-19 +* Bump to API version 2014-02-18 +* Change Card, DefaultCard, Cards to Source, DefaultSource, Sources in Stripe response objects +* Add paymentsource package for manipulating Customer's sources +* Support Update action for Bitcoin Receivers + +## 4.4.3 - 2015-02-08 +* Modify NewIdempotencyKey() algorithm to increase likelihood of randomness + +## 4.4.2 - 2015-01-24 +* Add BankAccountParams.Token +* Add Token.ClientIP +* Add LogLevel + +## 4.4.0 - 2015-01-20 +* Add Bitcoin support + +## 4.3.0 - 2015-01-13 +* Added support for listing FileUploads +* Mime parameter on FileUpload has been changed to Type + +## 4.2.1 - 2014-12-28 +* Handle charges with customer card tokens + +## 4.2.0 - 2014-12-18 +* Add idempotency support + +## 4.1.0 - 2014-12-17 +* Bump to API version 2014-12-17. + +## 4.0.0 - 2014-12-16 +* Add FileUpload resource. This brings in a new endpoint (uploads.stripe.com) and thus makes changes to some of the existing interfaces. +* This also adds support for multipart content. + +## 3.1.0 - 2014-12-16 +* Add Charge.FraudDetails + +## 3.0.1 - 2014-12-15 +* Add timeout value to HTTP requests + +## 3.0.0 - 2014-12-05 +* Add Dispute.EvidenceDetails +* Remove Dispute.DueDate +* Change Dispute.Evidence from string to struct + +## 2.0.0 - 2014-11-26 +* Change List interface to .Next() and .Resource() +* Better error messages for Get() methods +* EventData.Raw contains the raw event message +* SubParams.QuantityZero can be used for free subscriptions + +## 1.0.3 - 2014-10-22 +* Add AddMeta method + +## 1.0.2 - 2014-09-23 +* Minor fixes + +## 1.0.1 - 2014-09-23 +* Linter-based updates + +## 1.0.0 - 2014-09-22 +* Initial version diff --git a/vendor/github.com/stripe/stripe-go/CODE_OF_CONDUCT.md b/vendor/github.com/stripe/stripe-go/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..349f5a0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/CODE_OF_CONDUCT.md @@ -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 + diff --git a/vendor/github.com/stripe/stripe-go/LICENSE b/vendor/github.com/stripe/stripe-go/LICENSE new file mode 100644 index 0000000..2754f88 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/LICENSE @@ -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. diff --git a/vendor/github.com/stripe/stripe-go/Makefile b/vendor/github.com/stripe/stripe-go/Makefile new file mode 100644 index 0000000..c9fb56c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/Makefile @@ -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 diff --git a/vendor/github.com/stripe/stripe-go/README.md b/vendor/github.com/stripe/stripe-go/README.md new file mode 100644 index 0000000..ceb1db9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/README.md @@ -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 + + diff --git a/vendor/github.com/stripe/stripe-go/VERSION b/vendor/github.com/stripe/stripe-go/VERSION new file mode 100644 index 0000000..d5e9eba --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/VERSION @@ -0,0 +1 @@ +70.5.0 diff --git a/vendor/github.com/stripe/stripe-go/account.go b/vendor/github.com/stripe/stripe-go/account.go new file mode 100644 index 0000000..2401088 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/account.go @@ -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 +// account’s 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 +// account’s 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 account’s 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"` +} diff --git a/vendor/github.com/stripe/stripe-go/accountlink.go b/vendor/github.com/stripe/stripe-go/accountlink.go new file mode 100644 index 0000000..38357f1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/accountlink.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/address.go b/vendor/github.com/stripe/stripe-go/address.go new file mode 100644 index 0000000..50db8ef --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/address.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/applepaydomain.go b/vendor/github.com/stripe/stripe-go/applepaydomain.go new file mode 100644 index 0000000..3ec6e06 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/applepaydomain.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/application.go b/vendor/github.com/stripe/stripe-go/application.go new file mode 100644 index 0000000..79136e6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/application.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/balance.go b/vendor/github.com/stripe/stripe-go/balance.go new file mode 100644 index 0000000..c4c45ca --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/balance.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/balancetransaction.go b/vendor/github.com/stripe/stripe-go/balancetransaction.go new file mode 100644 index 0000000..958e11a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/balancetransaction.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/bankaccount.go b/vendor/github.com/stripe/stripe-go/bankaccount.go new file mode 100644 index 0000000..08be247 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/bankaccount.go @@ -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 user’s 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 +} diff --git a/vendor/github.com/stripe/stripe-go/bitcoinreceiver.go b/vendor/github.com/stripe/stripe-go/bitcoinreceiver.go new file mode 100644 index 0000000..7acf81e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/bitcoinreceiver.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/bitcointransaction.go b/vendor/github.com/stripe/stripe-go/bitcointransaction.go new file mode 100644 index 0000000..af2b8f7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/bitcointransaction.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/capability.go b/vendor/github.com/stripe/stripe-go/capability.go new file mode 100644 index 0000000..b79e5d0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/capability.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/card.go b/vendor/github.com/stripe/stripe-go/card.go new file mode 100644 index 0000000..ac705cf --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/card.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/charge.go b/vendor/github.com/stripe/stripe-go/charge.go new file mode 100644 index 0000000..2d81f05 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/charge.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/checkout_session.go b/vendor/github.com/stripe/stripe-go/checkout_session.go new file mode 100644 index 0000000..71511f4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/checkout_session.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/countryspec.go b/vendor/github.com/stripe/stripe-go/countryspec.go new file mode 100644 index 0000000..894beb1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/countryspec.go @@ -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:"*"` +} diff --git a/vendor/github.com/stripe/stripe-go/coupon.go b/vendor/github.com/stripe/stripe-go/coupon.go new file mode 100644 index 0000000..d6aaf6f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/coupon.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/creditnote.go b/vendor/github.com/stripe/stripe-go/creditnote.go new file mode 100644 index 0000000..0f3bbcf --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/creditnote.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/currency.go b/vendor/github.com/stripe/stripe-go/currency.go new file mode 100644 index 0000000..2de6749 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/currency.go @@ -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 +) diff --git a/vendor/github.com/stripe/stripe-go/customer.go b/vendor/github.com/stripe/stripe-go/customer.go new file mode 100644 index 0000000..7c1888b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/customer.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/customerbalancetransaction.go b/vendor/github.com/stripe/stripe-go/customerbalancetransaction.go new file mode 100644 index 0000000..764778c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/customerbalancetransaction.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/discount.go b/vendor/github.com/stripe/stripe-go/discount.go new file mode 100644 index 0000000..d86a4e6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/discount.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/dispute.go b/vendor/github.com/stripe/stripe-go/dispute.go new file mode 100644 index 0000000..3c074ef --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/dispute.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/ephemeralkey.go b/vendor/github.com/stripe/stripe-go/ephemeralkey.go new file mode 100644 index 0000000..c513977 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/ephemeralkey.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/error.go b/vendor/github.com/stripe/stripe-go/error.go new file mode 100644 index 0000000..94d0f48 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/error.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/event.go b/vendor/github.com/stripe/stripe-go/event.go new file mode 100644 index 0000000..973e6c2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/event.go @@ -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) +} diff --git a/vendor/github.com/stripe/stripe-go/exchangerate.go b/vendor/github.com/stripe/stripe-go/exchangerate.go new file mode 100644 index 0000000..f21f66c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/exchangerate.go @@ -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:"*"` +} diff --git a/vendor/github.com/stripe/stripe-go/fee.go b/vendor/github.com/stripe/stripe-go/fee.go new file mode 100644 index 0000000..bc986f7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/fee.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/feerefund.go b/vendor/github.com/stripe/stripe-go/feerefund.go new file mode 100644 index 0000000..9d1ffa5 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/feerefund.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/file.go b/vendor/github.com/stripe/stripe-go/file.go new file mode 100644 index 0000000..00a3cdc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/file.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/filelink.go b/vendor/github.com/stripe/stripe-go/filelink.go new file mode 100644 index 0000000..19615ff --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/filelink.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/form/form.go b/vendor/github.com/stripe/stripe-go/form/form.go new file mode 100644 index 0000000..8008ea8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/form/form.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/invoice.go b/vendor/github.com/stripe/stripe-go/invoice.go new file mode 100644 index 0000000..d976857 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/invoice.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/invoiceitem.go b/vendor/github.com/stripe/stripe-go/invoiceitem.go new file mode 100644 index 0000000..a998775 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/invoiceitem.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/issuing_authorization.go b/vendor/github.com/stripe/stripe-go/issuing_authorization.go new file mode 100644 index 0000000..b236ad7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/issuing_authorization.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/issuing_card.go b/vendor/github.com/stripe/stripe-go/issuing_card.go new file mode 100644 index 0000000..d188e2f --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/issuing_card.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/issuing_cardholder.go b/vendor/github.com/stripe/stripe-go/issuing_cardholder.go new file mode 100644 index 0000000..e39f0cd --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/issuing_cardholder.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/issuing_dispute.go b/vendor/github.com/stripe/stripe-go/issuing_dispute.go new file mode 100644 index 0000000..47df5bb --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/issuing_dispute.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/issuing_transaction.go b/vendor/github.com/stripe/stripe-go/issuing_transaction.go new file mode 100644 index 0000000..817f605 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/issuing_transaction.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/iter.go b/vendor/github.com/stripe/stripe-go/iter.go new file mode 100644 index 0000000..c11b621 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/iter.go @@ -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] + } +} diff --git a/vendor/github.com/stripe/stripe-go/log.go b/vendor/github.com/stripe/stripe-go/log.go new file mode 100644 index 0000000..7604216 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/log.go @@ -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) +} diff --git a/vendor/github.com/stripe/stripe-go/loginlink.go b/vendor/github.com/stripe/stripe-go/loginlink.go new file mode 100644 index 0000000..b89ef32 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/loginlink.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/mandate.go b/vendor/github.com/stripe/stripe-go/mandate.go new file mode 100644 index 0000000..2caec93 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/mandate.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/oauth.go b/vendor/github.com/stripe/stripe-go/oauth.go new file mode 100644 index 0000000..a899689 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/oauth.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/order.go b/vendor/github.com/stripe/stripe-go/order.go new file mode 100644 index 0000000..9e911de --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/order.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/orderreturn.go b/vendor/github.com/stripe/stripe-go/orderreturn.go new file mode 100644 index 0000000..ee35cd9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/orderreturn.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/params.go b/vendor/github.com/stripe/stripe-go/params.go new file mode 100644 index 0000000..dd782ec --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/params.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/paymentintent.go b/vendor/github.com/stripe/stripe-go/paymentintent.go new file mode 100644 index 0000000..89c1c8b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/paymentintent.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/paymentintent/client.go b/vendor/github.com/stripe/stripe-go/paymentintent/client.go new file mode 100644 index 0000000..f428f2e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/paymentintent/client.go @@ -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} +} diff --git a/vendor/github.com/stripe/stripe-go/paymentmethod.go b/vendor/github.com/stripe/stripe-go/paymentmethod.go new file mode 100644 index 0000000..99c52c3 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/paymentmethod.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/paymentsource.go b/vendor/github.com/stripe/stripe-go/paymentsource.go new file mode 100644 index 0000000..4f59294 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/paymentsource.go @@ -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) +} diff --git a/vendor/github.com/stripe/stripe-go/payout.go b/vendor/github.com/stripe/stripe-go/payout.go new file mode 100644 index 0000000..aae9502 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/payout.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/person.go b/vendor/github.com/stripe/stripe-go/person.go new file mode 100644 index 0000000..f439939 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/person.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/plan.go b/vendor/github.com/stripe/stripe-go/plan.go new file mode 100644 index 0000000..ffbf90b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/plan.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/product.go b/vendor/github.com/stripe/stripe-go/product.go new file mode 100644 index 0000000..de6785a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/product.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/radar_earlyfraudwarning.go b/vendor/github.com/stripe/stripe-go/radar_earlyfraudwarning.go new file mode 100644 index 0000000..f2350d9 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/radar_earlyfraudwarning.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/radar_valuelist.go b/vendor/github.com/stripe/stripe-go/radar_valuelist.go new file mode 100644 index 0000000..a8a39e8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/radar_valuelist.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/radar_valuelistitem.go b/vendor/github.com/stripe/stripe-go/radar_valuelistitem.go new file mode 100644 index 0000000..98dfcbc --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/radar_valuelistitem.go @@ -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"` +} diff --git a/vendor/github.com/stripe/stripe-go/recipient.go b/vendor/github.com/stripe/stripe-go/recipient.go new file mode 100644 index 0000000..7b1676a --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/recipient.go @@ -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 +} diff --git a/vendor/github.com/stripe/stripe-go/recipienttransfer.go b/vendor/github.com/stripe/stripe-go/recipienttransfer.go new file mode 100644 index 0000000..854beec --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/recipienttransfer.go @@ -0,0 +1,155 @@ +package stripe + +import "encoding/json" + +// RecipientTransferDestinationType consts represent valid recipient_transfer destinations. +type RecipientTransferDestinationType string + +// List of values that RecipientTransferDestinationType can take. +const ( + RecipientTransferDestinationBankAccount RecipientTransferDestinationType = "bank_account" + RecipientTransferDestinationCard RecipientTransferDestinationType = "card" +) + +// RecipientTransferFailureCode is the list of allowed values for the recipient_transfer's failure code. +type RecipientTransferFailureCode string + +// List of values that RecipientTransferFailureCode can take. +const ( + RecipientTransferFailureCodeAccountClosed RecipientTransferFailureCode = "account_closed" + RecipientTransferFailureCodeAccountFrozen RecipientTransferFailureCode = "account_frozen" + RecipientTransferFailureCodeBankAccountRestricted RecipientTransferFailureCode = "bank_account_restricted" + RecipientTransferFailureCodeBankOwnershipChanged RecipientTransferFailureCode = "bank_ownership_changed" + RecipientTransferFailureCodeDebitNotAuthorized RecipientTransferFailureCode = "debit_not_authorized" + RecipientTransferFailureCodeCouldNotProcess RecipientTransferFailureCode = "could_not_process" + RecipientTransferFailureCodeInsufficientFunds RecipientTransferFailureCode = "insufficient_funds" + RecipientTransferFailureCodeInvalidAccountNumber RecipientTransferFailureCode = "invalid_account_number" + RecipientTransferFailureCodeInvalidCurrency RecipientTransferFailureCode = "invalid_currency" + RecipientTransferFailureCodeNoAccount RecipientTransferFailureCode = "no_account" +) + +// RecipientTransferSourceType is the list of allowed values for the recipient_transfer's source_type field. +type RecipientTransferSourceType string + +// List of values that RecipientTransferSourceType can take. +const ( + RecipientTransferSourceTypeAlipayAccount RecipientTransferSourceType = "alipay_account" + RecipientTransferSourceTypeBankAccount RecipientTransferSourceType = "bank_account" + RecipientTransferSourceTypeBitcoinReceiver RecipientTransferSourceType = "bitcoin_receiver" + RecipientTransferSourceTypeCard RecipientTransferSourceType = "card" +) + +// RecipientTransferStatus is the list of allowed values for the recipient_transfer's status. +type RecipientTransferStatus string + +// List of values that RecipientTransferStatus can take. +const ( + RecipientTransferStatusFailed RecipientTransferStatus = "failed" + RecipientTransferStatusInTransit RecipientTransferStatus = "in_transit" + RecipientTransferStatusPaid RecipientTransferStatus = "paid" + RecipientTransferStatusPending RecipientTransferStatus = "pending" +) + +// RecipientTransferType is the list of allowed values for the recipient_transfer's type. +type RecipientTransferType string + +// List of values that RecipientTransferType can take. +const ( + RecipientTransferTypeBankAccount RecipientTransferType = "bank_account" + RecipientTransferTypeCard RecipientTransferType = "card" +) + +// RecipientTransferMethodType represents the type of recipient_transfer +type RecipientTransferMethodType string + +// List of values that RecipientTransferMethodType can take. +const ( + RecipientTransferMethodInstant RecipientTransferMethodType = "instant" + RecipientTransferMethodStandard RecipientTransferMethodType = "standard" +) + +// RecipientTransferDestination describes the destination of a RecipientTransfer. +// The Type should indicate which object is fleshed out +// For more details see https://stripe.com/docs/api/go#recipient_transfer_object +type RecipientTransferDestination struct { + BankAccount *BankAccount `json:"-"` + Card *Card `json:"-"` + ID string `json:"id"` + Type RecipientTransferDestinationType `json:"object"` +} + +// RecipientTransfer is the resource representing a Stripe recipient_transfer. +// For more details see https://stripe.com/docs/api#recipient_transfers. +type RecipientTransfer struct { + Amount int64 `json:"amount"` + AmountReversed int64 `json:"amount_reversed"` + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + BankAccount *BankAccount `json:"bank_account"` + Card *Card `json:"card"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + Date int64 `json:"date"` + Description string `json:"description"` + Destination string `json:"destination"` + FailureCode RecipientTransferFailureCode `json:"failure_code"` + FailureMessage string `json:"failure_message"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Metadata map[string]string `json:"metadata"` + Method RecipientTransferMethodType `json:"method"` + Recipient *Recipient `json:"recipient"` + Reversals *ReversalList `json:"reversals"` + Reversed bool `json:"reversed"` + SourceTransaction *BalanceTransactionSource `json:"source_transaction"` + SourceType RecipientTransferSourceType `json:"source_type"` + StatementDescriptor string `json:"statement_descriptor"` + Status RecipientTransferStatus `json:"status"` + Type RecipientTransferType `json:"type"` +} + +// UnmarshalJSON handles deserialization of a RecipientTransfer. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *RecipientTransfer) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type recipientTransfer RecipientTransfer + var v recipientTransfer + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = RecipientTransfer(v) + return nil +} + +// UnmarshalJSON handles deserialization of a RecipientTransferDestination. +// This custom unmarshaling is needed because the specific +// type of destination it refers to is specified in the JSON +func (d *RecipientTransferDestination) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + d.ID = id + return nil + } + + type recipientTransferDestination RecipientTransferDestination + var v recipientTransferDestination + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + var err error + *d = RecipientTransferDestination(v) + + switch d.Type { + case RecipientTransferDestinationBankAccount: + err = json.Unmarshal(data, &d.BankAccount) + case RecipientTransferDestinationCard: + err = json.Unmarshal(data, &d.Card) + } + + return err +} diff --git a/vendor/github.com/stripe/stripe-go/refund.go b/vendor/github.com/stripe/stripe-go/refund.go new file mode 100644 index 0000000..662c257 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/refund.go @@ -0,0 +1,103 @@ +package stripe + +import "encoding/json" + +// RefundFailureReason is, if set, the reason the refund failed. +type RefundFailureReason string + +// List of values that RefundFailureReason can take. +const ( + RefundFailureReasonExpiredOrCanceledCard RefundFailureReason = "expired_or_canceled_card" + RefundFailureReasonLostOrStolenCard RefundFailureReason = "lost_or_stolen_card" + RefundFailureReasonUnknown RefundFailureReason = "unknown" +) + +// RefundReason is, if set, the reason the refund is being made +type RefundReason string + +// List of values that RefundReason can take. +const ( + RefundReasonDuplicate RefundReason = "duplicate" + RefundReasonExpiredUncapturedCharge RefundReason = "expired_uncaptured_charge" + RefundReasonFraudulent RefundReason = "fraudulent" + RefundReasonRequestedByCustomer RefundReason = "requested_by_customer" +) + +// RefundStatus is the status of the refund. +type RefundStatus string + +// List of values that RefundStatus can take. +const ( + RefundStatusCanceled RefundStatus = "canceled" + RefundStatusFailed RefundStatus = "failed" + RefundStatusPending RefundStatus = "pending" + RefundStatusSucceeded RefundStatus = "succeeded" +) + +// RefundParams is the set of parameters that can be used when refunding a charge. +// For more details see https://stripe.com/docs/api#refund. +type RefundParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + Charge *string `form:"charge"` + PaymentIntent *string `form:"payment_intent"` + Reason *string `form:"reason"` + RefundApplicationFee *bool `form:"refund_application_fee"` + ReverseTransfer *bool `form:"reverse_transfer"` +} + +// RefundListParams is the set of parameters that can be used when listing refunds. +// For more details see https://stripe.com/docs/api#list_refunds. +type RefundListParams struct { + ListParams `form:"*"` + Charge *string `form:"charge"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` + PaymentIntent *string `form:"payment_intent"` +} + +// Refund is the resource representing a Stripe refund. +// For more details see https://stripe.com/docs/api#refunds. +type Refund struct { + Amount int64 `json:"amount"` + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + Charge *Charge `json:"charge"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + FailureReason RefundFailureReason `json:"failure_reason"` + FailureBalanceTransaction *BalanceTransaction `json:"failure_balance_transaction"` + ID string `json:"id"` + Metadata map[string]string `json:"metadata"` + Object string `json:"object"` + PaymentIntent *PaymentIntent `json:"payment_intent"` + Reason RefundReason `json:"reason"` + ReceiptNumber string `json:"receipt_number"` + SourceTransferReversal *Reversal `json:"source_transfer_reversal"` + Status RefundStatus `json:"status"` + TransferReversal *Reversal `json:"transfer_reversal"` +} + +// RefundList is a list object for refunds. +type RefundList struct { + ListMeta + Data []*Refund `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Refund. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (r *Refund) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + r.ID = id + return nil + } + + type refund Refund + var v refund + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *r = Refund(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/reporting_reportrun.go b/vendor/github.com/stripe/stripe-go/reporting_reportrun.go new file mode 100644 index 0000000..d43c657 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/reporting_reportrun.go @@ -0,0 +1,69 @@ +package stripe + +// ReportRunStatus is the possible values for status on a report run. +type ReportRunStatus string + +// List of values that ReportRunStatus can take. +const ( + ReportRunStatusFailed ReportRunStatus = "failed" + ReportRunStatusPending ReportRunStatus = "pending" + ReportRunStatusSucceeded ReportRunStatus = "succeeded" +) + +// ReportRunParametersParams is the set of parameters that can be used when creating a report run. +type ReportRunParametersParams struct { + Columns []*string `form:"columns"` + ConnectedAccount *string `form:"connected_account"` + Currency *string `form:"currency"` + IntervalEnd *int64 `form:"interval_end"` + IntervalStart *int64 `form:"interval_start"` + Payout *string `form:"payout"` + ReportingCategory *string `form:"reporting_category"` + Timezone *string `form:"timezone"` +} + +// ReportRunParams is the set of parameters that can be used when creating a report run. +type ReportRunParams struct { + Params `form:"*"` + Parameters *ReportRunParametersParams `form:"parameters"` + ReportType *string `form:"report_type"` +} + +// ReportRunListParams is the set of parameters that can be used when listing report runs. +type ReportRunListParams struct { + ListParams `form:"*"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` +} + +// ReportRunParameters describes the parameters hash on a report run. +type ReportRunParameters struct { + Columns []string `json:"columns"` + ConnectedAccount string `json:"connected_account"` + Currency Currency `json:"currency"` + IntervalEnd int64 `json:"interval_end"` + IntervalStart int64 `json:"interval_start"` + Payout string `json:"payout"` + ReportingCategory string `json:"reporting_category"` + Timezone string `json:"timezone"` +} + +// ReportRun is the resource representing a report run. +type ReportRun struct { + Created int64 `json:"created"` + Error string `json:"error"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Object string `json:"object"` + Parameters *ReportRunParameters `json:"parameters"` + ReportType string `json:"report_type"` + Result *File `json:"result"` + Status ReportRunStatus `json:"status"` + SucceededAt int64 `json:"succeeded_at"` +} + +// ReportRunList is a list of report runs as retrieved from a list endpoint. +type ReportRunList struct { + ListMeta + Data []*ReportRun `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/reporting_reporttype.go b/vendor/github.com/stripe/stripe-go/reporting_reporttype.go new file mode 100644 index 0000000..19bf5a8 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/reporting_reporttype.go @@ -0,0 +1,30 @@ +package stripe + +// ReportTypeListParams is the set of parameters that can be used when listing report types. +type ReportTypeListParams struct { + ListParams `form:"*"` +} + +// ReportTypeParams is the set of parameters that can be used when retrieving a report type. +type ReportTypeParams struct { + Params `form:"*"` +} + +// ReportType is the resource representing a report type. +type ReportType struct { + DefaultColumns []string `json:"default_columns"` + Created int64 `json:"created"` + DataAvailableEnd int64 `json:"data_available_end"` + DataAvailableStart int64 `json:"data_available_start"` + ID string `json:"id"` + Name string `json:"name"` + Object string `json:"object"` + Updated int64 `json:"updated"` + Version int64 `json:"version"` +} + +// ReportTypeList is a list of report types as retrieved from a list endpoint. +type ReportTypeList struct { + ListMeta + Data []*ReportType `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/reversal.go b/vendor/github.com/stripe/stripe-go/reversal.go new file mode 100644 index 0000000..d017016 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/reversal.go @@ -0,0 +1,57 @@ +package stripe + +import "encoding/json" + +// ReversalParams is the set of parameters that can be used when reversing a transfer. +type ReversalParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + Description *string `form:"description"` + RefundApplicationFee *bool `form:"refund_application_fee"` + Transfer *string `form:"-"` // Included in URL +} + +// ReversalListParams is the set of parameters that can be used when listing reversals. +type ReversalListParams struct { + ListParams `form:"*"` + Transfer *string `form:"-"` // Included in URL +} + +// Reversal represents a transfer reversal. +type Reversal struct { + Amount int64 `json:"amount"` + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + Description string `json:"description"` + DestinationPaymentRefund *Refund `json:"destination_payment_refund"` + ID string `json:"id"` + Metadata map[string]string `json:"metadata"` + SourceRefund *Refund `json:"source_refund"` + Transfer string `json:"transfer"` +} + +// ReversalList is a list of object for reversals. +type ReversalList struct { + ListMeta + Data []*Reversal `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Reversal. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (r *Reversal) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + r.ID = id + return nil + } + + type reversal Reversal + var v reversal + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *r = Reversal(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/review.go b/vendor/github.com/stripe/stripe-go/review.go new file mode 100644 index 0000000..3ef33f2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/review.go @@ -0,0 +1,71 @@ +package stripe + +import "encoding/json" + +// ReviewReasonType describes the reason why the review is open or closed. +type ReviewReasonType string + +// List of values that ReviewReasonType can take. +const ( + ReviewReasonApproved ReviewReasonType = "approved" + ReviewReasonDisputed ReviewReasonType = "disputed" + ReviewReasonManual ReviewReasonType = "manual" + ReviewReasonRefunded ReviewReasonType = "refunded" + ReviewReasonRefundedAsFraud ReviewReasonType = "refunded_as_fraud" + ReviewReasonRule ReviewReasonType = "rule" +) + +// ReviewParams is the set of parameters that can be used when approving a review. +type ReviewParams struct { + Params `form:"*"` +} + +// ReviewApproveParams is the set of parameters that can be used when approving a review. +type ReviewApproveParams struct { + Params `form:"*"` +} + +// ReviewListParams is the set of parameters that can be used when listing reviews. +type ReviewListParams struct { + ListParams `form:"*"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` +} + +// Review is the resource representing a Radar review. +// For more details see https://stripe.com/docs/api#reviews. +type Review struct { + Charge *Charge `json:"charge"` + Created int64 `json:"created"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Object string `json:"object"` + Open bool `json:"open"` + PaymentIntent *PaymentIntent `json:"payment_intent"` + Reason ReviewReasonType `json:"reason"` +} + +// ReviewList is a list of reviews as retrieved from a list endpoint. +type ReviewList struct { + ListMeta + Data []*Review `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Review. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (r *Review) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + r.ID = id + return nil + } + + type review Review + var v review + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *r = Review(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/setupintent.go b/vendor/github.com/stripe/stripe-go/setupintent.go new file mode 100644 index 0000000..ce91669 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/setupintent.go @@ -0,0 +1,218 @@ +package stripe + +import ( + "encoding/json" +) + +// SetupIntentCancellationReason is the list of allowed values for the cancelation reason. +type SetupIntentCancellationReason string + +// List of values that SetupIntentCancellationReason can take. +const ( + SetupIntentCancellationReasonAbandoned SetupIntentCancellationReason = "abandoned" + SetupIntentCancellationReasonFailedInvoice SetupIntentCancellationReason = "failed_invoice" + SetupIntentCancellationReasonFraudulent SetupIntentCancellationReason = "fraudulent" + SetupIntentCancellationReasonRequestedByCustomer SetupIntentCancellationReason = "requested_by_customer" +) + +// SetupIntentNextActionType is the list of allowed values for the next action's type. +type SetupIntentNextActionType string + +// List of values that SetupIntentNextActionType can take. +const ( + SetupIntentNextActionTypeRedirectToURL SetupIntentNextActionType = "redirect_to_url" +) + +// SetupIntentPaymentMethodOptionsCardRequestThreeDSecure is the list of allowed values controlling +// when to request 3D Secure on a SetupIntent. +type SetupIntentPaymentMethodOptionsCardRequestThreeDSecure string + +// List of values that SetupIntentNextActionType can take. +const ( + SetupIntentPaymentMethodOptionsCardRequestThreeDSecureAny SetupIntentPaymentMethodOptionsCardRequestThreeDSecure = "any" + SetupIntentPaymentMethodOptionsCardRequestThreeDSecureAutomatic SetupIntentPaymentMethodOptionsCardRequestThreeDSecure = "automatic" +) + +// SetupIntentStatus is the list of allowed values for the setup intent's status. +type SetupIntentStatus string + +// List of values that SetupIntentStatus can take. +const ( + SetupIntentStatusCanceled SetupIntentStatus = "canceled" + SetupIntentStatusProcessing SetupIntentStatus = "processing" + SetupIntentStatusRequiresAction SetupIntentStatus = "requires_action" + SetupIntentStatusRequiresConfirmation SetupIntentStatus = "requires_confirmation" + SetupIntentStatusRequiresPaymentMethod SetupIntentStatus = "requires_payment_method" + SetupIntentStatusSucceeded SetupIntentStatus = "succeeded" +) + +// SetupIntentUsage is the list of allowed values for the setup intent's usage. +type SetupIntentUsage string + +// List of values that SetupIntentUsage can take. +const ( + SetupIntentUsageOffSession SetupIntentUsage = "off_session" + SetupIntentUsageOnSession SetupIntentUsage = "on_session" +) + +// SetupIntentCancelParams is the set of parameters that can be used when canceling a setup intent. +type SetupIntentCancelParams struct { + Params `form:"*"` + CancellationReason *string `form:"cancellation_reason"` +} + +// SetupIntentConfirmParams is the set of parameters that can be used when confirming a setup intent. +type SetupIntentConfirmParams struct { + Params `form:"*"` + MandateData *SetupIntentMandateDataParams `form:"mandate_data"` + PaymentMethod *string `form:"payment_method"` + PaymentMethodOptions *SetupIntentPaymentMethodOptionsParams `form:"payment_method_options"` + ReturnURL *string `form:"return_url"` +} + +// SetupIntentMandateDataCustomerAcceptanceOfflineParams is the set of parameters for the customer +// acceptance of an offline mandate. +type SetupIntentMandateDataCustomerAcceptanceOfflineParams struct { +} + +// SetupIntentMandateDataCustomerAcceptanceOnlineParams is the set of parameters for the customer +// acceptance of an online mandate. +type SetupIntentMandateDataCustomerAcceptanceOnlineParams struct { + IPAddress *string `form:"ip_address"` + UserAgent *string `form:"user_agent"` +} + +// SetupIntentMandateDataCustomerAcceptanceParams is the set of parameters for the customer +// acceptance of a mandate. +type SetupIntentMandateDataCustomerAcceptanceParams struct { + AcceptedAt int64 `form:"accepted_at"` + Offline *SetupIntentMandateDataCustomerAcceptanceOfflineParams `form:"offline"` + Online *SetupIntentMandateDataCustomerAcceptanceOnlineParams `form:"online"` + Type MandateCustomerAcceptanceType `form:"type"` +} + +// SetupIntentMandateDataParams is the set of parameters controlling the creation of the mandate +// associated with this SetupIntent. +type SetupIntentMandateDataParams struct { + CustomerAcceptance *SetupIntentMandateDataCustomerAcceptanceParams `form:"customer_acceptance"` +} + +// SetupIntentPaymentMethodOptionsCardParams represents the card-specific options applied to a +// SetupIntent. +type SetupIntentPaymentMethodOptionsCardParams struct { + MOTO *bool `form:"moto"` + RequestThreeDSecure *string `form:"request_three_d_secure"` +} + +// SetupIntentPaymentMethodOptionsParams represents the type-specific payment method options +// applied to a SetupIntent. +type SetupIntentPaymentMethodOptionsParams struct { + Card *SetupIntentPaymentMethodOptionsCardParams `form:"card"` +} + +// SetupIntentSingleUseParams represents the single-use mandate-specific parameters. +type SetupIntentSingleUseParams struct { + Amount *int64 `form:"amount"` + Currency *string `form:"currency"` +} + +// SetupIntentParams is the set of parameters that can be used when handling a setup intent. +type SetupIntentParams struct { + Params `form:"*"` + Confirm *bool `form:"confirm"` + Customer *string `form:"customer"` + Description *string `form:"description"` + MandateData *SetupIntentMandateDataParams `form:"mandate_data"` + OnBehalfOf *string `form:"on_behalf_of"` + PaymentMethod *string `form:"payment_method"` + PaymentMethodOptions *SetupIntentPaymentMethodOptionsParams `form:"payment_method_options"` + PaymentMethodTypes []*string `form:"payment_method_types"` + ReturnURL *string `form:"return_url"` + SingleUse *SetupIntentSingleUseParams `form:"single_use"` + Usage *string `form:"usage"` +} + +// SetupIntentListParams is the set of parameters that can be used when listing setup intents. +// For more details see https://stripe.com/docs/api#list_payouts. +type SetupIntentListParams struct { + ListParams `form:"*"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` + Customer *string `form:"customer"` + PaymentMethod *string `form:"payment_method"` +} + +// SetupIntentNextActionRedirectToURL represents the resource for the next action of type +// "redirect_to_url". +type SetupIntentNextActionRedirectToURL struct { + ReturnURL string `json:"return_url"` + URL string `json:"url"` +} + +// SetupIntentNextAction represents the type of action to take on a setup intent. +type SetupIntentNextAction struct { + RedirectToURL *SetupIntentNextActionRedirectToURL `json:"redirect_to_url"` + Type SetupIntentNextActionType `json:"type"` +} + +// SetupIntentPaymentMethodOptionsCard represents the card-specific options applied to a +// SetupIntent. +type SetupIntentPaymentMethodOptionsCard struct { + RequestThreeDSecure SetupIntentPaymentMethodOptionsCardRequestThreeDSecure `json:"request_three_d_secure"` +} + +// SetupIntentPaymentMethodOptions represents the type-specific payment method options applied to a +// SetupIntent. +type SetupIntentPaymentMethodOptions struct { + Card *SetupIntentPaymentMethodOptionsCard `json:"card"` +} + +// SetupIntent is the resource representing a Stripe payout. +// For more details see https://stripe.com/docs/api#payment_intents. +type SetupIntent struct { + Application *Application `json:"application"` + CancellationReason SetupIntentCancellationReason `json:"cancellation_reason"` + ClientSecret string `json:"client_secret"` + Created int64 `json:"created"` + Customer *Customer `json:"customer"` + Description string `json:"description"` + ID string `json:"id"` + LastSetupError *Error `json:"last_setup_error"` + Livemode bool `json:"livemode"` + Mandate *Mandate `json:"mandate"` + Metadata map[string]string `json:"metadata"` + NextAction *SetupIntentNextAction `json:"next_action"` + Object string `json:"object"` + OnBehalfOf *Account `json:"on_behalf_of"` + PaymentMethod *PaymentMethod `json:"payment_method"` + PaymentMethodOptions *SetupIntentPaymentMethodOptions `json:"payment_method_options"` + PaymentMethodTypes []string `json:"payment_method_types"` + SingleUseMandate *Mandate `json:"single_use_mandate"` + Status SetupIntentStatus `json:"status"` + Usage SetupIntentUsage `json:"usage"` +} + +// SetupIntentList is a list of setup intents as retrieved from a list endpoint. +type SetupIntentList struct { + ListMeta + Data []*SetupIntent `json:"data"` +} + +// UnmarshalJSON handles deserialization of a SetupIntent. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (p *SetupIntent) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + p.ID = id + return nil + } + + type setupIntent SetupIntent + var v setupIntent + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *p = SetupIntent(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/sigma_scheduledqueryrun.go b/vendor/github.com/stripe/stripe-go/sigma_scheduledqueryrun.go new file mode 100644 index 0000000..9f9690c --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/sigma_scheduledqueryrun.go @@ -0,0 +1,64 @@ +package stripe + +import "encoding/json" + +// SigmaScheduledQueryRunStatus is the possible values for status for a scheduled query run. +type SigmaScheduledQueryRunStatus string + +// List of values that SigmaScheduledQueryRunStatus can take. +const ( + SigmaScheduledQueryRunStatusCanceled SigmaScheduledQueryRunStatus = "canceled" + SigmaScheduledQueryRunStatusCompleted SigmaScheduledQueryRunStatus = "completed" + SigmaScheduledQueryRunStatusFailed SigmaScheduledQueryRunStatus = "failed" + SigmaScheduledQueryRunStatusTimedOut SigmaScheduledQueryRunStatus = "timed_out" +) + +// SigmaScheduledQueryRunParams is the set of parameters that can be used when updating a scheduled query run. +type SigmaScheduledQueryRunParams struct { + Params `form:"*"` +} + +// SigmaScheduledQueryRunListParams is the set of parameters that can be used when listing scheduled query runs. +type SigmaScheduledQueryRunListParams struct { + ListParams `form:"*"` +} + +// SigmaScheduledQueryRun is the resource representing a scheduled query run. +type SigmaScheduledQueryRun struct { + Created int64 `json:"created"` + DataLoadTime int64 `json:"data_load_time"` + Error string `json:"error"` + File *File `json:"file"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Object string `json:"object"` + ResultAvailableUntil int64 `json:"result_available_until"` + SQL string `json:"sql"` + Status SigmaScheduledQueryRunStatus `json:"status"` + Query string `json:"query"` +} + +// SigmaScheduledQueryRunList is a list of scheduled query runs as retrieved from a list endpoint. +type SigmaScheduledQueryRunList struct { + ListMeta + Data []*SigmaScheduledQueryRun `json:"data"` +} + +// UnmarshalJSON handles deserialization of an SigmaScheduledQueryRun. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (i *SigmaScheduledQueryRun) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + i.ID = id + return nil + } + + type sigmaScheduledQueryRun SigmaScheduledQueryRun + var v sigmaScheduledQueryRun + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *i = SigmaScheduledQueryRun(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/sku.go b/vendor/github.com/stripe/stripe-go/sku.go new file mode 100644 index 0000000..3d976d4 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/sku.go @@ -0,0 +1,106 @@ +package stripe + +import "encoding/json" + +// SKUInventoryType describe's the possible value for inventory type +type SKUInventoryType string + +// List of values that SKUInventoryType can take. +const ( + SKUInventoryTypeBucket SKUInventoryType = "bucket" + SKUInventoryTypeFinite SKUInventoryType = "finite" + SKUInventoryTypeInfinite SKUInventoryType = "infinite" +) + +// SKUInventoryValue describe's the possible value for inventory value +type SKUInventoryValue string + +// List of values that SKUInventoryValue can take. +const ( + SKUInventoryValueInStock SKUInventoryValue = "in_stock" + SKUInventoryValueLimited SKUInventoryValue = "limited" + SKUInventoryValueOutOfStock SKUInventoryValue = "out_of_stock" +) + +// InventoryParams is the set of parameters allowed as inventory on a SKU. +type InventoryParams struct { + Quantity *int64 `form:"quantity"` + Type *string `form:"type"` + Value *string `form:"value"` +} + +// SKUParams is the set of parameters allowed on SKU creation or update. +type SKUParams struct { + Params `form:"*"` + Active *bool `form:"active"` + Attributes map[string]string `form:"attributes"` + Currency *string `form:"currency"` + Description *string `form:"description"` + ID *string `form:"id"` + Image *string `form:"image"` + Inventory *InventoryParams `form:"inventory"` + PackageDimensions *PackageDimensionsParams `form:"package_dimensions"` + Price *int64 `form:"price"` + Product *string `form:"product"` +} + +// Inventory represents the inventory options of a SKU. +type Inventory struct { + Quantity int64 `json:"quantity"` + Type SKUInventoryType `json:"type"` + Value SKUInventoryValue `json:"value"` +} + +// SKU is the resource representing a SKU. +// For more details see https://stripe.com/docs/api#skus. +type SKU struct { + Active bool `json:"active"` + Attributes map[string]string `json:"attributes"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + Description string `json:"description"` + ID string `json:"id"` + Image string `json:"image"` + Inventory *Inventory `json:"inventory"` + Livemode bool `json:"livemode"` + Metadata map[string]string `json:"metadata"` + PackageDimensions *PackageDimensions `json:"package_dimensions"` + Price int64 `json:"price"` + Product *Product `json:"product"` + Updated int64 `json:"updated"` +} + +// SKUList is a list of SKUs as returned from a list endpoint. +type SKUList struct { + ListMeta + Data []*SKU `json:"data"` +} + +// SKUListParams is the set of parameters that can be used when listing SKUs. +type SKUListParams struct { + ListParams `form:"*"` + Active *bool `form:"active"` + Attributes map[string]string `form:"attributes"` + IDs []*string `form:"ids"` + InStock *bool `form:"in_stock"` + Product *string `form:"product"` +} + +// UnmarshalJSON handles deserialization of a SKU. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *SKU) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type sku SKU + var v sku + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = SKU(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/source.go b/vendor/github.com/stripe/stripe-go/source.go new file mode 100644 index 0000000..11f8ea1 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/source.go @@ -0,0 +1,352 @@ +package stripe + +import ( + "encoding/json" + + "github.com/stripe/stripe-go/form" +) + +// SourceCodeVerificationFlowStatus represents the possible statuses of a code verification flow. +type SourceCodeVerificationFlowStatus string + +// List of values that SourceCodeVerificationFlowStatus can take. +const ( + SourceCodeVerificationFlowStatusFailed SourceCodeVerificationFlowStatus = "failed" + SourceCodeVerificationFlowStatusPending SourceCodeVerificationFlowStatus = "pending" + SourceCodeVerificationFlowStatusSucceeded SourceCodeVerificationFlowStatus = "succeeded" +) + +// SourceFlow represents the possible flows of a source object. +type SourceFlow string + +// List of values that SourceFlow can take. +const ( + SourceFlowCodeVerification SourceFlow = "code_verification" + SourceFlowNone SourceFlow = "none" + SourceFlowReceiver SourceFlow = "receiver" + SourceFlowRedirect SourceFlow = "redirect" +) + +// SourceMandateAcceptanceStatus represents the possible failure reasons of a redirect flow. +type SourceMandateAcceptanceStatus string + +// List of values that SourceMandateAcceptanceStatus can take. +const ( + SourceMandateAcceptanceStatusAccepted SourceMandateAcceptanceStatus = "accepted" + SourceMandateAcceptanceStatusRefused SourceMandateAcceptanceStatus = "refused" +) + +// SourceMandateNotificationMethod represents the possible methods of notification for a mandate. +type SourceMandateNotificationMethod string + +// List of values that SourceMandateNotificationMethod can take. +const ( + SourceMandateNotificationMethodEmail SourceMandateNotificationMethod = "email" + SourceMandateNotificationMethodManual SourceMandateNotificationMethod = "manual" + SourceMandateNotificationMethodNone SourceMandateNotificationMethod = "none" +) + +// SourceSourceOrderItemType describes the type of source order items on source +// orders for sources. +type SourceSourceOrderItemType string + +// The list of possible values for source order item types. +const ( + SourceSourceOrderItemTypeDiscount SourceSourceOrderItemType = "discount" + SourceSourceOrderItemTypeSKU SourceSourceOrderItemType = "sku" + SourceSourceOrderItemTypeShipping SourceSourceOrderItemType = "shipping" + SourceSourceOrderItemTypeTax SourceSourceOrderItemType = "tax" +) + +// SourceRedirectFlowFailureReason represents the possible failure reasons of a redirect flow. +type SourceRedirectFlowFailureReason string + +// List of values that SourceRedirectFlowFailureReason can take. +const ( + SourceRedirectFlowFailureReasonDeclined SourceRedirectFlowFailureReason = "declined" + SourceRedirectFlowFailureReasonProcessingError SourceRedirectFlowFailureReason = "processing_error" + SourceRedirectFlowFailureReasonUserAbort SourceRedirectFlowFailureReason = "user_abort" +) + +// SourceRedirectFlowStatus represents the possible statuses of a redirect flow. +type SourceRedirectFlowStatus string + +// List of values that SourceRedirectFlowStatus can take. +const ( + SourceRedirectFlowStatusFailed SourceRedirectFlowStatus = "failed" + SourceRedirectFlowStatusNotRequired SourceRedirectFlowStatus = "not_required" + SourceRedirectFlowStatusPending SourceRedirectFlowStatus = "pending" + SourceRedirectFlowStatusSucceeded SourceRedirectFlowStatus = "succeeded" +) + +// SourceRefundAttributesMethod are the possible method to retrieve a receiver's refund attributes. +type SourceRefundAttributesMethod string + +// List of values that SourceRefundAttributesMethod can take. +const ( + SourceRefundAttributesMethodEmail SourceRefundAttributesMethod = "email" + SourceRefundAttributesMethodManual SourceRefundAttributesMethod = "manual" +) + +// SourceRefundAttributesStatus are the possible status of a receiver's refund attributes. +type SourceRefundAttributesStatus string + +// List of values that SourceRefundAttributesStatus can take. +const ( + SourceRefundAttributesStatusAvailable SourceRefundAttributesStatus = "available" + SourceRefundAttributesStatusMissing SourceRefundAttributesStatus = "missing" + SourceRefundAttributesStatusRequested SourceRefundAttributesStatus = "requested" +) + +// SourceStatus represents the possible statuses of a source object. +type SourceStatus string + +// List of values that SourceStatus can take. +const ( + SourceStatusCanceled SourceStatus = "canceled" + SourceStatusChargeable SourceStatus = "chargeable" + SourceStatusConsumed SourceStatus = "consumed" + SourceStatusFailed SourceStatus = "failed" + SourceStatusPending SourceStatus = "pending" +) + +// SourceUsage represents the possible usages of a source object. +type SourceUsage string + +// List of values that SourceUsage can take. +const ( + SourceUsageReusable SourceUsage = "reusable" + SourceUsageSingleUse SourceUsage = "single_use" +) + +// SourceOwnerParams is the set of parameters allowed for the owner hash on +// source creation or update. +type SourceOwnerParams struct { + Address *AddressParams `form:"address"` + Email *string `form:"email"` + Name *string `form:"name"` + Phone *string `form:"phone"` +} + +// RedirectParams is the set of parameters allowed for the redirect hash on +// source creation or update. +type RedirectParams struct { + ReturnURL *string `form:"return_url"` +} + +// SourceOrderItemsParams is the set of parameters allowed for the items on a +// source order for a source. +type SourceOrderItemsParams 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"` +} + +// SourceOrderParams is the set of parameters allowed for the source order of a +// source. +type SourceOrderParams struct { + Items []*SourceOrderItemsParams `form:"items"` + Shipping *ShippingDetailsParams `form:"shipping"` +} + +// SourceObjectParams is the set of parameters allowed on source creation or update. +type SourceObjectParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + Currency *string `form:"currency"` + Customer *string `form:"customer"` + Flow *string `form:"flow"` + Mandate *SourceMandateParams `form:"mandate"` + OriginalSource *string `form:"original_source"` + Owner *SourceOwnerParams `form:"owner"` + Receiver *SourceReceiverParams `form:"receiver"` + Redirect *RedirectParams `form:"redirect"` + SourceOrder *SourceOrderParams `form:"source_order"` + StatementDescriptor *string `form:"statement_descriptor"` + Token *string `form:"token"` + Type *string `form:"type"` + TypeData map[string]string `form:"-"` + Usage *string `form:"usage"` +} + +// SourceMandateAcceptanceParams describes the set of parameters allowed for the `acceptance` +// hash on source creation or update. +type SourceMandateAcceptanceParams struct { + Date *int64 `form:"date"` + IP *string `form:"ip"` + Offline *SourceMandateAcceptanceOfflineParams `form:"offline"` + Online *SourceMandateAcceptanceOnlineParams `form:"online"` + Status *string `form:"status"` + Type *string `form:"type"` + UserAgent *string `form:"user_agent"` +} + +// SourceMandateAcceptanceOnlineParams describes the set of parameters for online accepted mandate +type SourceMandateAcceptanceOnlineParams struct { + Date *int64 `form:"date"` + IP *string `form:"ip"` + UserAgent *string `form:"user_agent"` +} + +// SourceMandateAcceptanceOfflineParams describes the set of parameters for offline accepted mandate +type SourceMandateAcceptanceOfflineParams struct { + ContactEmail *string `form:"contact_email"` +} + +// SourceMandateParams describes the set of parameters allowed for the `mandate` hash on +// source creation or update. +type SourceMandateParams struct { + Amount *int64 `form:"amount"` + Acceptance *SourceMandateAcceptanceParams `form:"acceptance"` + Currency *string `form:"currency"` + Interval *string `form:"interval"` + NotificationMethod *string `form:"notification_method"` +} + +// SourceReceiverParams is the set of parameters allowed for the `receiver` hash on +// source creation or update. +type SourceReceiverParams struct { + RefundAttributesMethod *string `form:"refund_attributes_method"` +} + +// SourceObjectDetachParams is the set of parameters that can be used when detaching +// a source from a customer. +type SourceObjectDetachParams struct { + Params `form:"*"` + Customer *string `form:"-"` +} + +// SourceOwner describes the owner hash on a source. +type SourceOwner struct { + Address *Address `json:"address,omitempty"` + Email string `json:"email"` + Name string `json:"name"` + Phone string `json:"phone"` + VerifiedAddress *Address `json:"verified_address,omitempty"` + VerifiedEmail string `json:"verified_email"` + VerifiedName string `json:"verified_name"` + VerifiedPhone string `json:"verified_phone"` +} + +// RedirectFlow informs of the state of a redirect authentication flow. +type RedirectFlow struct { + FailureReason SourceRedirectFlowFailureReason `json:"failure_reason"` + ReturnURL string `json:"return_url"` + Status SourceRedirectFlowStatus `json:"status"` + URL string `json:"url"` +} + +// ReceiverFlow informs of the state of a receiver authentication flow. +type ReceiverFlow struct { + Address string `json:"address"` + AmountCharged int64 `json:"amount_charged"` + AmountReceived int64 `json:"amount_received"` + AmountReturned int64 `json:"amount_returned"` + RefundAttributesMethod SourceRefundAttributesMethod `json:"refund_attributes_method"` + RefundAttributesStatus SourceRefundAttributesStatus `json:"refund_attributes_status"` +} + +// CodeVerificationFlow informs of the state of a verification authentication flow. +type CodeVerificationFlow struct { + AttemptsRemaining int64 `json:"attempts_remaining"` + Status SourceCodeVerificationFlowStatus `json:"status"` +} + +// SourceMandateAcceptance describes a source mandate acceptance state. +type SourceMandateAcceptance struct { + Date int64 `json:"date"` + IP string `json:"ip"` + Status SourceMandateAcceptanceStatus `json:"status"` + UserAgent string `json:"user_agent"` +} + +// SourceMandate describes a source mandate. +type SourceMandate struct { + Acceptance *SourceMandateAcceptance `json:"acceptance"` + NotificationMethod SourceMandateNotificationMethod `json:"notification_method"` + Reference string `json:"reference"` + URL string `json:"url"` +} + +// SourceSourceOrderItems describes the items on source orders for sources. +type SourceSourceOrderItems struct { + Amount int64 `json:"amount"` + Currency Currency `json:"currency"` + Description string `json:"description"` + Quantity int64 `json:"quantity"` + Type SourceSourceOrderItemType `json:"type"` +} + +// SourceSourceOrder describes a source order for a source. +type SourceSourceOrder struct { + Amount int64 `json:"amount"` + Currency Currency `json:"currency"` + Email string `json:"email"` + Items *[]SourceSourceOrderItems `json:"items"` + Shipping *ShippingDetails `json:"shipping"` +} + +// Source is the resource representing a Source. +// For more details see https://stripe.com/docs/api#sources. +type Source struct { + Amount int64 `json:"amount"` + ClientSecret string `json:"client_secret"` + CodeVerification *CodeVerificationFlow `json:"code_verification,omitempty"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + Customer string `json:"customer"` + Flow SourceFlow `json:"flow"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Mandate *SourceMandate `json:"mandate"` + Metadata map[string]string `json:"metadata"` + Owner *SourceOwner `json:"owner"` + Receiver *ReceiverFlow `json:"receiver,omitempty"` + Redirect *RedirectFlow `json:"redirect,omitempty"` + StatementDescriptor string `json:"statement_descriptor"` + SourceOrder *SourceSourceOrder `json:"source_order"` + Status SourceStatus `json:"status"` + Type string `json:"type"` + TypeData map[string]interface{} + Usage SourceUsage `json:"usage"` +} + +// AppendTo implements custom encoding logic for SourceObjectParams so that the special +// "TypeData" value for is sent as the correct parameter based on the Source type +func (p *SourceObjectParams) AppendTo(body *form.Values, keyParts []string) { + if len(p.TypeData) > 0 && p.Type == nil { + panic("You can not fill TypeData if you don't explicitly set Type") + } + + for k, vs := range p.TypeData { + body.Add(form.FormatKey(append(keyParts, StringValue(p.Type), k)), vs) + } +} + +// UnmarshalJSON handles deserialization of an Source. This custom unmarshaling +// is needed to extract the type specific data (accessible under `TypeData`) +// but stored in JSON under a hash named after the `type` of the source. +func (s *Source) UnmarshalJSON(data []byte) error { + type source Source + var v source + if err := json.Unmarshal(data, &v); err != nil { + return err + } + *s = Source(v) + + var raw map[string]interface{} + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + if d, ok := raw[s.Type]; ok { + if m, ok := d.(map[string]interface{}); ok { + s.TypeData = m + } + } + + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/sourcetransaction.go b/vendor/github.com/stripe/stripe-go/sourcetransaction.go new file mode 100644 index 0000000..ea87590 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/sourcetransaction.go @@ -0,0 +1,55 @@ +package stripe + +import "encoding/json" + +// SourceTransactionListParams is the set of parameters that can be used when listing SourceTransactions. +type SourceTransactionListParams struct { + ListParams `form:"*"` + Source *string `form:"-"` // Sent in with the URL +} + +// SourceTransactionList is a list object for SourceTransactions. +type SourceTransactionList struct { + ListMeta + Data []*SourceTransaction `json:"data"` +} + +// SourceTransaction is the resource representing a Stripe source transaction. +type SourceTransaction struct { + Amount int64 `json:"amount"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + CustomerData string `json:"customer_data"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Source string `json:"source"` + Type string `json:"type"` + TypeData map[string]interface{} +} + +// UnmarshalJSON handles deserialization of a SourceTransaction. This custom +// unmarshaling is needed to extract the type specific data (accessible under +// `TypeData`) but stored in JSON under a hash named after the `type` of the +// source transaction. +func (t *SourceTransaction) UnmarshalJSON(data []byte) error { + type sourceTransaction SourceTransaction + var v sourceTransaction + err := json.Unmarshal(data, &v) + if err != nil { + return err + } + *t = SourceTransaction(v) + + var raw map[string]interface{} + err = json.Unmarshal(data, &raw) + if err != nil { + return err + } + if d, ok := raw[t.Type]; ok { + if m, ok := d.(map[string]interface{}); ok { + t.TypeData = m + } + } + + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/stripe.go b/vendor/github.com/stripe/stripe-go/stripe.go new file mode 100644 index 0000000..9f1feee --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/stripe.go @@ -0,0 +1,1139 @@ +// Package stripe provides the binding for Stripe REST APIs. +package stripe + +import ( + "bytes" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "math/rand" + "net/http" + "net/url" + "os/exec" + "reflect" + "runtime" + "strings" + "sync" + "time" + + "github.com/stripe/stripe-go/form" +) + +// +// Public constants +// + +const ( + // APIVersion is the currently supported API version + APIVersion string = "2020-03-02" + + // APIBackend is a constant representing the API service backend. + APIBackend SupportedBackend = "api" + + // APIURL is the URL of the API service backend. + APIURL string = "https://api.stripe.com" + + // ConnectURL is the URL for OAuth. + ConnectURL string = "https://connect.stripe.com" + + // ConnectBackend is a constant representing the connect service backend for + // OAuth. + ConnectBackend SupportedBackend = "connect" + + // UnknownPlatform is the string returned as the system name if we couldn't get + // one from `uname`. + UnknownPlatform string = "unknown platform" + + // UploadsBackend is a constant representing the uploads service backend. + UploadsBackend SupportedBackend = "uploads" + + // UploadsURL is the URL of the uploads service backend. + UploadsURL string = "https://files.stripe.com" +) + +// +// Public variables +// + +// EnableTelemetry is a global override for enabling client telemetry, which +// sends request performance metrics to Stripe via the `X-Stripe-Client-Telemetry` +// header. If set to true, all clients will send telemetry metrics. Defaults to +// true. +// +// Telemetry can also be disabled on a per-client basis by instead creating a +// `BackendConfig` with `EnableTelemetry: false`. +var EnableTelemetry = true + +// Key is the Stripe API key used globally in the binding. +var Key string + +// +// Public types +// + +// AppInfo contains information about the "app" which this integration belongs +// to. This should be reserved for plugins that wish to identify themselves +// with Stripe. +type AppInfo struct { + Name string `json:"name"` + PartnerID string `json:"partner_id"` + URL string `json:"url"` + Version string `json:"version"` +} + +// formatUserAgent formats an AppInfo in a way that's suitable to be appended +// to a User-Agent string. Note that this format is shared between all +// libraries so if it's changed, it should be changed everywhere. +func (a *AppInfo) formatUserAgent() string { + str := a.Name + if a.Version != "" { + str += "/" + a.Version + } + if a.URL != "" { + str += " (" + a.URL + ")" + } + return str +} + +// Backend is an interface for making calls against a Stripe service. +// This interface exists to enable mocking for during testing if needed. +type Backend interface { + Call(method, path, key string, params ParamsContainer, v interface{}) error + CallRaw(method, path, key string, body *form.Values, params *Params, v interface{}) error + CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v interface{}) error + SetMaxNetworkRetries(maxNetworkRetries int) +} + +// BackendConfig is used to configure a new Stripe backend. +type BackendConfig struct { + // EnableTelemetry allows request metrics (request id and duration) to be sent + // to Stripe in subsequent requests via the `X-Stripe-Client-Telemetry` header. + // + // Defaults to false. + EnableTelemetry bool + + // HTTPClient is an HTTP client instance to use when making API requests. + // + // If left unset, it'll be set to a default HTTP client for the package. + HTTPClient *http.Client + + // LeveledLogger is the logger that the backend 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. + LeveledLogger LeveledLoggerInterface + + // LogLevel is the logging level of the library and defined by: + // + // 0: no logging + // 1: errors only + // 2: errors + informational (default) + // 3: errors + informational + debug + // + // Defaults to 0 (no logging), so please make sure to set this if you want + // to see logging output in your custom configuration. + // + // Deprecated: Logging should be configured with LeveledLogger instead. + LogLevel int + + // Logger is where this backend will write its logs. + // + // If left unset, it'll be set to Logger. + // + // Deprecated: Logging should be configured with LeveledLogger instead. + Logger Printfer + + // MaxNetworkRetries sets maximum number of times that the library will + // retry requests that appear to have failed due to an intermittent + // problem. + // + // Defaults to 0. + MaxNetworkRetries int + + // URL is the base URL to use for API paths. + // + // If left empty, it'll be set to the default for the SupportedBackend. + URL string +} + +// BackendImplementation is the internal implementation for making HTTP calls +// to Stripe. +// +// The public use of this struct is deprecated. It will be unexported in a +// future version. +type BackendImplementation struct { + Type SupportedBackend + URL string + HTTPClient *http.Client + LeveledLogger LeveledLoggerInterface + MaxNetworkRetries int + + enableTelemetry bool + + // networkRetriesSleep indicates whether the backend should use the normal + // sleep between retries. + // + // See also SetNetworkRetriesSleep. + networkRetriesSleep bool + + requestMetricsBuffer chan requestMetrics +} + +// Call is the Backend.Call implementation for invoking Stripe APIs. +func (s *BackendImplementation) Call(method, path, key string, params ParamsContainer, v interface{}) error { + var body *form.Values + var commonParams *Params + + if params != nil { + // This is a little unfortunate, but Go makes it impossible to compare + // an interface value to nil without the use of the reflect package and + // its true disciples insist that this is a feature and not a bug. + // + // Here we do invoke reflect because (1) we have to reflect anyway to + // use encode with the form package, and (2) the corresponding removal + // of boilerplate that this enables makes the small performance penalty + // worth it. + reflectValue := reflect.ValueOf(params) + + if reflectValue.Kind() == reflect.Ptr && !reflectValue.IsNil() { + commonParams = params.GetParams() + body = &form.Values{} + form.AppendTo(body, params) + } + } + + return s.CallRaw(method, path, key, body, commonParams, v) +} + +// CallMultipart is the Backend.CallMultipart implementation for invoking Stripe APIs. +func (s *BackendImplementation) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *Params, v interface{}) error { + contentType := "multipart/form-data; boundary=" + boundary + + req, err := s.NewRequest(method, path, key, contentType, params) + if err != nil { + return err + } + + if err := s.Do(req, body, v); err != nil { + return err + } + + return nil +} + +// CallRaw is the implementation for invoking Stripe APIs internally without a backend. +func (s *BackendImplementation) CallRaw(method, path, key string, form *form.Values, params *Params, v interface{}) error { + var body string + if form != nil && !form.Empty() { + body = form.Encode() + + // On `GET`, move the payload into the URL + if method == http.MethodGet { + path += "?" + body + body = "" + } + } + bodyBuffer := bytes.NewBufferString(body) + + req, err := s.NewRequest(method, path, key, "application/x-www-form-urlencoded", params) + if err != nil { + return err + } + + if err := s.Do(req, bodyBuffer, v); err != nil { + return err + } + + return nil +} + +// NewRequest is used by Call to generate an http.Request. It handles encoding +// parameters and attaching the appropriate headers. +func (s *BackendImplementation) NewRequest(method, path, key, contentType string, params *Params) (*http.Request, error) { + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + + path = s.URL + path + + // Body is set later by `Do`. + req, err := http.NewRequest(method, path, nil) + if err != nil { + s.LeveledLogger.Errorf("Cannot create Stripe request: %v", err) + return nil, err + } + + authorization := "Bearer " + key + + req.Header.Add("Authorization", authorization) + req.Header.Add("Content-Type", contentType) + req.Header.Add("Stripe-Version", APIVersion) + req.Header.Add("User-Agent", encodedUserAgent) + req.Header.Add("X-Stripe-Client-User-Agent", encodedStripeUserAgent) + + if params != nil { + if params.Context != nil { + req = req.WithContext(params.Context) + } + + if params.IdempotencyKey != nil { + idempotencyKey := strings.TrimSpace(*params.IdempotencyKey) + if len(idempotencyKey) > 255 { + return nil, errors.New("cannot use an idempotency key longer than 255 characters") + } + + req.Header.Add("Idempotency-Key", idempotencyKey) + } else if isHTTPWriteMethod(method) { + req.Header.Add("Idempotency-Key", NewIdempotencyKey()) + } + + if params.StripeAccount != nil { + req.Header.Add("Stripe-Account", strings.TrimSpace(*params.StripeAccount)) + } + + for k, v := range params.Headers { + for _, line := range v { + // Use Set to override the default value possibly set before + req.Header.Set(k, line) + } + } + } + + return req, nil +} + +// Do is used by Call to execute an API request and parse the response. It uses +// the backend's HTTP client to execute the request and unmarshals the response +// into v. It also handles unmarshaling errors returned by the API. +func (s *BackendImplementation) Do(req *http.Request, body *bytes.Buffer, v interface{}) error { + s.LeveledLogger.Infof("Requesting %v %v%v\n", req.Method, req.URL.Host, req.URL.Path) + + if s.enableTelemetry { + select { + case metrics := <-s.requestMetricsBuffer: + metricsJSON, err := json.Marshal(&requestTelemetry{LastRequestMetrics: metrics}) + if err == nil { + req.Header.Set("X-Stripe-Client-Telemetry", string(metricsJSON)) + } else { + s.LeveledLogger.Warnf("Unable to encode client telemetry: %v", err) + } + default: + // There are no metrics available, so don't send any. + // This default case needs to be here to prevent Do from blocking on an + // empty requestMetricsBuffer. + } + } + + var res *http.Response + var err error + var requestDuration time.Duration + var resBody []byte + for retry := 0; ; { + start := time.Now() + + // This might look a little strange, but we set the request's body + // outside of `NewRequest` so that we can get a fresh version every + // time. + // + // The background is that back in the era of old style HTTP, it was + // safe to reuse `Request` objects, but with the addition of HTTP/2, + // it's now only sometimes safe. Reusing a `Request` with a body will + // break. + // + // See some details here: + // + // https://github.com/golang/go/issues/19653#issuecomment-341539160 + // + // And our original bug report here: + // + // https://github.com/stripe/stripe-go/issues/642 + // + // To workaround the problem, we put a fresh `Body` onto the `Request` + // every time we execute it, and this seems to empirically resolve the + // problem. + if body != nil { + // We can safely reuse the same buffer that we used to encode our body, + // but return a new reader to it everytime so that each read is from + // the beginning. + reader := bytes.NewReader(body.Bytes()) + + req.Body = nopReadCloser{reader} + + // And also add the same thing to `Request.GetBody`, which allows + // `net/http` to get a new body in cases like a redirect. This is + // usually not used, but it doesn't hurt to set it in case it's + // needed. See: + // + // https://github.com/stripe/stripe-go/issues/710 + // + req.GetBody = func() (io.ReadCloser, error) { + reader := bytes.NewReader(body.Bytes()) + return nopReadCloser{reader}, nil + } + } + + res, err = s.HTTPClient.Do(req) + + requestDuration = time.Since(start) + s.LeveledLogger.Infof("Request completed in %v (retry: %v)", requestDuration, retry) + + if err == nil { + resBody, err = ioutil.ReadAll(res.Body) + res.Body.Close() + } + + if err != nil { + s.LeveledLogger.Errorf("Request failed with error: %v", err) + } else if res.StatusCode >= 400 { + err = s.ResponseToError(res, resBody) + + if stripeErr, ok := err.(*Error); ok { + // The Stripe API makes a distinction between errors that were + // caused by invalid parameters or something else versus those + // that occurred *despite* valid parameters, the latter coming + // back with status 402. + // + // On a 402, log to info so as to not make an integration's log + // noisy with error messages that they don't have much control + // over. + // + // Note I use the constant 402 instead of an `http.Status*` + // constant because technically 402 is "Payment required". The + // Stripe API doesn't comply to the letter of the specification + // and uses it in a broader sense. + if res.StatusCode == 402 { + s.LeveledLogger.Infof("User-compelled request error from Stripe (status %v): %v", + res.StatusCode, stripeErr) + } else { + s.LeveledLogger.Errorf("Request error from Stripe (status %v): %v", + res.StatusCode, stripeErr) + } + } else { + s.LeveledLogger.Errorf("Error decoding error from Stripe: %v", err) + } + } + + // If the response was okay, or an error that shouldn't be retried, + // we're done, and it's safe to leave the retry loop. + if !s.shouldRetry(err, req, res, retry) { + break + } + + sleepDuration := s.sleepTime(retry) + retry++ + + s.LeveledLogger.Warnf("Initiating retry %v for request %v %v%v after sleeping %v", + retry, req.Method, req.URL.Host, req.URL.Path, sleepDuration) + + time.Sleep(sleepDuration) + } + + if s.enableTelemetry && res != nil { + reqID := res.Header.Get("Request-Id") + if len(reqID) > 0 { + metrics := requestMetrics{ + RequestDurationMS: int(requestDuration / time.Millisecond), + RequestID: reqID, + } + + // If the metrics buffer is full, discard the new metrics. Otherwise, add + // them to the buffer. + select { + case s.requestMetricsBuffer <- metrics: + default: + } + } + } + + if err != nil { + return err + } + + s.LeveledLogger.Debugf("Response: %s\n", string(resBody)) + + if v != nil { + return s.UnmarshalJSONVerbose(res.StatusCode, resBody, v) + } + + return nil +} + +// ResponseToError converts a stripe response to an Error. +func (s *BackendImplementation) ResponseToError(res *http.Response, resBody []byte) error { + var raw rawError + if s.Type == ConnectBackend { + // If this is an OAuth request, deserialize as Error because OAuth errors + // are a different shape from the standard API errors. + var topLevelError rawErrorInternal + if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &topLevelError); err != nil { + return err + } + raw.E = &topLevelError + } else { + if err := s.UnmarshalJSONVerbose(res.StatusCode, resBody, &raw); err != nil { + return err + } + } + + // no error in resBody + if raw.E == nil { + err := errors.New(string(resBody)) + return err + } + raw.E.HTTPStatusCode = res.StatusCode + raw.E.RequestID = res.Header.Get("Request-Id") + + var typedError error + switch raw.E.Type { + case ErrorTypeAPI: + typedError = &APIError{stripeErr: raw.E.Error} + case ErrorTypeAPIConnection: + typedError = &APIConnectionError{stripeErr: raw.E.Error} + case ErrorTypeAuthentication: + typedError = &AuthenticationError{stripeErr: raw.E.Error} + case ErrorTypeCard: + cardErr := &CardError{stripeErr: raw.E.Error} + if raw.E.DeclineCode != nil { + cardErr.DeclineCode = *raw.E.DeclineCode + } + typedError = cardErr + case ErrorTypeInvalidRequest: + typedError = &InvalidRequestError{stripeErr: raw.E.Error} + case ErrorTypePermission: + typedError = &PermissionError{stripeErr: raw.E.Error} + case ErrorTypeRateLimit: + typedError = &RateLimitError{stripeErr: raw.E.Error} + } + raw.E.Err = typedError + + return raw.E.Error +} + +// SetMaxNetworkRetries sets max number of retries on failed requests +// +// This function is deprecated. Please use GetBackendWithConfig instead. +func (s *BackendImplementation) SetMaxNetworkRetries(maxNetworkRetries int) { + s.MaxNetworkRetries = maxNetworkRetries +} + +// SetNetworkRetriesSleep allows the normal sleep between network retries to be +// enabled or disabled. +// +// This function is available for internal testing only and should never be +// used in production. +func (s *BackendImplementation) SetNetworkRetriesSleep(sleep bool) { + s.networkRetriesSleep = sleep +} + +// UnmarshalJSONVerbose unmarshals JSON, but in case of a failure logs and +// produces a more descriptive error. +func (s *BackendImplementation) UnmarshalJSONVerbose(statusCode int, body []byte, v interface{}) error { + err := json.Unmarshal(body, v) + if err != nil { + // If we got invalid JSON back then something totally unexpected is + // happening (caused by a bug on the server side). Put a sample of the + // response body into the error message so we can get a better feel for + // what the problem was. + bodySample := string(body) + if len(bodySample) > 500 { + bodySample = bodySample[0:500] + " ..." + } + + // Make sure a multi-line response ends up all on one line + bodySample = strings.Replace(bodySample, "\n", "\\n", -1) + + newErr := fmt.Errorf("Couldn't deserialize JSON (response status: %v, body sample: '%s'): %v", + statusCode, bodySample, err) + s.LeveledLogger.Errorf("%s", newErr.Error()) + return newErr + } + + return nil +} + +// Checks if an error is a problem that we should retry on. This includes both +// socket errors that may represent an intermittent problem and some special +// HTTP statuses. +func (s *BackendImplementation) shouldRetry(err error, req *http.Request, resp *http.Response, numRetries int) bool { + if numRetries >= s.MaxNetworkRetries { + return false + } + + stripeErr, _ := err.(*Error) + + // TODO: This retries any non-Stripe errors produced as part of the + // communication process. It generally works, but there are many errors + // that should *not* be retried. Try to make this more granular by + // including only connection errors, timeout errors, etc. + if stripeErr == nil && err != nil { + return true + } + + // The API may ask us not to retry (e.g. if doing so would be a no-op), or + // advise us to retry (e.g. in cases of lock timeouts). Defer to those + // instructions if given. + if resp.Header.Get("Stripe-Should-Retry") == "false" { + return false + } + if resp.Header.Get("Stripe-Should-Retry") == "true" { + return true + } + + // 409 Conflict + if resp.StatusCode == http.StatusConflict { + return true + } + + // 429 Too Many Requests + // + // There are a few different problems that can lead to a 429. The most + // common is rate limiting, on which we *don't* want to retry because + // that'd likely contribute to more contention problems. However, some 429s + // are lock timeouts, which is when a request conflicted with another + // request or an internal process on some particular object. These 429s are + // safe to retry. + if resp.StatusCode == http.StatusTooManyRequests { + if stripeErr != nil && stripeErr.Code == ErrorCodeLockTimeout { + return true + } + } + + // 500 Internal Server Error + // + // We only bother retrying these for non-POST requests. POSTs end up being + // cached by the idempotency layer so there's no purpose in retrying them. + if resp.StatusCode >= http.StatusInternalServerError && req.Method != http.MethodPost { + return true + } + + // 503 Service Unavailable + if resp.StatusCode == http.StatusServiceUnavailable { + return true + } + + return false +} + +// sleepTime calculates sleeping/delay time in milliseconds between failure and a new one request. +func (s *BackendImplementation) sleepTime(numRetries int) time.Duration { + // We disable sleeping in some cases for tests. + if !s.networkRetriesSleep { + return 0 * time.Second + } + + // Apply exponential backoff with minNetworkRetriesDelay on the + // number of num_retries so far as inputs. + delay := minNetworkRetriesDelay + minNetworkRetriesDelay*time.Duration(numRetries*numRetries) + + // Do not allow the number to exceed maxNetworkRetriesDelay. + if delay > maxNetworkRetriesDelay { + delay = maxNetworkRetriesDelay + } + + // Apply some jitter by randomizing the value in the range of 75%-100%. + jitter := rand.Int63n(int64(delay / 4)) + delay -= time.Duration(jitter) + + // But never sleep less than the base sleep seconds. + if delay < minNetworkRetriesDelay { + delay = minNetworkRetriesDelay + } + + return delay +} + +// Backends are the currently supported endpoints. +type Backends struct { + API, Connect, Uploads Backend + mu sync.RWMutex +} + +// SupportedBackend is an enumeration of supported Stripe endpoints. +// Currently supported values are "api" and "uploads". +type SupportedBackend string + +// +// Public functions +// + +// Bool returns a pointer to the bool value passed in. +func Bool(v bool) *bool { + return &v +} + +// BoolValue returns the value of the bool pointer passed in or +// false if the pointer is nil. +func BoolValue(v *bool) bool { + if v != nil { + return *v + } + return false +} + +// BoolSlice returns a slice of bool pointers given a slice of bools. +func BoolSlice(v []bool) []*bool { + out := make([]*bool, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// Float64 returns a pointer to the float64 value passed in. +func Float64(v float64) *float64 { + return &v +} + +// Float64Value returns the value of the float64 pointer passed in or +// 0 if the pointer is nil. +func Float64Value(v *float64) float64 { + if v != nil { + return *v + } + return 0 +} + +// Float64Slice returns a slice of float64 pointers given a slice of float64s. +func Float64Slice(v []float64) []*float64 { + out := make([]*float64, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// FormatURLPath takes a format string (of the kind used in the fmt package) +// representing a URL path with a number of parameters that belong in the path +// and returns a formatted string. +// +// This is mostly a pass through to Sprintf. It exists to make it +// it impossible to accidentally provide a parameter type that would be +// formatted improperly; for example, a string pointer instead of a string. +// +// It also URL-escapes every given parameter. This usually isn't necessary for +// a standard Stripe ID, but is needed in places where user-provided IDs are +// allowed, like in coupons or plans. We apply it broadly for extra safety. +func FormatURLPath(format string, params ...string) string { + // Convert parameters to interface{} and URL-escape them + untypedParams := make([]interface{}, len(params)) + for i, param := range params { + untypedParams[i] = interface{}(url.QueryEscape(param)) + } + + return fmt.Sprintf(format, untypedParams...) +} + +// GetBackend returns one of the library's supported backends based off of the +// given argument. +// +// It returns an existing default backend if one's already been created. +func GetBackend(backendType SupportedBackend) Backend { + var backend Backend + + backends.mu.RLock() + switch backendType { + case APIBackend: + backend = backends.API + case ConnectBackend: + backend = backends.Connect + case UploadsBackend: + backend = backends.Uploads + } + backends.mu.RUnlock() + if backend != nil { + return backend + } + + backend = GetBackendWithConfig( + backendType, + &BackendConfig{ + HTTPClient: httpClient, + LeveledLogger: DefaultLeveledLogger, + LogLevel: LogLevel, + Logger: Logger, + MaxNetworkRetries: 0, + URL: "", // Set by GetBackendWithConfiguation when empty + }, + ) + + SetBackend(backendType, backend) + + return backend +} + +// GetBackendWithConfig is the same as GetBackend except that it can be given a +// configuration struct that will configure certain aspects of the backend +// that's return. +func GetBackendWithConfig(backendType SupportedBackend, config *BackendConfig) Backend { + if config.HTTPClient == nil { + config.HTTPClient = httpClient + } + + if config.LeveledLogger == nil { + if config.Logger == nil { + config.Logger = Logger + } + + config.LeveledLogger = &leveledLoggerPrintferShim{ + level: printferLevel(config.LogLevel), + logger: config.Logger, + } + } + + switch backendType { + case APIBackend: + if config.URL == "" { + config.URL = apiURL + } + + config.URL = normalizeURL(config.URL) + + return newBackendImplementation(backendType, config) + + case UploadsBackend: + if config.URL == "" { + config.URL = uploadsURL + } + + config.URL = normalizeURL(config.URL) + + return newBackendImplementation(backendType, config) + + case ConnectBackend: + if config.URL == "" { + config.URL = ConnectURL + } + + config.URL = normalizeURL(config.URL) + + return newBackendImplementation(backendType, config) + } + + return nil +} + +// Int64 returns a pointer to the int64 value passed in. +func Int64(v int64) *int64 { + return &v +} + +// Int64Value returns the value of the int64 pointer passed in or +// 0 if the pointer is nil. +func Int64Value(v *int64) int64 { + if v != nil { + return *v + } + return 0 +} + +// Int64Slice returns a slice of int64 pointers given a slice of int64s. +func Int64Slice(v []int64) []*int64 { + out := make([]*int64, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// NewBackends creates a new set of backends with the given HTTP client. You +// should only need to use this for testing purposes or on App Engine. +func NewBackends(httpClient *http.Client) *Backends { + apiConfig := &BackendConfig{HTTPClient: httpClient} + connectConfig := &BackendConfig{HTTPClient: httpClient} + uploadConfig := &BackendConfig{HTTPClient: httpClient} + return &Backends{ + API: GetBackendWithConfig(APIBackend, apiConfig), + Connect: GetBackendWithConfig(ConnectBackend, connectConfig), + Uploads: GetBackendWithConfig(UploadsBackend, uploadConfig), + } +} + +// ParseID attempts to parse a string scalar from a given JSON value which is +// still encoded as []byte. If the value was a string, it returns the string +// along with true as the second return value. If not, false is returned as the +// second return value. +// +// The purpose of this function is to detect whether a given value in a +// response from the Stripe API is a string ID or an expanded object. +func ParseID(data []byte) (string, bool) { + s := string(data) + + if !strings.HasPrefix(s, "\"") { + return "", false + } + + if !strings.HasSuffix(s, "\"") { + return "", false + } + + return s[1 : len(s)-1], true +} + +// SetAppInfo sets app information. See AppInfo. +func SetAppInfo(info *AppInfo) { + if info != nil && info.Name == "" { + panic(fmt.Errorf("App info name cannot be empty")) + } + appInfo = info + + // This is run in init, but we need to reinitialize it now that we have + // some app info. + initUserAgent() +} + +// SetBackend sets the backend used in the binding. +func SetBackend(backend SupportedBackend, b Backend) { + backends.mu.Lock() + defer backends.mu.Unlock() + + switch backend { + case APIBackend: + backends.API = b + case ConnectBackend: + backends.Connect = b + case UploadsBackend: + backends.Uploads = b + } +} + +// SetHTTPClient overrides the default HTTP client. +// This is useful if you're running in a Google AppEngine environment +// where the http.DefaultClient is not available. +func SetHTTPClient(client *http.Client) { + httpClient = client +} + +// String returns a pointer to the string value passed in. +func String(v string) *string { + return &v +} + +// StringValue returns the value of the string pointer passed in or +// "" if the pointer is nil. +func StringValue(v *string) string { + if v != nil { + return *v + } + return "" +} + +// StringSlice returns a slice of string pointers given a slice of strings. +func StringSlice(v []string) []*string { + out := make([]*string, len(v)) + for i := range v { + out[i] = &v[i] + } + return out +} + +// +// Private constants +// + +const apiURL = "https://api.stripe.com" + +// clientversion is the binding version +const clientversion = "70.5.0" + +// defaultHTTPTimeout is the default timeout on the http.Client used by the library. +// This is chosen to be consistent with the other Stripe language libraries and +// to coordinate with other timeouts configured in the Stripe infrastructure. +const defaultHTTPTimeout = 80 * time.Second + +// maxNetworkRetriesDelay and minNetworkRetriesDelay defines sleep time in milliseconds between +// tries to send HTTP request again after network failure. +const maxNetworkRetriesDelay = 5000 * time.Millisecond +const minNetworkRetriesDelay = 500 * time.Millisecond + +// The number of requestMetric objects to buffer for client telemetry. When the +// buffer is full, new requestMetrics are dropped. +const telemetryBufferSize = 16 + +const uploadsURL = "https://uploads.stripe.com" + +// +// Private types +// + +// nopReadCloser's sole purpose is to give us a way to turn an `io.Reader` into +// an `io.ReadCloser` by adding a no-op implementation of the `Closer` +// interface. We need this because `http.Request`'s `Body` takes an +// `io.ReadCloser` instead of a `io.Reader`. +type nopReadCloser struct { + io.Reader +} + +func (nopReadCloser) Close() error { return nil } + +// stripeClientUserAgent contains information about the current runtime which +// is serialized and sent in the `X-Stripe-Client-User-Agent` as additional +// debugging information. +type stripeClientUserAgent struct { + Application *AppInfo `json:"application"` + BindingsVersion string `json:"bindings_version"` + Language string `json:"lang"` + LanguageVersion string `json:"lang_version"` + Publisher string `json:"publisher"` + Uname string `json:"uname"` +} + +// requestMetrics contains the id and duration of the last request sent +type requestMetrics struct { + RequestDurationMS int `json:"request_duration_ms"` + RequestID string `json:"request_id"` +} + +// requestTelemetry contains the payload sent in the +// `X-Stripe-Client-Telemetry` header when BackendConfig.EnableTelemetry = true. +type requestTelemetry struct { + LastRequestMetrics requestMetrics `json:"last_request_metrics"` +} + +// +// Private variables +// + +var appInfo *AppInfo +var backends Backends +var encodedStripeUserAgent string +var encodedUserAgent string + +// The default HTTP client used for communication with any of Stripe's +// backends. +// +// Can be overridden with the function `SetHTTPClient` or by setting the +// `HTTPClient` value when using `BackendConfig`. +var httpClient = &http.Client{ + Timeout: defaultHTTPTimeout, + + // There is a bug in Go's HTTP/2 implementation that occasionally causes it + // to send an empty body when it receives a `GOAWAY` message from a server: + // + // https://github.com/golang/go/issues/32441 + // + // This is particularly problematic for this library because the empty body + // results in no parameters being sent, which usually results in a 400, + // which is a status code expressly not covered by retry logic. + // + // The bug seems to be somewhat tricky to fix and hasn't seen any traction + // lately, so for now we're mitigating by disabling HTTP/2 in stripe-go by + // default. Users who like to live dangerously can still re-enable it by + // specifying a custom HTTP client. When the bug above is fixed, we can + // turn it back on. + // + // The particular methodology here for disabling HTTP/2 is a little + // confusing at first glance, but is recommended by the `net/http` + // documentation ("Programs that must disable HTTP/2 can do so by setting + // Transport.TLSNextProto (for clients) ... to a non-nil, empty map.") + // + // Note that the test suite still uses HTTP/2 to run as it specifies its + // own HTTP client with it enabled. See `testing/testing.go`. + // + // (Written 2019/07/24.) + Transport: &http.Transport{ + TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper), + }, +} + +// +// Private functions +// + +// getUname tries to get a uname from the system, but not that hard. It tries +// to execute `uname -a`, but swallows any errors in case that didn't work +// (i.e. non-Unix non-Mac system or some other reason). +func getUname() string { + path, err := exec.LookPath("uname") + if err != nil { + return UnknownPlatform + } + + cmd := exec.Command(path, "-a") + var out bytes.Buffer + cmd.Stderr = nil // goes to os.DevNull + cmd.Stdout = &out + err = cmd.Run() + if err != nil { + return UnknownPlatform + } + + return out.String() +} + +func init() { + initUserAgent() +} + +func initUserAgent() { + encodedUserAgent = "Stripe/v1 GoBindings/" + clientversion + if appInfo != nil { + encodedUserAgent += " " + appInfo.formatUserAgent() + } + + stripeUserAgent := &stripeClientUserAgent{ + Application: appInfo, + BindingsVersion: clientversion, + Language: "go", + LanguageVersion: runtime.Version(), + Publisher: "stripe", + Uname: getUname(), + } + marshaled, err := json.Marshal(stripeUserAgent) + // Encoding this struct should never be a problem, so we're okay to panic + // in case it is for some reason. + if err != nil { + panic(err) + } + encodedStripeUserAgent = string(marshaled) +} + +func isHTTPWriteMethod(method string) bool { + return method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch || method == http.MethodDelete +} + +// newBackendImplementation returns a new Backend based off a given type and +// fully initialized BackendConfig struct. +// +// The vast majority of the time you should be calling GetBackendWithConfig +// instead of this function. +func newBackendImplementation(backendType SupportedBackend, config *BackendConfig) Backend { + var requestMetricsBuffer chan requestMetrics + enableTelemetry := config.EnableTelemetry || EnableTelemetry + + // only allocate the requestMetrics buffer if client telemetry is enabled. + if enableTelemetry { + requestMetricsBuffer = make(chan requestMetrics, telemetryBufferSize) + } + + return &BackendImplementation{ + HTTPClient: config.HTTPClient, + LeveledLogger: config.LeveledLogger, + MaxNetworkRetries: config.MaxNetworkRetries, + Type: backendType, + URL: config.URL, + enableTelemetry: enableTelemetry, + networkRetriesSleep: true, + requestMetricsBuffer: requestMetricsBuffer, + } +} + +func normalizeURL(url string) string { + // All paths include a leading slash, so to keep logs pretty, trim a + // trailing slash on the URL. + url = strings.TrimSuffix(url, "/") + + // For a long time we had the `/v1` suffix as part of a configured URL + // rather than in the per-package URLs throughout the library. Continue + // to support this for the time being by stripping one that's been + // passed for better backwards compatibility. + url = strings.TrimSuffix(url, "/v1") + + return url +} diff --git a/vendor/github.com/stripe/stripe-go/sub.go b/vendor/github.com/stripe/stripe-go/sub.go new file mode 100644 index 0000000..5212fa0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/sub.go @@ -0,0 +1,272 @@ +package stripe + +import ( + "encoding/json" + + "github.com/stripe/stripe-go/form" +) + +// SubscriptionStatus is the list of allowed values for the subscription's status. +type SubscriptionStatus string + +// List of values that SubscriptionStatus can take. +const ( + SubscriptionStatusActive SubscriptionStatus = "active" + SubscriptionStatusAll SubscriptionStatus = "all" + SubscriptionStatusCanceled SubscriptionStatus = "canceled" + SubscriptionStatusIncomplete SubscriptionStatus = "incomplete" + SubscriptionStatusIncompleteExpired SubscriptionStatus = "incomplete_expired" + SubscriptionStatusPastDue SubscriptionStatus = "past_due" + SubscriptionStatusTrialing SubscriptionStatus = "trialing" + SubscriptionStatusUnpaid SubscriptionStatus = "unpaid" +) + +// SubscriptionCollectionMethod is the type of collection method for this subscription's invoices. +type SubscriptionCollectionMethod string + +// List of values that SubscriptionCollectionMethod can take. +const ( + SubscriptionCollectionMethodChargeAutomatically SubscriptionCollectionMethod = "charge_automatically" + SubscriptionCollectionMethodSendInvoice SubscriptionCollectionMethod = "send_invoice" +) + +// SubscriptionPaymentBehavior lets you control the behavior of subscription creation in case of +// a failed payment. +type SubscriptionPaymentBehavior string + +// List of values that SubscriptionPaymentBehavior can take. +const ( + SubscriptionPaymentBehaviorAllowIncomplete SubscriptionPaymentBehavior = "allow_incomplete" + SubscriptionPaymentBehaviorErrorIfIncomplete SubscriptionPaymentBehavior = "error_if_incomplete" + SubscriptionPaymentBehaviorPendingIfIncomplete SubscriptionPaymentBehavior = "pending_if_incomplete" +) + +// SubscriptionProrationBehavior determines how to handle prorations when billing cycles change. +type SubscriptionProrationBehavior string + +// List of values that SubscriptionProrationBehavior can take. +const ( + SubscriptionProrationBehaviorAlwaysInvoice SubscriptionProrationBehavior = "always_invoice" + SubscriptionProrationBehaviorCreateProrations SubscriptionProrationBehavior = "create_prorations" + SubscriptionProrationBehaviorNone SubscriptionProrationBehavior = "none" +) + +// SubscriptionPendingInvoiceItemIntervalInterval controls the interval at which pending invoice +// items should be invoiced. +type SubscriptionPendingInvoiceItemIntervalInterval string + +// List of values that SubscriptionPendingInvoiceItemIntervalInterval can take. +const ( + SubscriptionPendingInvoiceItemIntervalIntervalDay SubscriptionPendingInvoiceItemIntervalInterval = "day" + SubscriptionPendingInvoiceItemIntervalIntervalMonth SubscriptionPendingInvoiceItemIntervalInterval = "month" + SubscriptionPendingInvoiceItemIntervalIntervalWeek SubscriptionPendingInvoiceItemIntervalInterval = "week" + SubscriptionPendingInvoiceItemIntervalIntervalYear SubscriptionPendingInvoiceItemIntervalInterval = "year" +) + +// SubscriptionPendingInvoiceItemIntervalParams is the set of parameters allowed for the transfer_data hash. +type SubscriptionPendingInvoiceItemIntervalParams struct { + Interval *string `form:"interval"` + IntervalCount *int64 `form:"interval_count"` +} + +// SubscriptionTransferDataParams is the set of parameters allowed for the transfer_data hash. +type SubscriptionTransferDataParams struct { + Destination *string `form:"destination"` +} + +// SubscriptionParams is the set of parameters that can be used when creating or updating a subscription. +// For more details see https://stripe.com/docs/api#create_subscription and https://stripe.com/docs/api#update_subscription. +type SubscriptionParams struct { + Params `form:"*"` + ApplicationFeePercent *float64 `form:"application_fee_percent"` + BackdateStartDate *int64 `form:"backdate_start_date"` + BillingCycleAnchor *int64 `form:"billing_cycle_anchor"` + BillingCycleAnchorNow *bool `form:"-"` // See custom AppendTo + BillingCycleAnchorUnchanged *bool `form:"-"` // See custom AppendTo + BillingThresholds *SubscriptionBillingThresholdsParams `form:"billing_thresholds"` + CancelAt *int64 `form:"cancel_at"` + CancelAtPeriodEnd *bool `form:"cancel_at_period_end"` + Card *CardParams `form:"card"` + CollectionMethod *string `form:"collection_method"` + Coupon *string `form:"coupon"` + 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"` + Items []*SubscriptionItemsParams `form:"items"` + OffSession *bool `form:"off_session"` + OnBehalfOf *string `form:"on_behalf_of"` + PaymentBehavior *string `form:"payment_behavior"` + PendingInvoiceItemInterval *SubscriptionPendingInvoiceItemIntervalParams `form:"pending_invoice_item_interval"` + Plan *string `form:"plan"` + Prorate *bool `form:"prorate"` + ProrationBehavior *string `form:"proration_behavior"` + ProrationDate *int64 `form:"proration_date"` + Quantity *int64 `form:"quantity"` + TrialEnd *int64 `form:"trial_end"` + TransferData *SubscriptionTransferDataParams `form:"transfer_data"` + TrialEndNow *bool `form:"-"` // See custom AppendTo + TrialFromPlan *bool `form:"trial_from_plan"` + TrialPeriodDays *int64 `form:"trial_period_days"` + + // This parameter is deprecated and we recommend that you use TaxRates instead. + TaxPercent *float64 `form:"tax_percent"` +} + +// SubscriptionBillingThresholdsParams is a structure representing the parameters allowed to control +// billing thresholds for a subscription. +type SubscriptionBillingThresholdsParams struct { + AmountGTE *int64 `form:"amount_gte"` + ResetBillingCycleAnchor *bool `form:"reset_billing_cycle_anchor"` +} + +// SubscriptionCancelParams is the set of parameters that can be used when canceling a subscription. +// For more details see https://stripe.com/docs/api#cancel_subscription +type SubscriptionCancelParams struct { + Params `form:"*"` + InvoiceNow *bool `form:"invoice_now"` + Prorate *bool `form:"prorate"` +} + +// AppendTo implements custom encoding logic for SubscriptionParams so that the special +// "now" value for billing_cycle_anchor and trial_end can be implemented +// (they're otherwise timestamps rather than strings). +func (p *SubscriptionParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.BillingCycleAnchorNow) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "now") + } + + if BoolValue(p.BillingCycleAnchorUnchanged) { + body.Add(form.FormatKey(append(keyParts, "billing_cycle_anchor")), "unchanged") + } + + if BoolValue(p.TrialEndNow) { + body.Add(form.FormatKey(append(keyParts, "trial_end")), "now") + } +} + +// SubscriptionItemsParams is the set of parameters that can be used when creating or updating a subscription item on a subscription +// For more details see https://stripe.com/docs/api#create_subscription and https://stripe.com/docs/api#update_subscription. +type SubscriptionItemsParams struct { + Params `form:"*"` + BillingThresholds *SubscriptionItemBillingThresholdsParams `form:"billing_thresholds"` + ClearUsage *bool `form:"clear_usage"` + Deleted *bool `form:"deleted"` + ID *string `form:"id"` + Plan *string `form:"plan"` + Quantity *int64 `form:"quantity"` + TaxRates []*string `form:"tax_rates"` +} + +// SubscriptionListParams is the set of parameters that can be used when listing active subscriptions. +// For more details see https://stripe.com/docs/api#list_subscriptions. +type SubscriptionListParams struct { + ListParams `form:"*"` + CollectionMethod *string `form:"collection_method"` + Created int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` + CurrentPeriodEnd *int64 `form:"current_period_end"` + CurrentPeriodEndRange *RangeQueryParams `form:"current_period_end"` + CurrentPeriodStart *int64 `form:"current_period_start"` + CurrentPeriodStartRange *RangeQueryParams `form:"current_period_start"` + Customer string `form:"customer"` + Plan string `form:"plan"` + Status string `form:"status"` +} + +// SubscriptionPendingInvoiceItemInterval represents the interval at which to invoice pending invoice +// items. +type SubscriptionPendingInvoiceItemInterval struct { + Interval SubscriptionPendingInvoiceItemIntervalInterval `json:"interval"` + IntervalCount int64 `json:"interval_count"` +} + +// SubscriptionPendingUpdate represents deferred changes that will be applied when latest invoice is paid. +type SubscriptionPendingUpdate struct { + BillingCycleAnchor int64 `json:"billing_cycle_anchor"` + ExpiresAt int64 `json:"expires_at"` + SubscriptionItems []*SubscriptionItem `json:"subscription_items"` + TrialEnd int64 `json:"trial_end"` + TrialFromPlan bool `json:"trial_from_plan"` +} + +// SubscriptionTransferData represents the information for the transfer_data associated with a subscription. +type SubscriptionTransferData struct { + Destination *Account `json:"destination"` +} + +// Subscription is the resource representing a Stripe subscription. +// For more details see https://stripe.com/docs/api#subscriptions. +type Subscription struct { + ApplicationFeePercent float64 `json:"application_fee_percent"` + BillingCycleAnchor int64 `json:"billing_cycle_anchor"` + BillingThresholds *SubscriptionBillingThresholds `json:"billing_thresholds"` + CancelAt int64 `json:"cancel_at"` + CancelAtPeriodEnd bool `json:"cancel_at_period_end"` + CanceledAt int64 `json:"canceled_at"` + CollectionMethod SubscriptionCollectionMethod `json:"collection_method"` + Created int64 `json:"created"` + CurrentPeriodEnd int64 `json:"current_period_end"` + CurrentPeriodStart int64 `json:"current_period_start"` + Customer *Customer `json:"customer"` + DaysUntilDue int64 `json:"days_until_due"` + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + DefaultSource *PaymentSource `json:"default_source"` + DefaultTaxRates []*TaxRate `json:"default_tax_rates"` + Discount *Discount `json:"discount"` + EndedAt int64 `json:"ended_at"` + ID string `json:"id"` + Items *SubscriptionItemList `json:"items"` + LatestInvoice *Invoice `json:"latest_invoice"` + Livemode bool `json:"livemode"` + Metadata map[string]string `json:"metadata"` + NextPendingInvoiceItemInvoice int64 `json:"next_pending_invoice_item_invoice"` + Object string `json:"object"` + OnBehalfOf *Account `json:"on_behalf_of"` + PendingInvoiceItemInterval SubscriptionPendingInvoiceItemInterval `json:"pending_invoice_item_interval"` + PendingSetupIntent *SetupIntent `json:"pending_setup_intent"` + PendingUpdate *SubscriptionPendingUpdate `json:"pending_update"` + Plan *Plan `json:"plan"` + Quantity int64 `json:"quantity"` + Schedule *SubscriptionSchedule `json:"schedule"` + StartDate int64 `json:"start_date"` + Status SubscriptionStatus `json:"status"` + TransferData *SubscriptionTransferData `json:"transfer_data"` + TrialEnd int64 `json:"trial_end"` + TrialStart int64 `json:"trial_start"` + + // This field is deprecated and we recommend that you use TaxRates instead. + TaxPercent float64 `json:"tax_percent"` +} + +// SubscriptionBillingThresholds is a structure representing the billing thresholds for a subscription. +type SubscriptionBillingThresholds struct { + AmountGTE int64 `json:"amount_gte"` + ResetBillingCycleAnchor bool `json:"reset_billing_cycle_anchor"` +} + +// SubscriptionList is a list object for subscriptions. +type SubscriptionList struct { + ListMeta + Data []*Subscription `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Subscription. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *Subscription) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type subscription Subscription + var v subscription + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = Subscription(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/subitem.go b/vendor/github.com/stripe/stripe-go/subitem.go new file mode 100644 index 0000000..bb6f1d7 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/subitem.go @@ -0,0 +1,60 @@ +package stripe + +// SubscriptionItemParams is the set of parameters that can be used when creating or updating a subscription item. +// For more details see https://stripe.com/docs/api#create_subscription_item and https://stripe.com/docs/api#update_subscription_item. +type SubscriptionItemParams struct { + Params `form:"*"` + ID *string `form:"-"` // Handled in URL + BillingThresholds *SubscriptionItemBillingThresholdsParams `form:"billing_thresholds"` + ClearUsage *bool `form:"clear_usage"` + PaymentBehavior *string `form:"payment_behavior"` + Plan *string `form:"plan"` + Prorate *bool `form:"prorate"` + ProrationDate *int64 `form:"proration_date"` + ProrationBehavior *string `form:"proration_behavior"` + Quantity *int64 `form:"quantity"` + Subscription *string `form:"subscription"` + TaxRates []*string `form:"tax_rates"` + + // The following parameters are only supported on updates + OffSession *bool `form:"off_session"` +} + +// SubscriptionItemBillingThresholdsParams is a structure representing the parameters allowed to +// control billing thresholds for a subscription item. +type SubscriptionItemBillingThresholdsParams struct { + UsageGTE *int64 `form:"usage_gte"` +} + +// SubscriptionItemListParams 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 SubscriptionItemListParams struct { + ListParams `form:"*"` + Subscription *string `form:"subscription"` +} + +// SubscriptionItem is the resource representing a Stripe subscription item. +// For more details see https://stripe.com/docs/api#subscription_items. +type SubscriptionItem struct { + BillingThresholds SubscriptionItemBillingThresholds `json:"billing_thresholds"` + Created int64 `json:"created"` + Deleted bool `json:"deleted"` + ID string `json:"id"` + Metadata map[string]string `json:"metadata"` + Plan *Plan `json:"plan"` + Quantity int64 `json:"quantity"` + Subscription string `json:"subscription"` + TaxRates []*TaxRate `json:"tax_rates"` +} + +// SubscriptionItemBillingThresholds is a structure representing the billing thresholds for a +// subscription item. +type SubscriptionItemBillingThresholds struct { + UsageGTE int64 `form:"usage_gte"` +} + +// SubscriptionItemList is a list of invoice items as retrieved from a list endpoint. +type SubscriptionItemList struct { + ListMeta + Data []*SubscriptionItem `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/subschedule.go b/vendor/github.com/stripe/stripe-go/subschedule.go new file mode 100644 index 0000000..73016f6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/subschedule.go @@ -0,0 +1,230 @@ +package stripe + +import ( + "encoding/json" + + "github.com/stripe/stripe-go/form" +) + +// SubscriptionScheduleEndBehavior describe what happens to a schedule when it ends. +type SubscriptionScheduleEndBehavior string + +// List of values that SubscriptionScheduleEndBehavior can take. +const ( + SubscriptionScheduleEndBehaviorCancel SubscriptionScheduleEndBehavior = "cancel" + SubscriptionScheduleEndBehaviorRelease SubscriptionScheduleEndBehavior = "release" +) + +// SubscriptionScheduleStatus is the list of allowed values for the schedule's status. +type SubscriptionScheduleStatus string + +// List of values that SubscriptionScheduleStatus can take. +const ( + SubscriptionScheduleStatusActive SubscriptionScheduleStatus = "active" + SubscriptionScheduleStatusCanceled SubscriptionScheduleStatus = "canceled" + SubscriptionScheduleStatusCompleted SubscriptionScheduleStatus = "completed" + SubscriptionScheduleStatusPastDue SubscriptionScheduleStatus = "not_started" + SubscriptionScheduleStatusTrialing SubscriptionScheduleStatus = "released" +) + +// SubscriptionScheduleInvoiceSettingsParams is a structure representing the parameters allowed to +// control invoice settings on invoices associated with a subscription schedule. +type SubscriptionScheduleInvoiceSettingsParams struct { + DaysUntilDue *int64 `form:"days_until_due"` +} + +// SubscriptionScheduleDefaultSettingsParams is the set of parameters +// representing the subscription schedule’s default settings. +type SubscriptionScheduleDefaultSettingsParams struct { + Params `form:"*"` + BillingThresholds *SubscriptionBillingThresholdsParams `form:"billing_thresholds"` + CollectionMethod *string `form:"collection_method"` + DefaultPaymentMethod *string `form:"default_payment_method"` + InvoiceSettings *SubscriptionScheduleInvoiceSettingsParams `form:"invoice_settings"` +} + +// SubscriptionSchedulePhaseItemParams is a structure representing the parameters allowed to control +// a specic plan on a phase on a subscription schedule. +type SubscriptionSchedulePhaseItemParams struct { + BillingThresholds *SubscriptionItemBillingThresholdsParams `form:"billing_thresholds"` + Plan *string `form:"plan"` + Quantity *int64 `form:"quantity"` + TaxRates []*string `form:"tax_rates"` +} + +// SubscriptionSchedulePhaseParams is a structure representing the parameters allowed to control +// a phase on a subscription schedule. +type SubscriptionSchedulePhaseParams struct { + ApplicationFeePercent *int64 `form:"application_fee_percent"` + BillingThresholds *SubscriptionBillingThresholdsParams `form:"billing_thresholds"` + CollectionMethod *string `form:"collection_method"` + Coupon *string `form:"coupon"` + DefaultPaymentMethod *string `form:"default_payment_method"` + DefaultTaxRates []*string `form:"default_tax_rates"` + EndDate *int64 `form:"end_date"` + InvoiceSettings *SubscriptionScheduleInvoiceSettingsParams `form:"invoice_settings"` + Iterations *int64 `form:"iterations"` + Plans []*SubscriptionSchedulePhaseItemParams `form:"plans"` + ProrationBehavior *string `form:"proration_behavior"` + StartDate *int64 `form:"start_date"` + Trial *bool `form:"trial"` + TrialEnd *int64 `form:"trial_end"` + + // This parameter is deprecated and we recommend that you use TaxRates instead. + TaxPercent *float64 `form:"tax_percent"` +} + +// SubscriptionScheduleParams is the set of parameters that can be used when creating or updating a +// subscription schedule. +type SubscriptionScheduleParams struct { + Params `form:"*"` + Customer *string `form:"customer"` + DefaultSettings *SubscriptionScheduleDefaultSettingsParams `form:"default_settings"` + EndBehavior *string `form:"end_behavior"` + FromSubscription *string `form:"from_subscription"` + ProrationBehavior *string `form:"proration_behavior"` + Phases []*SubscriptionSchedulePhaseParams `form:"phases"` + StartDate *int64 `form:"start_date"` + StartDateNow *bool `form:"-"` // See custom AppendTo + + // TODO remove in the next major version + // This propery is considered deprecated. Use ProrationBehavior instead + Prorate *bool `form:"prorate"` +} + +// AppendTo implements custom encoding logic for SubscriptionScheduleParams so that the special +// "now" value for start_date can be implemented (they're otherwise timestamps rather than strings). +func (p *SubscriptionScheduleParams) AppendTo(body *form.Values, keyParts []string) { + if BoolValue(p.StartDateNow) { + body.Add(form.FormatKey(append(keyParts, "start_date")), "now") + } +} + +// SubscriptionScheduleCancelParams is the set of parameters that can be used when canceling a +// subscription schedule. +type SubscriptionScheduleCancelParams struct { + Params `form:"*"` + InvoiceNow *bool `form:"invoice_now"` + Prorate *bool `form:"prorate"` +} + +// SubscriptionScheduleReleaseParams is the set of parameters that can be used when releasing a +// subscription schedule. +type SubscriptionScheduleReleaseParams struct { + Params `form:"*"` + PreserveCancelDate *bool `form:"preserve_cancel_date"` +} + +// SubscriptionScheduleListParams is the set of parameters that can be used when listing +// subscription schedules. +type SubscriptionScheduleListParams struct { + ListParams `form:"*"` + CanceledAt int64 `form:"canceled_at"` + CanceledAtRange *RangeQueryParams `form:"canceled_at"` + CompletedAt int64 `form:"completed_at"` + CompletedAtRange *RangeQueryParams `form:"completed_at"` + Created int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` + Customer string `form:"customer"` + ReleasedAt int64 `form:"released_at"` + ReleasedAtRange *RangeQueryParams `form:"released_at"` + Scheduled *bool `form:"scheduled"` +} + +// SubscriptionScheduleCurrentPhase is a structure the current phase's period. +type SubscriptionScheduleCurrentPhase struct { + EndDate int64 `json:"end_date"` + StartDate int64 `json:"start_date"` +} + +// SubscriptionScheduleInvoiceSettings is a structure representing the settings applied to invoices +// associated with a subscription schedule. +type SubscriptionScheduleInvoiceSettings struct { + DaysUntilDue int64 `json:"days_until_due"` +} + +// SubscriptionScheduleDefaultSettings is a structure representing the +// subscription schedule’s default settings. +type SubscriptionScheduleDefaultSettings struct { + BillingThresholds *SubscriptionBillingThresholds `json:"billing_thresholds"` + CollectionMethod SubscriptionCollectionMethod `json:"collection_method"` + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + InvoiceSettings *SubscriptionScheduleInvoiceSettings `json:"invoice_settings"` +} + +// SubscriptionSchedulePhaseItem represents plan details for a given phase +type SubscriptionSchedulePhaseItem struct { + BillingThresholds *SubscriptionItemBillingThresholds `json:"billing_thresholds"` + Plan *Plan `json:"plan"` + Quantity int64 `json:"quantity"` + TaxRates []*TaxRate `json:"tax_rates"` +} + +// SubscriptionSchedulePhase is a structure a phase of a subscription schedule. +type SubscriptionSchedulePhase struct { + ApplicationFeePercent float64 `json:"application_fee_percent"` + BillingThresholds *SubscriptionBillingThresholds `json:"billing_thresholds"` + CollectionMethod SubscriptionCollectionMethod `json:"collection_method"` + Coupon *Coupon `json:"coupon"` + DefaultPaymentMethod *PaymentMethod `json:"default_payment_method"` + DefaultTaxRates []*TaxRate `json:"default_tax_rates"` + EndDate int64 `json:"end_date"` + InvoiceSettings *SubscriptionScheduleInvoiceSettings `json:"invoice_settings"` + Plans []*SubscriptionSchedulePhaseItem `json:"plans"` + StartDate int64 `json:"start_date"` + TrialEnd int64 `json:"trial_end"` + + // This field is deprecated and we recommend that you use TaxRates instead. + TaxPercent float64 `json:"tax_percent"` +} + +// SubscriptionScheduleRenewalInterval represents the interval and duration of a schedule. +type SubscriptionScheduleRenewalInterval struct { + Interval PlanInterval `form:"interval"` + Length int64 `form:"length"` +} + +// SubscriptionSchedule is the resource representing a Stripe subscription schedule. +type SubscriptionSchedule struct { + CanceledAt int64 `json:"canceled_at"` + CompletedAt int64 `json:"completed_at"` + Created int64 `json:"created"` + CurrentPhase *SubscriptionScheduleCurrentPhase `json:"current_phase"` + Customer *Customer `json:"customer"` + DefaultSettings *SubscriptionScheduleDefaultSettings `json:"default_settings"` + EndBehavior SubscriptionScheduleEndBehavior `json:"end_behavior"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Metadata map[string]string `json:"metadata"` + Object string `json:"object"` + Phases []*SubscriptionSchedulePhase `json:"phases"` + ReleasedSubscription *Subscription `json:"released_subscription"` + RenewalInterval *SubscriptionScheduleRenewalInterval `json:"renewal_interval"` + Status SubscriptionScheduleStatus `json:"status"` + Subscription *Subscription `json:"subscription"` +} + +// SubscriptionScheduleList is a list object for subscription schedules. +type SubscriptionScheduleList struct { + ListMeta + Data []*SubscriptionSchedule `json:"data"` +} + +// UnmarshalJSON handles deserialization of a SubscriptionSchedule. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (s *SubscriptionSchedule) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + s.ID = id + return nil + } + + type schedule SubscriptionSchedule + var v schedule + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *s = SubscriptionSchedule(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/taxid.go b/vendor/github.com/stripe/stripe-go/taxid.go new file mode 100644 index 0000000..1f7020d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/taxid.go @@ -0,0 +1,107 @@ +package stripe + +import "encoding/json" + +// TaxIDType is the list of allowed values for the tax id's type.. +type TaxIDType string + +// List of values that TaxIDType can take. +const ( + TaxIDTypeAUABN TaxIDType = "au_abn" + TaxIDTypeCABN TaxIDType = "ca_bn" + TaxIDTypeCAQST TaxIDType = "ca_qst" + TaxIDTypeCHVAT TaxIDType = "ch_vat" + TaxIDTypeESCIF TaxIDType = "es_cif" + TaxIDTypeEUVAT TaxIDType = "eu_vat" + TaxIDTypeHKBR TaxIDType = "hk_br" + TaxIDTypeINGST TaxIDType = "in_gst" + TaxIDTypeJPCN TaxIDType = "jp_cn" + TaxIDTypeKRBRN TaxIDType = "kr_brn" + TaxIDTypeLIUID TaxIDType = "li_uid" + TaxIDTypeMXRFC TaxIDType = "mx_rfc" + TaxIDTypeMYITN TaxIDType = "my_itn" + TaxIDTypeMYSST TaxIDType = "my_sst" + TaxIDTypeNOVAT TaxIDType = "no_vat" + TaxIDTypeNZGST TaxIDType = "nz_gst" + TaxIDTypeRUINN TaxIDType = "ru_inn" + TaxIDTypeSGUEN TaxIDType = "sg_uen" + TaxIDTypeTHVAT TaxIDType = "th_vat" + TaxIDTypeTWVAT TaxIDType = "tw_vat" + TaxIDTypeUSEIN TaxIDType = "us_ein" + TaxIDTypeZAVAT TaxIDType = "za_vat" + TaxIDTypeUnknown TaxIDType = "unknown" +) + +// TaxIDVerificationStatus is the list of allowed values for the tax id's verification status.. +type TaxIDVerificationStatus string + +// List of values that TaxIDDuration can take. +const ( + TaxIDVerificationStatusPending TaxIDVerificationStatus = "pending" + TaxIDVerificationStatusUnavailable TaxIDVerificationStatus = "unavailable" + TaxIDVerificationStatusUnverified TaxIDVerificationStatus = "unverified" + TaxIDVerificationStatusVerified TaxIDVerificationStatus = "verified" +) + +// TaxIDParams is the set of parameters that can be used when creating a tax id. +// For more details see https://stripe.com/docs/api/customers/create_tax_id +type TaxIDParams struct { + Params `form:"*"` + Customer *string `form:"-"` + Type *string `form:"type"` + Value *string `form:"value"` +} + +// TaxIDListParams is the set of parameters that can be used when listing tax ids. +// For more detail see https://stripe.com/docs/api/customers/tax_ids +type TaxIDListParams struct { + ListParams `form:"*"` + Customer *string `form:"-"` +} + +// TaxIDVerification represents the verification details of a customer's tax id. +type TaxIDVerification struct { + Status TaxIDVerificationStatus `json:"status"` + VerifiedAddress string `json:"verified_address"` + VerifiedName string `json:"verified_name"` +} + +// TaxID is the resource representing a customer's tax id. +// For more details see https://stripe.com/docs/api/customers/tax_id_object +type TaxID struct { + Country string `json:"country"` + Created int64 `json:"created"` + Customer *Customer `json:"customer"` + Deleted bool `json:"deleted"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Object string `json:"object"` + Type TaxIDType `json:"type"` + Value string `json:"value"` + Verification *TaxIDVerification `json:"verification"` +} + +// TaxIDList is a list of tax ids as retrieved from a list endpoint. +type TaxIDList struct { + ListMeta + Data []*TaxID `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TaxID. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *TaxID) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type taxid TaxID + var v taxid + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = TaxID(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/taxrate.go b/vendor/github.com/stripe/stripe-go/taxrate.go new file mode 100644 index 0000000..733087d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/taxrate.go @@ -0,0 +1,76 @@ +package stripe + +import "encoding/json" + +// TaxRateParams is the set of parameters that can be used when creating a tax rate. +// For more details see https://stripe.com/docs/api/tax_rates/create. +type TaxRateParams struct { + Params `form:"*"` + Active *bool `form:"active"` + Description *string `form:"description"` + DisplayName *string `form:"display_name"` + Inclusive *bool `form:"inclusive"` + Jurisdiction *string `form:"jurisdiction"` + Percentage *float64 `form:"percentage"` +} + +// TaxRatePercentageRangeQueryParams are used to filter tax rates by specific percentage values. +type TaxRatePercentageRangeQueryParams struct { + GreaterThan float64 `form:"gt"` + GreaterThanOrEqual float64 `form:"gte"` + LesserThan float64 `form:"lt"` + LesserThanOrEqual float64 `form:"lte"` +} + +// TaxRateListParams is the set of parameters that can be used when listing tax rates. +// For more detail see https://stripe.com/docs/api/tax_rates/list. +type TaxRateListParams struct { + ListParams `form:"*"` + Active *bool `form:"active"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` + Inclusive *bool `form:"inclusive"` + Percentage *float64 `form:"percentage"` + PercentageRange *TaxRatePercentageRangeQueryParams `form:"percentage"` +} + +// TaxRate is the resource representing a Stripe tax rate. +// For more details see https://stripe.com/docs/api/tax_rates/object. +type TaxRate struct { + Active bool `json:"active"` + Created int64 `json:"created"` + Description string `json:"description"` + DisplayName string `json:"display_name"` + ID string `json:"id"` + Inclusive bool `json:"inclusive"` + Jurisdiction string `json:"jurisdiction"` + Livemode bool `json:"livemode"` + Metadata map[string]string `json:"metadata"` + Object string `json:"object"` + Percentage float64 `json:"percentage"` +} + +// TaxRateList is a list of tax rates as retrieved from a list endpoint. +type TaxRateList struct { + ListMeta + Data []*TaxRate `json:"data"` +} + +// UnmarshalJSON handles deserialization of a TaxRate. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *TaxRate) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type taxrate TaxRate + var v taxrate + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = TaxRate(v) + return nil +} diff --git a/vendor/github.com/stripe/stripe-go/terminal_connectiontoken.go b/vendor/github.com/stripe/stripe-go/terminal_connectiontoken.go new file mode 100644 index 0000000..4d599b2 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/terminal_connectiontoken.go @@ -0,0 +1,14 @@ +package stripe + +// TerminalConnectionTokenParams is the set of parameters that can be used when creating a terminal connection token. +type TerminalConnectionTokenParams struct { + Params `form:"*"` + Location string `form:"location"` +} + +// TerminalConnectionToken is the resource representing a Stripe terminal connection token. +type TerminalConnectionToken struct { + Location string `json:"location"` + Object string `json:"object"` + Secret string `json:"secret"` +} diff --git a/vendor/github.com/stripe/stripe-go/terminal_location.go b/vendor/github.com/stripe/stripe-go/terminal_location.go new file mode 100644 index 0000000..4ab6735 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/terminal_location.go @@ -0,0 +1,30 @@ +package stripe + +// TerminalLocationParams is the set of parameters that can be used when creating or updating a terminal location. +type TerminalLocationParams struct { + Params `form:"*"` + Address *AccountAddressParams `form:"address"` + DisplayName *string `form:"display_name"` +} + +// TerminalLocationListParams is the set of parameters that can be used when listing temrinal locations. +type TerminalLocationListParams struct { + ListParams `form:"*"` +} + +// TerminalLocation is the resource representing a Stripe terminal location. +type TerminalLocation struct { + Address *AccountAddressParams `json:"address"` + Deleted bool `json:"deleted"` + DisplayName string `json:"display_name"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Metadata map[string]string `json:"metadata"` + Object string `json:"object"` +} + +// TerminalLocationList is a list of terminal readers as retrieved from a list endpoint. +type TerminalLocationList struct { + ListMeta + Data []*TerminalLocation `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/terminal_reader.go b/vendor/github.com/stripe/stripe-go/terminal_reader.go new file mode 100644 index 0000000..c0c250d --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/terminal_reader.go @@ -0,0 +1,46 @@ +package stripe + +// TerminalReaderParams is the set of parameters that can be used for creating or updating a terminal reader. +type TerminalReaderParams struct { + Params `form:"*"` + Label *string `form:"label"` + Location *string `form:"location"` + RegistrationCode *string `form:"registration_code"` +} + +// TerminalReaderGetParams is the set of parameters that can be used to get a terminal reader. +type TerminalReaderGetParams struct { + Params `form:"*"` +} + +// TerminalReaderListParams is the set of parameters that can be used when listing temrinal readers. +type TerminalReaderListParams struct { + ListParams `form:"*"` + DeviceType *string `form:"device_type"` + Location *string `form:"location"` + Status *string `form:"status"` +} + +// TerminalReader is the resource representing a Stripe terminal reader. +type TerminalReader struct { + Deleted bool `json:"deleted"` + DeviceSwVersion string `json:"device_sw_version"` + DeviceType string `json:"device_type"` + ID string `json:"id"` + IPAddress string `json:"ip_address"` + Label string `json:"label"` + Livemode bool `json:"livemode"` + Location string `json:"location"` + Metadata map[string]string `json:"metadata"` + Object string `json:"object"` + SerialNumber string `json:"serial_number"` + Status string `json:"status"` +} + +// TerminalReaderList is a list of terminal readers as retrieved from a list endpoint. +type TerminalReaderList struct { + ListMeta + Data []*TerminalReader `json:"data"` + Location *string `json:"location"` + Status *string `json:"status"` +} diff --git a/vendor/github.com/stripe/stripe-go/threedsecure.go b/vendor/github.com/stripe/stripe-go/threedsecure.go new file mode 100644 index 0000000..db02779 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/threedsecure.go @@ -0,0 +1,29 @@ +package stripe + +// ThreeDSecureStatus represents the possible statuses of a ThreeDSecure object. +type ThreeDSecureStatus string + +// ThreeDSecureParams is the set of parameters that can be used when creating a 3DS object. +type ThreeDSecureParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + Card *string `form:"card"` + Currency *string `form:"currency"` + Customer *string `form:"customer"` + ReturnURL *string `form:"return_url"` +} + +// ThreeDSecure is the resource representing a Stripe 3DS object +// For more details see https://stripe.com/docs/api#three_d_secure. +type ThreeDSecure struct { + Amount int64 `json:"amount"` + Authenticated bool `json:"authenticated"` + Card *Card `json:"card"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + RedirectURL string `json:"redirect_url"` + Status ThreeDSecureStatus `json:"status"` + Supported string `json:"supported"` +} diff --git a/vendor/github.com/stripe/stripe-go/token.go b/vendor/github.com/stripe/stripe-go/token.go new file mode 100644 index 0000000..f9958d6 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/token.go @@ -0,0 +1,51 @@ +package stripe + +// TokenType is the list of allowed values for a token's type. +type TokenType string + +// List of values that TokenType can take. +const ( + TokenTypeAccount TokenType = "account" + TokenTypeCard TokenType = "card" + TokenTypeBankAccount TokenType = "bank_account" + TokenTypePII TokenType = "pii" +) + +// TokenParams is the set of parameters that can be used when creating a token. +// For more details see https://stripe.com/docs/api#create_card_token and https://stripe.com/docs/api#create_bank_account_token. +type TokenParams struct { + Params `form:"*"` + BankAccount *BankAccountParams `form:"bank_account"` + Card *CardParams `form:"card"` + Customer *string `form:"customer"` + + // Email is an undocumented parameter used by Stripe Checkout + // It may be removed from the API without notice. + Email *string `form:"email"` + + PII *PIIParams `form:"pii"` +} + +// Token is the resource representing a Stripe token. +// For more details see https://stripe.com/docs/api#tokens. +type Token struct { + BankAccount *BankAccount `json:"bank_account"` + Card *Card `json:"card"` + ClientIP string `json:"client_ip"` + Created int64 `json:"created"` + + // Email is an undocumented field but included for all tokens created + // with Stripe Checkout. + Email string `json:"email"` + + ID string `json:"id"` + Livemode bool `json:"livemode"` + Type TokenType `json:"type"` + Used bool `json:"used"` +} + +// PIIParams are parameters for personal identifiable information (PII). +type PIIParams struct { + Params `form:"*"` + IDNumber *string `form:"id_number"` +} diff --git a/vendor/github.com/stripe/stripe-go/topup.go b/vendor/github.com/stripe/stripe-go/topup.go new file mode 100644 index 0000000..cf0e852 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/topup.go @@ -0,0 +1,55 @@ +package stripe + +// TopupParams is the set of parameters that can be used when creating or updating a top-up. +// For more details see https://stripe.com/docs/api#create_topup and https://stripe.com/docs/api#update_topup. +type TopupParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + Currency *string `form:"currency"` + Description *string `form:"description"` + Source *SourceParams `form:"*"` // SourceParams has custom encoding so brought to top level with "*" + StatementDescriptor *string `form:"statement_descriptor"` + TransferGroup *string `form:"transfer_group"` +} + +// SetSource adds valid sources to a TopupParams object, +// returning an error for unsupported sources. +func (p *TopupParams) SetSource(sp interface{}) error { + source, err := SourceParamsFor(sp) + p.Source = source + return err +} + +// TopupListParams is the set of parameters that can be used when listing top-ups. +// For more details see https://stripe.com/docs/api#list_topups. +type TopupListParams struct { + ListParams `form:"*"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` +} + +// TopupList is a list of top-ups as retrieved from a list endpoint. +type TopupList struct { + ListMeta + Data []*Topup `json:"data"` +} + +// Topup is the resource representing a Stripe top-up. +// For more details see https://stripe.com/docs/api#topups. +type Topup struct { + Amount int64 `json:"amount"` + ArrivalDate int64 `json:"arrival_date"` + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + Description string `json:"description"` + ExpectedAvailabilityDate int64 `json:"expected_availability_date"` + FailureCode string `json:"failure_code"` + FailureMessage string `json:"failure_message"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Source *PaymentSource `json:"source"` + StatementDescriptor string `json:"statement_descriptor"` + Status string `json:"status"` + TransferGroup string `json:"transfer_group"` +} diff --git a/vendor/github.com/stripe/stripe-go/transfer.go b/vendor/github.com/stripe/stripe-go/transfer.go new file mode 100644 index 0000000..6dd77a0 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/transfer.go @@ -0,0 +1,111 @@ +package stripe + +import "encoding/json" + +// TransferSourceType is the list of allowed values for the transfer's source_type field. +type TransferSourceType string + +// List of values that TransferSourceType can take. +const ( + TransferSourceTypeAlipayAccount TransferSourceType = "alipay_account" + TransferSourceTypeBankAccount TransferSourceType = "bank_account" + TransferSourceTypeBitcoinReceiver TransferSourceType = "bitcoin_receiver" + TransferSourceTypeCard TransferSourceType = "card" + TransferSourceTypeFPX TransferSourceType = "fpx" +) + +// TransferDestination describes the destination of a Transfer. +// The Type should indicate which object is fleshed out +// For more details see https://stripe.com/docs/api/go#transfer_object +type TransferDestination struct { + Account *Account `json:"-"` + ID string `json:"id"` +} + +// TransferParams is the set of parameters that can be used when creating or updating a transfer. +// For more details see https://stripe.com/docs/api#create_transfer and https://stripe.com/docs/api#update_transfer. +type TransferParams struct { + Params `form:"*"` + Amount *int64 `form:"amount"` + Currency *string `form:"currency"` + Description *string `form:"description"` + Destination *string `form:"destination"` + SourceTransaction *string `form:"source_transaction"` + SourceType *string `form:"source_type"` + TransferGroup *string `form:"transfer_group"` +} + +// TransferListParams is the set of parameters that can be used when listing transfers. +// For more details see https://stripe.com/docs/api#list_transfers. +type TransferListParams struct { + ListParams `form:"*"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` + Destination *string `form:"destination"` + TransferGroup *string `form:"transfer_group"` +} + +// Transfer is the resource representing a Stripe transfer. +// For more details see https://stripe.com/docs/api#transfers. +type Transfer struct { + Amount int64 `json:"amount"` + AmountReversed int64 `json:"amount_reversed"` + BalanceTransaction *BalanceTransaction `json:"balance_transaction"` + Created int64 `json:"created"` + Currency Currency `json:"currency"` + Description string `json:"description"` + Destination *TransferDestination `json:"destination"` + DestinationPayment *Charge `json:"destination_payment"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Metadata map[string]string `json:"metadata"` + Reversals *ReversalList `json:"reversals"` + Reversed bool `json:"reversed"` + SourceTransaction *BalanceTransactionSource `json:"source_transaction"` + SourceType TransferSourceType `json:"source_type"` + TransferGroup string `json:"transfer_group"` +} + +// TransferList is a list of transfers as retrieved from a list endpoint. +type TransferList struct { + ListMeta + Data []*Transfer `json:"data"` +} + +// UnmarshalJSON handles deserialization of a Transfer. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (t *Transfer) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + t.ID = id + return nil + } + + type transfer Transfer + var v transfer + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *t = Transfer(v) + return nil +} + +// UnmarshalJSON handles deserialization of a TransferDestination. +// This custom unmarshaling is needed because the specific +// type of destination it refers to is specified in the JSON +func (d *TransferDestination) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + d.ID = id + return nil + } + + type transferDestination TransferDestination + var v transferDestination + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *d = TransferDestination(v) + return json.Unmarshal(data, &d.Account) +} diff --git a/vendor/github.com/stripe/stripe-go/usagerecord.go b/vendor/github.com/stripe/stripe-go/usagerecord.go new file mode 100644 index 0000000..69b5f0b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/usagerecord.go @@ -0,0 +1,27 @@ +package stripe + +// Possible values for the action parameter on usage record creation. +const ( + UsageRecordActionIncrement string = "increment" + UsageRecordActionSet string = "set" +) + +// UsageRecord represents a usage record. +// See https://stripe.com/docs/api#usage_records +type UsageRecord struct { + ID string `json:"id"` + Livemode bool `json:"livemode"` + Quantity int64 `json:"quantity"` + SubscriptionItem string `json:"subscription_item"` + Timestamp int64 `json:"timestamp"` +} + +// UsageRecordParams create a usage record for a specified subscription item +// and date, and fills it with a quantity. +type UsageRecordParams struct { + Params `form:"*"` + Action *string `form:"action"` + Quantity *int64 `form:"quantity"` + SubscriptionItem *string `form:"-"` // passed in the URL + Timestamp *int64 `form:"timestamp"` +} diff --git a/vendor/github.com/stripe/stripe-go/usagerecordsummary.go b/vendor/github.com/stripe/stripe-go/usagerecordsummary.go new file mode 100644 index 0000000..51afd5e --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/usagerecordsummary.go @@ -0,0 +1,25 @@ +package stripe + +// UsageRecordSummary represents a usage record summary. +// See https://stripe.com/docs/api#usage_records +type UsageRecordSummary struct { + ID string `json:"id"` + Invoice string `json:"invoice"` + Livemode bool `json:"livemode"` + Object string `json:"object"` + Period *Period `json:"period"` + SubscriptionItem string `json:"subscription_item"` + TotalUsage int64 `json:"total_usage"` +} + +// UsageRecordSummaryListParams is the set of parameters that can be used when listing charges. +type UsageRecordSummaryListParams struct { + ListParams `form:"*"` + SubscriptionItem *string `form:"-"` // Sent in with the URL +} + +// UsageRecordSummaryList is a list of usage record summaries as retrieved from a list endpoint. +type UsageRecordSummaryList struct { + ListMeta + Data []*UsageRecordSummary `json:"data"` +} diff --git a/vendor/github.com/stripe/stripe-go/v32_migration_guide.md b/vendor/github.com/stripe/stripe-go/v32_migration_guide.md new file mode 100644 index 0000000..7f09d20 --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/v32_migration_guide.md @@ -0,0 +1,146 @@ +# V32 Migration Guide + +Version 32 of stripe-go contains some very sizable breaking changes. + +The major reason that we moved forward on them is that it was previously +impossible when encoding a parameter struct for an API call to make a +distinction between a field that a user had left unset versus a field that had +been set explicitly, but to an empty value. So if we had a parameter struct +like this: + +``` go +type UsageRecordParams struct { + Quantity uint64 `form:"quantity"` +} +``` + +We were unable to differentiate these two cases: + +``` go +// Initialized with no quantity +UsageRecord {} + +// Initialized with an explicitly zero +UsageRecord { + Quantity: 0, +} +``` + +This is because any uninitialized fields on a struct in Go are set to their +type's "zero value", which for an integer is `0`. + +Working around the problem required a secondary field to help explicitly state +that the zero value was intended, which was quite unintuitive for users: + +``` go +type UsageRecordParams struct { + Quantity uint64 `form:"quantity"` + QuantityZero bool `form:"quantity,zero"` +} + +UsageRecord { + QuantityZero: true, +} +``` + +To address the problem, we moved every parameter struct over to use pointers +instead. So the above becomes: + +``` go +type UsageRecordParams struct { + Quantity *int64 `form:"quantity"` +} +``` + +Because in Go you can't take the address of an inline value (`&0`), we provide +a set of helper functions like `stripe.Int64` specifically for initializing +these structs: + +``` go +UsageRecord { + Quantity: stripe.Int64(0), +} +``` + +The zero value for pointers is `nil`, so we can now easily determine which +values on a struct were never set, and which ones were explicitly set to a zero +value, thus eliminating the need for the secondary fields like `QuantityZero`. + +Because this is a large change, we also took the opportunity to do some +housekeeping throughout the library. Most of this involves renaming fields and +some resources to be more accurate according to how they're named in Stripe's +REST API, but it also involves some smaller changes like moving some types and +constants around. + +Please see the list below for the complete set of changes. + +## Major changes + +* All fields on parameter structs (those that end with `*Params`) are now + pointers. Please use the new helper functions to set them: + * `stripe.Bool` + * `stripe.Float64` + * `stripe.Int64` + * `stripe.String` + + This also means that extra fields that used to be solely used for tracking + meaningful zero values like `CouponEmpty` and `QuantityZero` have been + dropped. Use their corresponding field (e.g., `Coupon`, `Quantity`) with an + explicit empty value instead (`stripe.String("")`, `stripe.Int64(0)`). +* Many fields have been renamed so that they're more consistent with their name + in Stripe's REST API. Most of the time, this changes abbreviations to a more + fully expanded form. For example: + * `Desc` becomes `Description`. + * `Live` becomes `Livemode`. +* A few names of API resources (and their corresponding parameter and list + classes) have changed: + * `Fee` becomes `ApplicationFee`. + * `FeeRefund` becomes `ApplicationFeeRefund`. + * `Owner` becomes `AdditionalOwner`. + * `Sub` becomes `Subscription`. + * `SubItem` becomes `SubscriptionItem`. + * `Transaction` becomes `BalanceTransaction`. + * `TxFee` becomes `BalanceTransactionFee`. +* Some sets of constants have been renamed and migrated to the top-level + `stripe` package. All constants now have a prefix according to what they + describe (for example, card brands all start with `CardBrand*` like + `CardBrandVisa`) and all now reside in the `stripe` package (for example + `dispute.Duplicate` is now `stripe.DisputeReasonDuplicate`). +* Some structs that used to be shared between requests and responses are now + broken apart. All API calls should be using only structs that end with a + `*Params` suffix. So for example, if you were using `Address` or `DOB` + before, you should now use `AddressParams` and `DOBParams`. + +## Other changes + +* All integer values now use `int64` as their type. This means that the + `stripe.Int64` helper function is appropriate for setting all integer values. + This usually doesn't require a change because just setting these fields to a + numerical literal didn't require that the type be explicitly stated. +* `Event.GetObjValue` becomes `Event.GetObjectValue` +* `Params.AddMeta` becomes `Params.AddMetadata` +* `Params.End` and `ListParams.End` become `EndingBefore`, and become a pointer + (use `stripe.String` to set them as with other parameters). +* `Params.Expand` and `ListParams.Expand` (the fields) becomes a slice of + pointers (instead of a slice of strings). +* `Params.Expand` and `ListParams.Expand` (the functions) become `AddExpand`. +* `Params.IdempotencyKey` becomes a pointer. +* `Params.Limit` becomes a pointer. +* `Params.Meta` becomes `Params.Metadata` +* `Params.Start` and `ListParams.Start` become `StartingAfter` +* `Params.StripeAccount` and `ListParams.StripeAccount` become pointers. +* List object data is now accessed with `object.Data` instead of `object.List`. + Nothing changes if you were using iterators and `Next`. +* The previously deprecated `FileUploadParams.File` has been removed. Please + use `FileUploadParams.FileReader` instead. +* The previously deprecated `Params.Account` has been removed. Please use + `Params.StripeAccount` instead. + +As usual, if you find bugs, please [open them on the repository][issues], or +reach out to `support@stripe.com` if you have any other questions. + +[issues]: https://github.com/stripe/stripe-go/issues/new + + diff --git a/vendor/github.com/stripe/stripe-go/webhookendpoint.go b/vendor/github.com/stripe/stripe-go/webhookendpoint.go new file mode 100644 index 0000000..f1b6b6b --- /dev/null +++ b/vendor/github.com/stripe/stripe-go/webhookendpoint.go @@ -0,0 +1,67 @@ +package stripe + +import "encoding/json" + +// WebhookEndpointParams is the set of parameters that can be used when creating a webhook endpoint. +// For more details see https://stripe.com/docs/api#create_webhook_endpoint. +type WebhookEndpointParams struct { + Params `form:"*"` + Connect *bool `form:"connect"` + Disabled *bool `form:"disabled"` + EnabledEvents []*string `form:"enabled_events"` + URL *string `form:"url"` + + // This parameter is only available on creation. + // We recommend setting the API version that the library is pinned to. See apiversion in stripe.go + APIVersion *string `form:"api_version"` +} + +// WebhookEndpointListParams is the set of parameters that can be used when listing webhook endpoints. +// For more detail see https://stripe.com/docs/api#list_webhook_endpoints. +type WebhookEndpointListParams struct { + ListParams `form:"*"` + Created *int64 `form:"created"` + CreatedRange *RangeQueryParams `form:"created"` +} + +// WebhookEndpoint is the resource representing a Stripe webhook endpoint. +// For more details see https://stripe.com/docs/api#webhook_endpoints. +type WebhookEndpoint struct { + APIVersion string `json:"api_version"` + Application string `json:"application"` + Connect bool `json:"connect"` + Created int64 `json:"created"` + Deleted bool `json:"deleted"` + EnabledEvents []string `json:"enabled_events"` + ID string `json:"id"` + Livemode bool `json:"livemode"` + Object string `json:"object"` + Secret string `json:"secret"` + Status string `json:"status"` + URL string `json:"url"` +} + +// WebhookEndpointList is a list of webhook endpoints as retrieved from a list endpoint. +type WebhookEndpointList struct { + ListMeta + Data []*WebhookEndpoint `json:"data"` +} + +// UnmarshalJSON handles deserialization of a WebhookEndpoint. +// This custom unmarshaling is needed because the resulting +// property may be an id or the full struct if it was expanded. +func (c *WebhookEndpoint) UnmarshalJSON(data []byte) error { + if id, ok := ParseID(data); ok { + c.ID = id + return nil + } + + type endpoint WebhookEndpoint + var v endpoint + if err := json.Unmarshal(data, &v); err != nil { + return err + } + + *c = WebhookEndpoint(v) + return nil +} diff --git a/vendor/modules.txt b/vendor/modules.txt new file mode 100644 index 0000000..dcb31ec --- /dev/null +++ b/vendor/modules.txt @@ -0,0 +1,17 @@ +# github.com/joho/godotenv v1.3.0 +## explicit +github.com/joho/godotenv +# github.com/lib/pq v1.3.0 +## explicit +github.com/lib/pq +github.com/lib/pq/oid +github.com/lib/pq/scram +# github.com/stretchr/testify v1.5.1 +## explicit +# github.com/stripe/stripe-go v70.5.0+incompatible +## explicit +github.com/stripe/stripe-go +github.com/stripe/stripe-go/form +github.com/stripe/stripe-go/paymentintent +# golang.org/x/net v0.0.0-20200301022130-244492dfa37a +## explicit