From 8dbf717bbad8b1ff822bf00b2eff6ab1682e639e Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Wed, 6 Mar 2019 14:03:09 -0500 Subject: [PATCH 01/14] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index aa3c828..228a90c 100644 --- a/README.md +++ b/README.md @@ -25,12 +25,12 @@ And you are all set. Interacting with the API is quite easy from any route handl ~~~~swift struct ChargeToken: Content { - var token: String + var stripeToken: String } func chargeCustomer(_ req: Request) throws -> EventLoopFuture { return try req.content.decode(ChargeToken.self).flatMap { charge in - return try req.make(StripeClient.self).charge.create(amount: 2500, currency: .usd, source: charge.token).map { stripeCharge in + return try req.make(StripeClient.self).charge.create(amount: 2500, currency: .usd, source: charge.stripeToken).map { stripeCharge in if stripeCharge.status == .success { return .ok } else { From 35ab15acc2ec3202ddbfb5d66afa782d110d7fc1 Mon Sep 17 00:00:00 2001 From: Bram Huenaerts Date: Wed, 6 Mar 2019 20:05:41 +0100 Subject: [PATCH 02/14] improved easy copy paste sample approach --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 228a90c..a66e12b 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,10 @@ func chargeCustomer(_ req: Request) throws -> EventLoopFuture { And you can always check the documentation to see the required paramaters for specific API calls. +## JS Stripe integration + +Also make sure to check out stripes documenation to add the client JS magic on https://stripe.com/docs/checkout#integration-simple or https://stripe.com/docs/checkout#integration-custom + ## Whats Implemented ### Core Resources From cdeb0c84a28c1c0cb817f7fc652ea93d2aafd193 Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Wed, 6 Mar 2019 14:07:24 -0500 Subject: [PATCH 03/14] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a66e12b..e40c93d 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ And you can always check the documentation to see the required paramaters for sp ## JS Stripe integration -Also make sure to check out stripes documenation to add the client JS magic on https://stripe.com/docs/checkout#integration-simple or https://stripe.com/docs/checkout#integration-custom +Also make sure to check out stripes documenation to add the client JS magic [here]( https://stripe.com/docs/checkout#integration-simple) or [here](https://stripe.com/docs/checkout#integration-custom) ## Whats Implemented From 670ace974b33b3bfb2063ca6d62d521e3fc22a89 Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Wed, 6 Mar 2019 14:07:43 -0500 Subject: [PATCH 04/14] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e40c93d..09bd4c3 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ And you can always check the documentation to see the required paramaters for sp ## JS Stripe integration -Also make sure to check out stripes documenation to add the client JS magic [here]( https://stripe.com/docs/checkout#integration-simple) or [here](https://stripe.com/docs/checkout#integration-custom) +Also make sure to check out stripes documenation to add the client JS magic [here]( https://stripe.com/docs/checkout#integration-simple) or [here](https://stripe.com/docs/checkout#integration-custom) ## Whats Implemented From 74635b1bd674134bcea31568f035e0f65b789054 Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Sun, 17 Mar 2019 18:06:18 -0400 Subject: [PATCH 05/14] Implemented ApplicationFee and ApplicationFeeRefunds. --- Package.swift | 2 +- README.md | 4 +- Sources/Stripe/API/Helpers/Endpoints.swift | 14 ++- .../Routes/ApplicationFeeRefundRoutes.swift | 116 ++++++++++++++++++ .../API/Routes/ApplicationFeesRoutes.swift | 54 ++++++++ Sources/Stripe/API/Routes/PersonRoutes.swift | 4 +- .../Models/Connect/ApplicationFee.swift | 72 +++++++++++ .../Models/Connect/ApplicationFeeRefund.swift | 54 ++++++++ Sources/Stripe/Provider/Provider.swift | 4 + Tests/StripeTests/ApplicationFeeTests.swift | 111 +++++++++++++++++ Tests/StripeTests/XCTestManifests.swift | 8 ++ 11 files changed, 437 insertions(+), 6 deletions(-) create mode 100644 Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift create mode 100644 Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift create mode 100644 Sources/Stripe/Models/Connect/ApplicationFee.swift create mode 100644 Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift create mode 100644 Tests/StripeTests/ApplicationFeeTests.swift diff --git a/Package.swift b/Package.swift index 7db9950..7753c3a 100644 --- a/Package.swift +++ b/Package.swift @@ -7,7 +7,7 @@ let package = Package( .library(name: "Stripe", targets: ["Stripe"]) ], dependencies: [ - .package(url: "https://github.com/vapor/vapor.git", from: "3.2.2"), + .package(url: "https://github.com/vapor/vapor.git", from: "3.3.0"), ], targets: [ .target(name: "Stripe", dependencies: ["Vapor"]), diff --git a/README.md b/README.md index 09bd4c3..602bc76 100644 --- a/README.md +++ b/README.md @@ -85,8 +85,8 @@ Also make sure to check out stripes documenation to add the client JS magic [her --- ### Connect * [x] Account -* [ ] Application Fee Refunds -* [ ] Application Fees +* [x] Application Fee Refunds +* [x] Application Fees * [ ] Country Specs * [ ] External Accounts * [x] Persons diff --git a/Sources/Stripe/API/Helpers/Endpoints.swift b/Sources/Stripe/API/Helpers/Endpoints.swift index 97d039b..52b9589 100644 --- a/Sources/Stripe/API/Helpers/Endpoints.swift +++ b/Sources/Stripe/API/Helpers/Endpoints.swift @@ -127,6 +127,12 @@ internal enum StripeAPIEndpoint { case person(String) case persons(String, String) + case applicationFee + case applicationFees(String) + + case applicationFeeRefund(String) + case applicationFeeRefunds(String, String) + var endpoint: String { switch self { case .balance: return APIBase + APIVersion + "balance" @@ -216,7 +222,13 @@ internal enum StripeAPIEndpoint { case .files(let id): return FilesAPIBase + APIVersion + "files/\(id)" case .person(let account): return APIBase + APIVersion + "accounts/\(account)/persons" - case .persons(let account, let person): return APIBase + APIVersion + "accounts/\(account)/persons\(person)" + case .persons(let account, let person): return APIBase + APIVersion + "accounts/\(account)/persons/\(person)" + + case .applicationFee: return APIBase + APIVersion + "application_fees" + case .applicationFees(let fee): return APIBase + APIVersion + "application_fees/\(fee)" + + case .applicationFeeRefund(let fee): return APIBase + APIVersion + "application_fees/\(fee)/refunds" + case .applicationFeeRefunds(let fee, let refund): return APIBase + APIVersion + "application_fees/\(fee)/refunds/\(refund)" } } } diff --git a/Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift b/Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift new file mode 100644 index 0000000..e241976 --- /dev/null +++ b/Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift @@ -0,0 +1,116 @@ +// +// ApplicationFeeRefundRoutes.swift +// Stripe +// +// Created by Andrew Edwards on 3/17/19. +// + +import Vapor + +public protocol ApplicationFeeRefundRoutes { + /// Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account from which the fee was originally collected. + /// You can optionally refund only part of an application fee. You can do so multiple times, until the entire fee has been refunded. + /// Once entirely refunded, an application fee can’t be refunded again. This method will return an error when called on an already-refunded application fee, or when trying to refund more money than is left on an application fee. + /// + /// - Parameters: + /// - fee: The identifier of the application fee to be refunded. + /// - amount: A positive integer, in `cents`, representing how much of this fee to refund. Can refund only up to the remaining unrefunded amount of the fee. + /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + /// - Returns: A `StripeApplicationFeeRefund`. + /// - Throws: A `StripeError`. + func create(fee: String, amount: Int?, metadata: [String: String]?) throws -> EventLoopFuture + + + /// By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee. + /// + /// - Parameters: + /// - refund: ID of refund to retrieve. + /// - fee: ID of the application fee refunded. + /// - Returns: A `StripeApplicationFeeRefund`. + /// - Throws: A `StripeError`. + func retrieve(refund: String, fee: String) throws -> EventLoopFuture + + + /// Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + /// This request only accepts metadata as an argument. + /// + /// - Parameters: + /// - refund: ID of refund to retrieve. + /// - fee: ID of the application fee refunded. + /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. + /// - Returns: A `StripeApplicationFeeRefund`. + /// - Throws: A `StripeError`. + func update(refund: String, fee: String, metadata: [String: String]?) throws -> EventLoopFuture + + + /// You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional refunds. + /// + /// - Parameters: + /// - fee: The ID of the application fee whose refunds will be retrieved. + /// - filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/fee_refunds/list) + /// - Returns: A `StripeApplicationFeeRefundList`. + /// - Throws: A `StripeError`. + func listAll(fee: String, filter: [String: Any]?) throws -> EventLoopFuture +} + +extension ApplicationFeeRefundRoutes { + public func create(fee: String, amount: Int? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { + return try create(fee: fee, amount: amount, metadata: metadata) + } + + public func retrieve(refund: String, fee: String) throws -> EventLoopFuture { + return try retrieve(refund: refund, fee: fee) + } + + public func update(refund: String, fee: String, metadata: [String: String]? = nil) throws -> EventLoopFuture { + return try update(refund: refund, fee: fee, metadata: metadata) + } + + public func listAll(fee: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { + return try listAll(fee: fee, filter: filter) + } +} + +public struct StripeApplicationFeeRefundRoutes: ApplicationFeeRefundRoutes { + private let request: StripeRequest + + init(request: StripeRequest) { + self.request = request + } + + public func create(fee: String, amount: Int?, metadata: [String: String]?) throws -> EventLoopFuture { + var body: [String: Any] = [:] + + if let amount = amount { + body["amount"] = amount + } + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.applicationFeeRefund(fee).endpoint, body: body.queryParameters) + } + + public func retrieve(refund: String, fee: String) throws -> EventLoopFuture { + return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFeeRefunds(fee, refund).endpoint) + } + + public func update(refund: String, fee: String, metadata: [String: String]?) throws -> EventLoopFuture { + var body: [String: Any] = [:] + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.applicationFeeRefunds(fee, refund).endpoint, body: body.queryParameters) + } + + public func listAll(fee: String, filter: [String: Any]?) throws -> EventLoopFuture { + var queryParams = "" + if let filter = filter { + queryParams = filter.queryParameters + } + return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFeeRefund(fee).endpoint, query: queryParams) + } +} diff --git a/Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift b/Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift new file mode 100644 index 0000000..fa00023 --- /dev/null +++ b/Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift @@ -0,0 +1,54 @@ +// +// ApplicationFeesRoutes.swift +// Stripe +// +// Created by Andrew Edwards on 3/17/19. +// + +import Vapor + +public protocol ApplicationFeesRoutes { + /// Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee. + /// + /// - Parameter fee: The identifier of the fee to be retrieved. + /// - Returns: A `StripeApplicationFee`. + /// - Throws: A `StripeError`. + func retrieve(fee: String) throws -> EventLoopFuture + + /// Returns a list of application fees you’ve previously collected. The application fees are returned in sorted order, with the most recent fees appearing first. + /// + /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/application_fees/list?lang=curl) + /// - Returns: A `StripeApplicationFeeList`. + /// - Throws: A `StripeError`. + func listAll(filter: [String: Any]?) throws -> EventLoopFuture +} + +extension ApplicationFeesRoutes { + public func retrieve(fee: String) throws -> EventLoopFuture { + return try retrieve(fee: fee) + } + + public func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture { + return try listAll(filter: filter) + } +} + +public struct StripeApplicationFeeRoutes: ApplicationFeesRoutes { + private let request: StripeRequest + + init(request: StripeRequest) { + self.request = request + } + + public func retrieve(fee: String) throws -> EventLoopFuture { + return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFees(fee).endpoint) + } + + public func listAll(filter: [String: Any]?) throws -> EventLoopFuture { + var queryParams = "" + if let filter = filter { + queryParams = filter.queryParameters + } + return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFee.endpoint, query: queryParams) + } +} diff --git a/Sources/Stripe/API/Routes/PersonRoutes.swift b/Sources/Stripe/API/Routes/PersonRoutes.swift index a131620..d586f30 100644 --- a/Sources/Stripe/API/Routes/PersonRoutes.swift +++ b/Sources/Stripe/API/Routes/PersonRoutes.swift @@ -173,11 +173,11 @@ extension PersonRoutes { verification: verification) } - func delete(account: String, person: String) throws -> EventLoopFuture { + public func delete(account: String, person: String) throws -> EventLoopFuture { return try delete(account: account, person: person) } - func listAll(account: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { + public func listAll(account: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { return try listAll(account: account, filter: filter) } } diff --git a/Sources/Stripe/Models/Connect/ApplicationFee.swift b/Sources/Stripe/Models/Connect/ApplicationFee.swift new file mode 100644 index 0000000..23e5495 --- /dev/null +++ b/Sources/Stripe/Models/Connect/ApplicationFee.swift @@ -0,0 +1,72 @@ +// +// ApplicationFee.swift +// Stripe +// +// Created by Andrew Edwards on 3/16/19. +// + +import Vapor +/// When you collect a transaction fee on top of a charge made for your user (using [Connect](https://stripe.com/docs/connect) ), an `Application Fee` object is created in your account. You can list, retrieve, and refund application fees. For details, see [Collecting application fees](https://stripe.com/docs/connect/direct-charges#collecting-fees). [Learn More →](https://stripe.com/docs/api/application_fees) +public struct StripeApplicationFee: StripeModel { + /// Unique identifier for the object. + public var id: String + /// String representing the object’s type. Objects of the same type share the same value. + public var object: String + /// ID of the Stripe account this fee was taken from. + public var account: String? + /// Amount earned, in cents. + public var amount: Int? + /// Amount in cents refunded (can be less than the amount attribute on the fee if a partial refund was issued) + public var amountRefunded: Int? + /// ID of the Connect application that earned the fee. + public var application: String? + /// Balance transaction that describes the impact of this collected application fee on your account balance (not including refunds). + public var balanceTransaction: String? + /// ID of the charge that the application fee was taken from. + public var charge: String? + /// Time at which the object was created. Measured in seconds since the Unix epoch. + public var created: Date? + /// Three-letter ISO currency code, in lowercase. Must be a supported currency. + public var currency: StripeCurrency? + /// Has the value true if the object exists in live mode or the value false if the object exists in test mode. + public var livemode: Bool? + /// ID of the corresponding charge on the platform account, if this fee was the result of a charge using the destination parameter. + public var originatingTransaction: String? + /// Whether the fee has been fully refunded. If the fee is only partially refunded, this attribute will still be false. + public var refunded: Bool? + /// A list of refunds that have been applied to the fee. + public var refunds: StripeApplicationFeeRefundList? + + private enum CodingKeys: String, CodingKey { + case id + case object + case account + case amount + case amountRefunded = "amount_refunded" + case application + case balanceTransaction = "balance_transaction" + case charge + case created + case currency + case livemode + case originatingTransaction = "originating_transaction" + case refunded + case refunds + } +} + +public struct StripeApplicationFeeList: StripeModel { + public var object: String + public var hasMore: Bool + public var totalCount: Int? + public var url: String? + public var data: [StripeApplicationFee]? + + private enum CodingKeys: String, CodingKey { + case object + case hasMore = "has_more" + case totalCount = "total_count" + case url + case data + } +} diff --git a/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift b/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift new file mode 100644 index 0000000..ebb7fb4 --- /dev/null +++ b/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift @@ -0,0 +1,54 @@ +// +// ApplicationFeeRefund.swift +// Stripe +// +// Created by Andrew Edwards on 3/17/19. +// + +import Vapor +/// `Application Fee Refund` objects allow you to refund an application fee that has previously been created but not yet refunded. Funds will be refunded to the Stripe account from which the fee was originally collected. +public struct StripeApplicationFeeRefund: StripeModel { + /// Unique identifier for the object. + public var id: String + /// String representing the object’s type. Objects of the same type share the same value. + public var object: String + /// Amount, in cents. + public var amount: Int? + /// Balance transaction that describes the impact on your account balance. + public var balanceTransaction: String? + /// Time at which the object was created. Measured in seconds since the Unix epoch. + public var created: Date? + /// Three-letter ISO currency code, in lowercase. Must be a supported currency. + public var currency: StripeCurrency? + /// ID of the application fee that was refunded. + public var fee: String? + /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + public var metadata: [String: String]? + + private enum CodingKeys: String, CodingKey { + case id + case object + case amount + case balanceTransaction = "balance_transaction" + case created + case currency + case fee + case metadata + } +} + +public struct StripeApplicationFeeRefundList: StripeModel { + public var object: String + public var hasMore: Bool + public var totalCount: Int? + public var url: String? + public var data: [StripeApplicationFeeRefund]? + + private enum CodingKeys: String, CodingKey { + case object + case hasMore = "has_more" + case totalCount = "total_count" + case url + case data + } +} diff --git a/Sources/Stripe/Provider/Provider.swift b/Sources/Stripe/Provider/Provider.swift index cc2afa9..5335fdf 100644 --- a/Sources/Stripe/Provider/Provider.swift +++ b/Sources/Stripe/Provider/Provider.swift @@ -69,6 +69,8 @@ public final class StripeClient: Service { public var fileLinks: FileLinkRoutes public var files: FileRoutes public var person: PersonRoutes + public var applicationFee: ApplicationFeesRoutes + public var applicationFeeRefunds: ApplicationFeeRefundRoutes internal init(apiKey: String, testKey: String?, client: Client) { let apiRequest = StripeAPIRequest(httpClient: client, apiKey: apiKey, testApiKey: testKey) @@ -98,5 +100,7 @@ public final class StripeClient: Service { fileLinks = StripeFileLinkRoutes(request: apiRequest) files = StripeFileRoutes(request: apiRequest) person = StripePersonRoutes(request: apiRequest) + applicationFee = StripeApplicationFeeRoutes(request: apiRequest) + applicationFeeRefunds = StripeApplicationFeeRefundRoutes(request: apiRequest) } } diff --git a/Tests/StripeTests/ApplicationFeeTests.swift b/Tests/StripeTests/ApplicationFeeTests.swift new file mode 100644 index 0000000..10fbcee --- /dev/null +++ b/Tests/StripeTests/ApplicationFeeTests.swift @@ -0,0 +1,111 @@ +// +// ApplicationFeeTests.swift +// StripeTests +// +// Created by Andrew Edwards on 3/17/19. +// + +import XCTest +@testable import Stripe +@testable import Vapor + +class ApplicationFeeTests: XCTestCase { + let applicationFeeRefundString = """ +{ + "id": "fr_1EEtTKKbnvuxQXGuFmk1SX9S", + "object": "fee_refund", + "amount": 100, + "balance_transaction": "bt_1234", + "created": 1552807914, + "currency": "usd", + "fee": "fee_1B73DOKbnvuxQXGuhY8Aw0TN", + "metadata": {} +} +""" + + let applicationfeeString = """ +{ + "id": "fee_1B73DOKbnvuxQXGuhY8Aw0TN", + "object": "application_fee", + "account": "acct_164wxjKbnvuxQXGu", + "amount": 105, + "amount_refunded": 105, + "application": "ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7", + "balance_transaction": "txn_19XJJ02eZvKYlo2ClwuJ1rbA", + "charge": "ch_1B73DOKbnvuxQXGurbwPqzsu", + "created": 1506609734, + "currency": "gbp", + "livemode": false, + "originating_transaction": null, + "refunded": true, + "refunds": { + "object": "list", + "data": [ + { + "id": "fr_D0s7fGBKB40Twy", + "object": "fee_refund", + "amount": 138, + "balance_transaction": "txn_1CaqNg2eZvKYlo2C75cA3Euk", + "created": 1528486576, + "currency": "usd", + "fee": "fee_1B73DOKbnvuxQXGuhY8Aw0TN", + "metadata": {} + } + ], + "has_more": false, + "total_count": 1, + "url": "/v1/application_fees/fee_1B73DOKbnvuxQXGuhY8Aw0TN/refunds" + } +} +""" + + + func testApplicationFeeRefundParsesProperly() throws { + do { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + let body = HTTPBody(string: applicationFeeRefundString) + var headers: HTTPHeaders = [:] + headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) + let request = HTTPRequest(headers: headers, body: body) + let refund = try decoder.decode(StripeApplicationFeeRefund.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() + + XCTAssertEqual(refund.id, "fr_1EEtTKKbnvuxQXGuFmk1SX9S") + XCTAssertEqual(refund.object, "fee_refund") + XCTAssertEqual(refund.amount, 100) + XCTAssertEqual(refund.balanceTransaction, "bt_1234") + XCTAssertEqual(refund.created, Date(timeIntervalSince1970: 1552807914)) + XCTAssertEqual(refund.currency, .usd) + XCTAssertEqual(refund.fee, "fee_1B73DOKbnvuxQXGuhY8Aw0TN") + XCTAssertEqual(refund.metadata, [:]) + } catch { + XCTFail("\(error)") + } + } + + func testApplicationFeeParsesProperly() throws { + do { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + let body = HTTPBody(string: applicationfeeString) + var headers: HTTPHeaders = [:] + headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) + let request = HTTPRequest(headers: headers, body: body) + let fee = try decoder.decode(StripeApplicationFee.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() + + XCTAssertEqual(fee.id, "fee_1B73DOKbnvuxQXGuhY8Aw0TN") + XCTAssertEqual(fee.object, "application_fee") + XCTAssertEqual(fee.balanceTransaction, "txn_19XJJ02eZvKYlo2ClwuJ1rbA") + XCTAssertEqual(fee.amount, 105) + XCTAssertEqual(fee.amountRefunded, 105) + XCTAssertEqual(fee.created, Date(timeIntervalSince1970: 1506609734)) + XCTAssertEqual(fee.currency, .gbp) + XCTAssertEqual(fee.refunded, true) + XCTAssertNotNil(fee.refunds?.data) + } catch { + XCTFail("\(error)") + } + } +} diff --git a/Tests/StripeTests/XCTestManifests.swift b/Tests/StripeTests/XCTestManifests.swift index a11e97a..d25c25d 100644 --- a/Tests/StripeTests/XCTestManifests.swift +++ b/Tests/StripeTests/XCTestManifests.swift @@ -6,6 +6,13 @@ extension AccountTests { ] } +extension ApplicationFeeTests { + static let __allTests = [ + ("testApplicationFeeParsesProperly", testApplicationFeeParsesProperly), + ("testApplicationFeeRefundParsesProperly", testApplicationFeeRefundParsesProperly), + ] +} + extension BalanceTests { static let __allTests = [ ("testBalanceParsedProperly", testBalanceParsedProperly), @@ -139,6 +146,7 @@ extension TransferTests { public func __allTests() -> [XCTestCaseEntry] { return [ testCase(AccountTests.__allTests), + testCase(ApplicationFeeTests.__allTests), testCase(BalanceTests.__allTests), testCase(ChargeTests.__allTests), testCase(CustomerTests.__allTests), From bb868be9d3324160a7a3a1475978d2053331dbbb Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Sat, 23 Mar 2019 05:35:57 -0400 Subject: [PATCH 06/14] Implemented external accounts. Minor clean up. --- README.md | 2 +- Sources/Stripe/API/Helpers/Endpoints.swift | 6 + Sources/Stripe/API/Routes/AccountRoutes.swift | 6 +- .../API/Routes/ExternalAccountsRoutes.swift | 383 ++++++++++++++++++ Sources/Stripe/Helpers/FundingType.swift | 14 - Sources/Stripe/Models/Connect/Account.swift | 16 +- .../Stripe/Models/Connect/AccountList.swift | 28 -- .../Models/Connect/ApplicationFee.swift | 2 - .../Models/Connect/ApplicationFeeRefund.swift | 2 - .../Models/Connect/ExternalAccounts.swift | 32 +- .../Models/Connect/ExternalBankAccount.swift | 28 -- .../Models/Connect/ExternalCardAccount.swift | 43 -- .../Stripe/Models/Sources/BankAccount.swift | 50 ++- Sources/Stripe/Models/Sources/Card.swift | 101 ++++- .../Models/Sources/CardValidationCheck.swift | 14 - .../Stripe/Models/Sources/OtherSources.swift | 2 +- .../Models/Sources/TokenizedMethod.swift | 14 - Sources/Stripe/Provider/Provider.swift | 2 + Tests/StripeTests/AccountTests.swift | 2 - Tests/StripeTests/TokenTests.swift | 6 +- 20 files changed, 557 insertions(+), 196 deletions(-) create mode 100644 Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift delete mode 100644 Sources/Stripe/Helpers/FundingType.swift delete mode 100644 Sources/Stripe/Models/Connect/AccountList.swift delete mode 100644 Sources/Stripe/Models/Connect/ExternalBankAccount.swift delete mode 100644 Sources/Stripe/Models/Connect/ExternalCardAccount.swift delete mode 100644 Sources/Stripe/Models/Sources/CardValidationCheck.swift delete mode 100644 Sources/Stripe/Models/Sources/TokenizedMethod.swift diff --git a/README.md b/README.md index 602bc76..58b5cd9 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ Also make sure to check out stripes documenation to add the client JS magic [her * [x] Application Fee Refunds * [x] Application Fees * [ ] Country Specs -* [ ] External Accounts +* [x] External Accounts * [x] Persons * [ ] Top-ups * [x] Transfers diff --git a/Sources/Stripe/API/Helpers/Endpoints.swift b/Sources/Stripe/API/Helpers/Endpoints.swift index 52b9589..4ee2cbf 100644 --- a/Sources/Stripe/API/Helpers/Endpoints.swift +++ b/Sources/Stripe/API/Helpers/Endpoints.swift @@ -133,6 +133,9 @@ internal enum StripeAPIEndpoint { case applicationFeeRefund(String) case applicationFeeRefunds(String, String) + case externalAccount(String) + case externalAccounts(String, String) + var endpoint: String { switch self { case .balance: return APIBase + APIVersion + "balance" @@ -229,6 +232,9 @@ internal enum StripeAPIEndpoint { case .applicationFeeRefund(let fee): return APIBase + APIVersion + "application_fees/\(fee)/refunds" case .applicationFeeRefunds(let fee, let refund): return APIBase + APIVersion + "application_fees/\(fee)/refunds/\(refund)" + + case . externalAccount(let account): return APIBase + APIVersion + "accounts/\(account)/external_accounts" + case . externalAccounts(let account, let id): return APIBase + APIVersion + "accounts/\(account)/external_accounts/\(id)" } } } diff --git a/Sources/Stripe/API/Routes/AccountRoutes.swift b/Sources/Stripe/API/Routes/AccountRoutes.swift index bf51919..8f47f22 100644 --- a/Sources/Stripe/API/Routes/AccountRoutes.swift +++ b/Sources/Stripe/API/Routes/AccountRoutes.swift @@ -39,7 +39,7 @@ public protocol AccountRoutes { tosAcceptance: [String: Any]?) throws -> Future func delete(account: String) throws -> Future func reject(account: String, for: AccountRejectReason) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future + func listAll(filter: [String: Any]?) throws -> Future func createLoginLink(for: String) throws -> Future } @@ -114,7 +114,7 @@ extension AccountRoutes { return try reject(account: account, for: `for`) } - public func listAll(filter: [String: Any]? = nil) throws -> Future { + public func listAll(filter: [String: Any]? = nil) throws -> Future { return try listAll(filter: filter) } @@ -297,7 +297,7 @@ public struct StripeConnectAccountRoutes: AccountRoutes { /// List all connected accounts /// [Learn More →](https://stripe.com/docs/api/curl#list_accounts) - public func listAll(filter: [String: Any]?) throws -> Future { + public func listAll(filter: [String: Any]?) throws -> Future { var queryParams = "" if let filter = filter { queryParams = filter.queryParameters diff --git a/Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift b/Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift new file mode 100644 index 0000000..d338941 --- /dev/null +++ b/Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift @@ -0,0 +1,383 @@ +// +// ExternalAccountsRoutes.swift +// Stripe +// +// Created by Andrew Edwards on 3/23/19. +// + +import Vapor + +public protocol ExternalAccountsRoutes { + /// Creates a new bank account. When you create a new bank account, you must specify a [Custom account](https://stripe.com/docs/connect/custom-accounts) to create it on. + /// + /// - Parameters: + /// - account: The connect account this bank account should be created for. + /// - bankAccount: Either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe-js/reference), or a dictionary containing a user’s bank account details + /// - defaultForCurrency: When set to true, or if this is the first external account added in this currency, this account becomes the default external account for its currency. + + /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. + /// - Returns: A `StripeBankAccount`. + /// - Throws: A `StripeError`. + func create(account: String, bankAccount: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture + + /// By default, you can see the 10 most recent external accounts stored on a Custom account directly on the object, but you can also retrieve details about a specific bank account stored on the [Custom account](https://stripe.com/docs/connect/custom-accounts). + /// + /// - Parameters: + /// - account: The connect account associated with this bank account. + /// - id: The ID of the bank account to retrieve. + /// - Returns: A `StripeBankAccount`. + /// - Throws: A `StripeError`. + func retrieve(account: String, id: String) throws -> EventLoopFuture + + /// Updates the metadata, account holder name, and account holder type of a bank account belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts), and optionally sets it as the default for its currency. Other bank account details are not editable by design. \n You can re-enable a disabled bank account by performing an update call without providing any arguments or changes. + /// + /// - Parameters: + /// - account: The connect account associated with this bank account. + /// - id: The ID of the bank account to update. + /// - accountHolderName: The name of the person or business that owns the bank account. This will be unset if you POST an empty value. + /// - accountHolderType: The type of entity that holds the account. This can be either `individual` or `company`. This will be unset if you POST an empty value. + /// - defaultForCurrency: When set to true, this becomes the default external account for its currency. + /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. + /// - Returns: A `StripeBankAccount`. + /// - Throws: A `StripeError`. + func update(account: String, + id: String, + accountHolderName: String?, + accountHolderType: StripeBankAccountHolderType?, + defaultForCurrency: Bool?, + metadata: [String: String]?) throws -> EventLoopFuture + + /// Deletes a bank account. You can delete destination bank accounts from a [Custom account](https://stripe.com/docs/connect/custom-accounts). \n If a bank account's `default_for_currency` property is true, it can only be deleted if it is the only external account for that currency, and the currency is not the Stripe account's default currency. Otherwise, before deleting the account, you must set another external account to be the default for the currency. + + /// + /// - Parameters: + /// - account: The connect account associated with this bank account. + /// - id: The ID of the bank account to be deleted. + /// - Returns: A `StripeDeletedObject`. + /// - Throws: A `StripeError`. + func deleteBankAccount(account: String, id: String) throws -> EventLoopFuture + + /// List all bank accounts belonging to a connect account. You can see a list of the bank accounts belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts). Note that the 10 most recent external accounts are always available by default on the corresponding Stripe object. If you need more than those 10, you can use this API method and the `limit` and `starting_after` parameters to page through additional bank accounts. + /// + /// - Parameters: + /// - account: The connect account associated with the bank account(s). + /// - filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/external_account_bank_accounts/list) + /// - Returns: A `StripeBankAccountList`. + /// - Throws: A `StripeError`. + func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture + + /// Creates a new card. When you create a new card, you must specify a [Custom account](https://stripe.com/docs/connect/custom-accounts) to create it on. \n If the account has no default destination card, then the new card will become the default. However, if the owner already has a default then it will not change. To change the default, you should set `default_for_currency` to `true` when creating a card for a Custom account. + /// + /// - Parameters: + /// - account: The connect account this card should be created for. + /// - card: Either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe-js/reference), or a dictionary containing a user’s card details. + /// - defaultForCurrency: When set to true, or if this is the first external account added in this currency, this account becomes the default external account for its currency. + + /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. + /// - Returns: A `StripeCard`. + /// - Throws: A `StripeError`. + func create(account: String, card: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture + + /// By default, you can see the 10 most recent external accounts stored on a [Custom account](https://stripe.com/docs/connect/custom-accounts) directly on the object, but you can also retrieve details about a specific card stored on the [Custom account](https://stripe.com/docs/connect/custom-accounts). + /// + /// - Parameters: + /// - account: The connect account associated with this card. + /// - id: The ID of the card to retrieve. + /// - Returns: A `StripeCard`. + /// - Throws: A `StripeError`. + func retrieve(account: String, id: String) throws -> EventLoopFuture + + /// If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the full card details. Stripe also works directly with card networks so that your customers can [continue using your service](https://stripe.com/docs/saving-cards#automatic-card-updates) without interruption. + /// - Parameters: + /// - account: The connect account associated with this card. + /// - id: The ID of the card to update. + /// - addressCity: City/District/Suburb/Town/Village. This will be unset if you POST an empty value. + /// - addressCountry: Billing address country, if provided when creating card. This will be unset if you POST an empty value. + /// - addressLine1: Address line 1 (Street address/PO Box/Company name). This will be unset if you POST an empty value. + /// - addressLine2: Address line 2 (Apartment/Suite/Unit/Building). This will be unset if you POST an empty value. + /// - addressState: State/County/Province/Region. This will be unset if you POST an empty value. + /// - addressZip: ZIP or postal code. This will be unset if you POST an empty value. + /// - defaultForCurrency: When set to true, this becomes the default external account for its currency. + /// - expMonth: Two digit number representing the card’s expiration month. + /// - expYear: Four digit number representing the card’s expiration year. + /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. + /// - name: Cardholder name. This will be unset if you POST an empty value. + /// - Returns: A `StripeCard`. + /// - Throws: A `StripeError`. + func update(account: String, + id: String, + addressCity: String?, + addressCountry: String?, + addressLine1: String?, + addressLine2: String?, + addressState: String?, + addressZip: String?, + defaultForCurrency: Bool?, + expMonth: Int?, + expYear: Int?, + metadata: [String: String]?, + name: String?) throws -> EventLoopFuture + + /// Deletes a card. If a card's default_for_currency property is true, it can only be deleted if it is the only external account for that currency, and the currency is not the Stripe account's default currency. Otherwise, before deleting the card, you must set another external account to be the default for the currency. + /// + /// - Parameters: + /// - account: The connect account associated with this card. + /// - id: The ID of the card to be deleted. + /// - Returns: A `StripeDeletedObject`. + /// - Throws: A `StripeError`. + func deleteCard(account: String, id: String) throws -> EventLoopFuture + + /// List all cards belonging to a connect account. You can see a list of the cards belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts). Note that the 10 most recent external accounts are always available by default on the corresponding Stripe object. If you need more than those 10, you can use this API method and the `limit` and `starting_after` parameters to page through additional bank accounts. + /// + /// - Parameters: + /// - account: The connect account associated with the card(s). + /// - filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/external_account_cards/list) + /// - Returns: A `StripeCardList`. + /// - Throws: A `StripeError`. + func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture +} + +extension ExternalAccountsRoutes { + public func create(account: String, bankAccount: Any, defaultForCurrency: Bool? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { + return try create(account: account, bankAccount: bankAccount, defaultForCurrency: defaultForCurrency, metadata: metadata) + } + + public func retrieve(account: String, id: String) throws -> EventLoopFuture { + return try retrieve(account: account, id: id) + } + + public func update(account: String, + id: String, + accountHolderName: String? = nil, + accountHolderType: StripeBankAccountHolderType? = nil, + defaultForCurrency: Bool? = nil, + metadata: [String: String]? = nil) throws -> EventLoopFuture { + return try update(account: account, + id: id, + accountHolderName: accountHolderName, + accountHolderType: accountHolderType, + defaultForCurrency: defaultForCurrency, + metadata: metadata) + } + + public func deleteBankAccount(account: String, id: String) throws -> EventLoopFuture { + return try deleteBankAccount(account: account, id: id) + } + + public func listAll(account: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { + return try listAll(account: account, filter: filter) + } + + public func create(account: String, card: Any, defaultForCurrency: Bool? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { + return try create(account: account, card: card, defaultForCurrency: defaultForCurrency, metadata: metadata) + } + + public func retrieve(account: String, id: String) throws -> EventLoopFuture { + return try retrieve(account: account, id: id) + } + + public func update(account: String, + id: String, + addressCity: String? = nil, + addressCountry: String? = nil, + addressLine1: String? = nil, + addressLine2: String? = nil, + addressState: String? = nil, + addressZip: String? = nil, + defaultForCurrency: Bool? = nil, + expMonth: Int? = nil, + expYear: Int? = nil, + metadata: [String: String]? = nil, + name: String?) throws -> EventLoopFuture { + return try update(account: account, + id: id, + addressCity: addressCity, + addressCountry: addressCountry, + addressLine1: addressLine1, + addressLine2: addressLine2, + addressState: addressState, + addressZip: addressZip, + defaultForCurrency: defaultForCurrency, + expMonth: expMonth, + expYear: expYear, + metadata: metadata, + name: name) + } + + public func deleteCard(account: String, id: String) throws -> EventLoopFuture { + return try deleteCard(account: account, id: id) + } + + public func listAll(account: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { + return try listAll(account: account, filter: filter) + } +} + +public struct StripeExternalAccountsRoutes: ExternalAccountsRoutes { + private let request: StripeRequest + + init(request: StripeRequest) { + self.request = request + } + + public func create(account: String, bankAccount: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture { + var body: [String: Any] = [:] + + if let bankToken = bankAccount as? String { + body["external_account"] = bankToken + } else if let bankDetails = bankAccount as? [String: Any] { + bankDetails.forEach { body["external_account[\($0)]"] = $1 } + } + + if let defaultForCurrency = defaultForCurrency { + body["default_for_currency"] = defaultForCurrency + } + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccount(account).endpoint, body: body.queryParameters) + } + + public func retrieve(account: String, id: String) throws -> EventLoopFuture { + return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) + } + + public func update(account: String, + id: String, + accountHolderName: String?, + accountHolderType: StripeBankAccountHolderType?, + defaultForCurrency: Bool?, + metadata: [String: String]?) throws -> EventLoopFuture { + var body: [String: Any] = [:] + + if let accountHolderName = accountHolderName { + body["account_holder_name"] = accountHolderName + } + + if let accountHolderType = accountHolderType { + body["account_holder_type"] = accountHolderType.rawValue + } + + if let defaultForCurrency = defaultForCurrency { + body["default_for_currency"] = defaultForCurrency + } + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint, body: body.queryParameters) + } + + public func deleteBankAccount(account: String, id: String) throws -> EventLoopFuture { + return try request.send(method: .DELETE, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) + } + + public func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture { + var queryParams = "" + if let filter = filter { + queryParams = filter.queryParameters + } + return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccount(account).endpoint, query: queryParams) + } + + public func create(account: String, card: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture { + var body: [String: Any] = [:] + + if let cardToken = card as? String { + body["external_account"] = cardToken + } else if let cardDetails = card as? [String: Any] { + cardDetails.forEach { body["external_account[\($0)]"] = $1 } + } + + if let defaultForCurrency = defaultForCurrency { + body["default_for_currency"] = defaultForCurrency + } + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccount(account).endpoint, body: body.queryParameters) + } + + public func retrieve(account: String, id: String) throws -> EventLoopFuture { + return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) + } + + public func update(account: String, + id: String, + addressCity: String?, + addressCountry: String?, + addressLine1: String?, + addressLine2: String?, + addressState: String?, + addressZip: String?, + defaultForCurrency: Bool?, + expMonth: Int?, + expYear: Int?, + metadata: [String: String]?, + name: String?) throws -> EventLoopFuture { + var body: [String: Any] = [:] + + if let addressCity = addressCity { + body["address_city"] = addressCity + } + + if let addressCountry = addressCountry { + body["address_country"] = addressCountry + } + + if let addressLine1 = addressLine1 { + body["address_line1"] = addressLine1 + } + + if let addressLine2 = addressLine2 { + body["address_line2"] = addressLine2 + } + + if let addressState = addressState { + body["address_state"] = addressState + } + + if let addressZip = addressZip { + body["address_zip"] = addressZip + } + + if let defaultForCurrency = defaultForCurrency { + body["default_for_currency"] = defaultForCurrency + } + + if let expMonth = expMonth { + body["exp_month"] = expMonth + } + + if let expYear = expYear { + body["exp_year"] = expYear + } + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + if let name = name { + body["name"] = name + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint, body: body.queryParameters) + } + + public func deleteCard(account: String, id: String) throws -> EventLoopFuture { + return try request.send(method: .DELETE, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) + } + + public func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture { + var queryParams = "" + if let filter = filter { + queryParams = filter.queryParameters + } + return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccount(account).endpoint, query: queryParams) + } +} diff --git a/Sources/Stripe/Helpers/FundingType.swift b/Sources/Stripe/Helpers/FundingType.swift deleted file mode 100644 index a21de75..0000000 --- a/Sources/Stripe/Helpers/FundingType.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// FundingType.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -public enum FundingType: String, Codable { - case credit - case debit - case prepaid - case unknown -} diff --git a/Sources/Stripe/Models/Connect/Account.swift b/Sources/Stripe/Models/Connect/Account.swift index 0cc87a3..1da4610 100644 --- a/Sources/Stripe/Models/Connect/Account.swift +++ b/Sources/Stripe/Models/Connect/Account.swift @@ -26,7 +26,7 @@ public struct StripeConnectAccount: StripeModel { public var defaultCurrency: StripeCurrency? public var detailsSubmitted: Bool? public var email: String? - public var externalAccounts: ExternalAccountsList? + public var externalAccounts: StripeExternalAccountsList? public var individual: StripePerson? public var metadata: [String: String] public var payoutsEnabled: Bool? @@ -59,6 +59,20 @@ public struct StripeConnectAccount: StripeModel { } } +public struct StripeConnectAccountList: StripeModel { + public var object: String + public var hasMore: Bool + public var url: String? + public var data: [StripeConnectAccount]? + + private enum CodingKeys: String, CodingKey { + case object + case hasMore = "has_more" + case url + case data + } +} + public struct StripeConnectAccountBusinessProfile: StripeModel { public var mcc: String? public var name: String? diff --git a/Sources/Stripe/Models/Connect/AccountList.swift b/Sources/Stripe/Models/Connect/AccountList.swift deleted file mode 100644 index 5096a96..0000000 --- a/Sources/Stripe/Models/Connect/AccountList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// AccountList.swift -// Stripe -// -// Created by Andrew Edwards on 7/9/17. -// -// - -/** - Connected Account list - https://stripe.com/docs/api/curl#list_accounts - */ - -public struct ConnectedAccountsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeConnectAccount]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Connect/ApplicationFee.swift b/Sources/Stripe/Models/Connect/ApplicationFee.swift index 23e5495..b60cd65 100644 --- a/Sources/Stripe/Models/Connect/ApplicationFee.swift +++ b/Sources/Stripe/Models/Connect/ApplicationFee.swift @@ -58,14 +58,12 @@ public struct StripeApplicationFee: StripeModel { public struct StripeApplicationFeeList: StripeModel { public var object: String public var hasMore: Bool - public var totalCount: Int? public var url: String? public var data: [StripeApplicationFee]? private enum CodingKeys: String, CodingKey { case object case hasMore = "has_more" - case totalCount = "total_count" case url case data } diff --git a/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift b/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift index ebb7fb4..f6a52d6 100644 --- a/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift +++ b/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift @@ -40,14 +40,12 @@ public struct StripeApplicationFeeRefund: StripeModel { public struct StripeApplicationFeeRefundList: StripeModel { public var object: String public var hasMore: Bool - public var totalCount: Int? public var url: String? public var data: [StripeApplicationFeeRefund]? private enum CodingKeys: String, CodingKey { case object case hasMore = "has_more" - case totalCount = "total_count" case url case data } diff --git a/Sources/Stripe/Models/Connect/ExternalAccounts.swift b/Sources/Stripe/Models/Connect/ExternalAccounts.swift index 13fd076..254c20e 100644 --- a/Sources/Stripe/Models/Connect/ExternalAccounts.swift +++ b/Sources/Stripe/Models/Connect/ExternalAccounts.swift @@ -6,41 +6,41 @@ // // -/** - External accounts list - https://stripe.com/docs/api/curl#account_object-external_accounts - */ - -public struct ExternalAccountsList: StripeModel { +/// External accounts list. [See here](https://stripe.com/docs/api/accounts/object#account_object-external_accounts) +public struct StripeExternalAccountsList: StripeModel { + /// String representing the object’s type. Objects of the same type share the same value. Always has the value list. public var object: String - public var hasMore: Bool - public var totalCount: Int? + /** + Needs to be a string because the result can be an array of 2 possible types `StripeCard` and/or `StripeBankAccount`. + We'll actually decode the array of accounts seperately based on type and filtered based on object. See the initializer. + The `data` key is still needed in the `CodingKeys` and for decoding that property from the Stripe API, so we still have to declare it even though the type is unused. + */ + private var data: String? + /// True if this list has another page of items after this one that can be fetched. + public var hasMore: Bool? + /// The URL where this list can be accessed. public var url: String? - // FIXME: - This is still quite hackey and i haven't come up with a great solution yet - public var data: String? + /// An array of `StripeCard`s associated with the account. public var cardAccounts: [StripeCard]? + /// /// An array of `StripeBankAccount`s associated with the account. public var bankAccounts: [StripeBankAccount]? public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) object = try container.decode(String.self, forKey: .object) hasMore = try container.decode(Bool.self, forKey: .hasMore) - totalCount = try container.decodeIfPresent(Int.self, forKey: .totalCount) url = try container.decodeIfPresent(String.self, forKey: .url) cardAccounts = try container.decodeIfPresent([StripeCard].self, forKey: .data)?.filter{ $0.object == "card" } bankAccounts = try container.decodeIfPresent([StripeBankAccount].self, forKey: .data)?.filter{ $0.object == "bank_account" } } - public enum CodingKeys: String, CodingKey { + private enum CodingKeys: String, CodingKey { case object + case data case hasMore = "has_more" - case totalCount = "total_count" case url - case data case cardAccounts case bankAccounts } } - -public protocol ExternalAccount {} diff --git a/Sources/Stripe/Models/Connect/ExternalBankAccount.swift b/Sources/Stripe/Models/Connect/ExternalBankAccount.swift deleted file mode 100644 index 0c4a25b..0000000 --- a/Sources/Stripe/Models/Connect/ExternalBankAccount.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// ExternalBankAccount.swift -// Stripe -// -// Created by Andrew Edwards on 1/20/18. -// - -// Only used for creating/updating Account external sources. -// Not expected to be returned by the API at all. -public struct StripeExternalBankAccount: ExternalAccount, StripeModel { - public var object: String = "bank_account" - public var accountNumber: String? - public var country: String? - public var currency: StripeCurrency? - public var accountHolderName: String? - public var accountHolderType: String? - public var routingNumber: String? - - public enum CodingKeys: String, CodingKey { - case object - case accountNumber = "account_number" - case country - case currency - case accountHolderName = "account_holder_name" - case accountHolderType = "account_holder_type" - case routingNumber = "routing_number" - } -} diff --git a/Sources/Stripe/Models/Connect/ExternalCardAccount.swift b/Sources/Stripe/Models/Connect/ExternalCardAccount.swift deleted file mode 100644 index ca00119..0000000 --- a/Sources/Stripe/Models/Connect/ExternalCardAccount.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// ExternalCardAccount.swift -// Stripe -// -// Created by Andrew Edwards on 1/20/18. -// - -// Only used for creating/updating Account external sources. -// Not expected to be returned by the API at all. -public struct StripeExternalCardAccount: ExternalAccount, StripeModel { - public var object: String = "card" - public var currency: StripeCurrency? - public var defaultForCurrency: Bool? - public var expMonth: Int? - public var expYear: Int? - public var number: String? - public var addressCity: String? - public var addressCountry: String? - public var addressLine1: String? - public var addressLine2: String? - public var addressState: String? - public var addressZip: String? - public var cvc: String? - public var metadata: [String: String]? - public var name: String? - - public enum CodingKeys: String, CodingKey { - case object - case defaultForCurrency = "default_for_currency" - case expMonth = "exp_month" - case expYear = "exp_year" - case number - case addressCity = "address_city" - case addressCountry = "address_country" - case addressLine1 = "address_line1" - case addressLine2 = "address_line2" - case addressState = "address_state" - case addressZip = "address_zip" - case cvc - case metadata - case name - } -} diff --git a/Sources/Stripe/Models/Sources/BankAccount.swift b/Sources/Stripe/Models/Sources/BankAccount.swift index 8e45dfc..7f735ee 100644 --- a/Sources/Stripe/Models/Sources/BankAccount.swift +++ b/Sources/Stripe/Models/Sources/BankAccount.swift @@ -6,27 +6,38 @@ // // -/** - Bank Account object - https://stripe.com/docs/api/curl#customer_bank_account_object -*/ - +/// The bank account object. [See here](https://stripe.com/docs/api/customer_bank_accounts/object). public struct StripeBankAccount: StripeModel { + /// Unique identifier for the object. public var id: String + /// String representing the object’s type. Objects of the same type share the same value. public var object: String + /// The account this bank account belongs to. public var account: String? + /// The name of the person or business that owns the bank account. public var accountHolderName: String? - public var accountHolderType: String? + /// The type of entity that holds the account. This can be either `individual` or `company`. + public var accountHolderType: StripeBankAccountHolderType? + /// Name of the bank associated with the routing number (e.g., WELLS FARGO). public var bankName: String? + /// Two-letter ISO code representing the country the bank account is located in. public var country: String? + /// Three-letter ISO code for the currency paid out to the bank account. public var currency: StripeCurrency? + /// The customer that this bank account belongs to. public var customer: String? + /// Whether this bank account is the default external account for its currency. public var defaultForCurrency: Bool? + /// Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. public var fingerprint: String? + /// /// The last four digits of the bank account. public var last4: String? + /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. public var metadata: [String: String]? + /// The routing transit number for the bank account. public var routingNumber: String? - public var status: BankAccountStatus? + /// For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. A bank account that hasn’t had any activity or validation performed is `new`. If Stripe can determine that the bank account exists, its status will be `validated`. Note that there often isn’t enough information to know (e.g., for smaller credit unions), and the validation is not always run. If customer bank account verification has succeeded, the bank account status will be `verified`. If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. If a transfer sent to this bank account fails, we’ll set the status to `errored` and will not continue to send transfers until the bank details are updated. \n For external accounts, possible values are `new` and `errored`. Validations aren’t run against external accounts because they’re only used for payouts. This means the other statuses don’t apply. If a transfer fails, the status is set to `errored` and transfers are stopped until account details are updated. + public var status: StripeBankAccountStatus? public enum CodingKeys: String, CodingKey { case id @@ -47,10 +58,33 @@ public struct StripeBankAccount: StripeModel { } } -public enum BankAccountStatus: String, Codable { +public struct StripeBankAccountList: StripeModel { + /// String representing the object’s type. Objects of the same type share the same value. Always has the value list. + public var object: String + /// An array of `StripeCard`s associated with the account. + public var data: [StripeBankAccount]? + /// True if this list has another page of items after this one that can be fetched. + public var hasMore: Bool? + /// The URL where this list can be accessed. + public var url: String? + + private enum CodingKeys: String, CodingKey { + case object + case data + case hasMore = "has_more" + case url + } +} + +public enum StripeBankAccountStatus: String, Codable { case new case validated case verified case verificationFailed = "verification_failed" case errored } + +public enum StripeBankAccountHolderType: String, StripeModel { + case individual + case company +} diff --git a/Sources/Stripe/Models/Sources/Card.swift b/Sources/Stripe/Models/Sources/Card.swift index 570f637..72e5a3f 100644 --- a/Sources/Stripe/Models/Sources/Card.swift +++ b/Sources/Stripe/Models/Sources/Card.swift @@ -6,42 +6,64 @@ // // -/** - Card object - https://stripe.com/docs/api/curl#card_object - https://stripe.com/docs/sources/cards - */ - +/// The card object. [See here](https://stripe.com/docs/api/external_account_cards/object). public struct StripeCard: StripeModel { + /// Unique identifier for the object. public var id: String + /// String representing the object’s type. Objects of the same type share the same value. public var object: String + /// The account this card belongs to. This attribute will not be in the card object if the card belongs to a customer or recipient instead. public var account: String? + /// City/District/Suburb/Town/Village. public var addressCity: String? + /// Billing address country, if provided when creating card. public var addressCountry: String? + /// Address line 1 (Street address/PO Box/Company name). public var addressLine1: String? - public var addressLine1Check: CardValidationCheck? + /// If `address_line1` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + public var addressLine1Check: StripeCardValidationCheck? + /// Address line 2 (Apartment/Suite/Unit/Building). public var addressLine2: String? + /// State/County/Province/Region. public var addressState: String? + /// ZIP or postal code. public var addressZip: String? - public var addressZipCheck: CardValidationCheck? + /// If `address_zip` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + public var addressZipCheck: StripeCardValidationCheck? + /// A set of available payout methods for this card. Will be either `["standard"]` or `["standard", "instant"]`. Only values from this set should be passed as the `method` when creating a transfer. public var availablePayoutMethods: [String]? - public var brand: String? + /// Card brand. Can be `American Express`, `Diners Club`, `Discover`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. + public var brand: StripeCardBrand? + /// Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you’ve collected. public var country: String? + /// Three-letter ISO code for currency. Only applicable on accounts (not customers or recipients). The card can be used as a transfer destination for funds in this currency. public var currency: StripeCurrency? + /// The customer that this card belongs to. This attribute will not be in the card object if the card belongs to an account or recipient instead. public var customer: String? - public var cvcCheck: CardValidationCheck? + /// If a CVC was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + public var cvcCheck: StripeCardValidationCheck? + /// Whether this card is the default external account for its currency. public var defaultForCurrency: Bool? + /// (For tokenized numbers only.) The last four digits of the device account number. public var dynamicLast4: String? + /// Two-digit number representing the card’s expiration month. public var expMonth: Int? + /// Four-digit number representing the card’s expiration year. public var expYear: Int? - public var fingerprint: String - public var funding: FundingType? + /// Uniquely identifies this particular card number. You can use this attribute to check whether two customers who’ve signed up with you are using the same card number, for example. + public var fingerprint: String? + /// Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. + public var funding: StripeCardFundingType? + /// The last four digits of the card. public var last4: String? - public var metadata: [String: String] + /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + public var metadata: [String: String]? + /// Cardholder name. public var name: String? + /// The recipient that this card belongs to. This attribute will not be in the card object if the card belongs to a customer or account instead. public var recipient: String? - public var tokenizationMethod: TokenizedMethod? - public var threeDSecure: String? + /// If the card number is tokenized, this is the method that was used. Can be `apple_pay` or `google_pay`. + public var tokenizationMethod: StripeCardTokenizedMethod? public enum CodingKeys: String, CodingKey { case id @@ -71,6 +93,53 @@ public struct StripeCard: StripeModel { case name case recipient case tokenizationMethod = "tokenization_method" - case threeDSecure = "three_d_secure" } } + +public struct StripeCardList: StripeModel { + /// String representing the object’s type. Objects of the same type share the same value. Always has the value list. + public var object: String + /// An array of `StripeCard`s associated with the account. + public var data: [StripeCard]? + /// True if this list has another page of items after this one that can be fetched. + public var hasMore: Bool? + /// The URL where this list can be accessed. + public var url: String? + + private enum CodingKeys: String, CodingKey { + case object + case data + case hasMore = "has_more" + case url + } +} + +public enum StripeCardValidationCheck: String, Codable { + case pass + case failed + case unavailable + case unchecked +} + +public enum StripeCardBrand: String, Codable { + case americanExpress = "American Express" + case dinersClub = "Diners Club" + case discover = "Discover" + case jcb = "JCB" + case masterCard = "MasterCard" + case unionPay = "UnionPay" + case visa = "Visa" + case unknown = "Unknown" +} + +public enum StripeCardFundingType: String, Codable { + case credit + case debit + case prepaid + case unknown +} + +public enum StripeCardTokenizedMethod: String, Codable { + case applePay = "apple_pay" + case androidPay = "android_pay" +} diff --git a/Sources/Stripe/Models/Sources/CardValidationCheck.swift b/Sources/Stripe/Models/Sources/CardValidationCheck.swift deleted file mode 100644 index 4333721..0000000 --- a/Sources/Stripe/Models/Sources/CardValidationCheck.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// ValidationCheck.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -public enum CardValidationCheck: String, Codable { - case pass - case failed - case unavailable - case unchecked -} diff --git a/Sources/Stripe/Models/Sources/OtherSources.swift b/Sources/Stripe/Models/Sources/OtherSources.swift index 84fcc98..11759ac 100644 --- a/Sources/Stripe/Models/Sources/OtherSources.swift +++ b/Sources/Stripe/Models/Sources/OtherSources.swift @@ -139,7 +139,7 @@ public struct ACHCreditTransfer: StripeModel { // MARK: - Basic Card public struct StripeBasicCard: StripeModel { - public var funding: FundingType + public var funding: StripeCardFundingType public var expMonth: Int public var country: String public var threeDSecure: String diff --git a/Sources/Stripe/Models/Sources/TokenizedMethod.swift b/Sources/Stripe/Models/Sources/TokenizedMethod.swift deleted file mode 100644 index b287489..0000000 --- a/Sources/Stripe/Models/Sources/TokenizedMethod.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// TokenizedMethod.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -import Foundation - -public enum TokenizedMethod: String, Codable { - case applePay = "apple_pay" - case androidPay = "android_pay" -} diff --git a/Sources/Stripe/Provider/Provider.swift b/Sources/Stripe/Provider/Provider.swift index 5335fdf..beb4506 100644 --- a/Sources/Stripe/Provider/Provider.swift +++ b/Sources/Stripe/Provider/Provider.swift @@ -71,6 +71,7 @@ public final class StripeClient: Service { public var person: PersonRoutes public var applicationFee: ApplicationFeesRoutes public var applicationFeeRefunds: ApplicationFeeRefundRoutes + public var externalAccounts: ExternalAccountsRoutes internal init(apiKey: String, testKey: String?, client: Client) { let apiRequest = StripeAPIRequest(httpClient: client, apiKey: apiKey, testApiKey: testKey) @@ -102,5 +103,6 @@ public final class StripeClient: Service { person = StripePersonRoutes(request: apiRequest) applicationFee = StripeApplicationFeeRoutes(request: apiRequest) applicationFeeRefunds = StripeApplicationFeeRefundRoutes(request: apiRequest) + externalAccounts = StripeExternalAccountsRoutes(request: apiRequest) } } diff --git a/Tests/StripeTests/AccountTests.swift b/Tests/StripeTests/AccountTests.swift index 8dbcfee..81d620b 100644 --- a/Tests/StripeTests/AccountTests.swift +++ b/Tests/StripeTests/AccountTests.swift @@ -93,7 +93,6 @@ class AccountTests: XCTestCase { } ], "has_more": false, - "total_count": 2, "url": "/v1/accounts/acct_1032D82eZvKYlo2C/external_accounts" }, "individual": { @@ -259,7 +258,6 @@ class AccountTests: XCTestCase { // ExternalAccounts XCTAssertEqual(account.externalAccounts?.object, "list") XCTAssertEqual(account.externalAccounts?.hasMore, false) - XCTAssertEqual(account.externalAccounts?.totalCount, 2) XCTAssertEqual(account.externalAccounts?.url, "/v1/accounts/acct_1032D82eZvKYlo2C/external_accounts") XCTAssertEqual(account.externalAccounts?.cardAccounts?.count, 1) XCTAssertEqual(account.externalAccounts?.bankAccounts?.count, 1) diff --git a/Tests/StripeTests/TokenTests.swift b/Tests/StripeTests/TokenTests.swift index 0eef0b7..153dd99 100644 --- a/Tests/StripeTests/TokenTests.swift +++ b/Tests/StripeTests/TokenTests.swift @@ -37,7 +37,7 @@ class TokenTests: XCTestCase { XCTAssertEqual(token.card?.addressState, "Florida") XCTAssertEqual(token.card?.addressZip, "12345") XCTAssertEqual(token.card?.addressZipCheck, .pass) - XCTAssertEqual(token.card?.brand, "Visa") + XCTAssertEqual(token.card?.brand, .visa) XCTAssertEqual(token.card?.country, "US") XCTAssertEqual(token.card?.cvcCheck, .pass) XCTAssertEqual(token.card?.dynamicLast4, "1234") @@ -46,7 +46,7 @@ class TokenTests: XCTestCase { XCTAssertEqual(token.card?.fingerprint, "Xt5EWLLDS7FJjR1c") XCTAssertEqual(token.card?.funding, .credit) XCTAssertEqual(token.card?.last4, "4242") - XCTAssertEqual(token.card?.metadata["hello"], "world") + XCTAssertEqual(token.card?.metadata?["hello"], "world") XCTAssertEqual(token.card?.name, "Vapor") XCTAssertEqual(token.card?.tokenizationMethod, .applePay) @@ -85,7 +85,7 @@ class TokenTests: XCTestCase { XCTAssertEqual(token.bankAccount?.id, "ba_1BnxhQ2eZvKYlo2C5cM6hYK1") XCTAssertEqual(token.bankAccount?.object, "bank_account") XCTAssertEqual(token.bankAccount?.accountHolderName, "Jane Austen") - XCTAssertEqual(token.bankAccount?.accountHolderType, "individual") + XCTAssertEqual(token.bankAccount?.accountHolderType, .individual) XCTAssertEqual(token.bankAccount?.bankName, "STRIPE TEST BANK") XCTAssertEqual(token.bankAccount?.country, "US") XCTAssertEqual(token.bankAccount?.currency, .usd) From 6c03c860792b8306a6c781a3bea05575833ecc9e Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Sat, 23 Mar 2019 07:11:22 -0400 Subject: [PATCH 07/14] Implemented country specs. --- README.md | 2 +- Sources/Stripe/API/Helpers/Endpoints.swift | 6 ++ .../Stripe/API/Routes/CountrySpecRoutes.swift | 54 ++++++++++ .../Stripe/Models/Connect/CountrySpec.swift | 66 ++++++++++++ Sources/Stripe/Provider/Provider.swift | 2 + Tests/StripeTests/CountrySpecTests.swift | 102 ++++++++++++++++++ 6 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 Sources/Stripe/API/Routes/CountrySpecRoutes.swift create mode 100644 Sources/Stripe/Models/Connect/CountrySpec.swift create mode 100644 Tests/StripeTests/CountrySpecTests.swift diff --git a/README.md b/README.md index 58b5cd9..7443689 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ Also make sure to check out stripes documenation to add the client JS magic [her * [x] Account * [x] Application Fee Refunds * [x] Application Fees -* [ ] Country Specs +* [x] Country Specs * [x] External Accounts * [x] Persons * [ ] Top-ups diff --git a/Sources/Stripe/API/Helpers/Endpoints.swift b/Sources/Stripe/API/Helpers/Endpoints.swift index 4ee2cbf..34e80a7 100644 --- a/Sources/Stripe/API/Helpers/Endpoints.swift +++ b/Sources/Stripe/API/Helpers/Endpoints.swift @@ -136,6 +136,9 @@ internal enum StripeAPIEndpoint { case externalAccount(String) case externalAccounts(String, String) + case countrySpec + case countrySpecs(String) + var endpoint: String { switch self { case .balance: return APIBase + APIVersion + "balance" @@ -235,6 +238,9 @@ internal enum StripeAPIEndpoint { case . externalAccount(let account): return APIBase + APIVersion + "accounts/\(account)/external_accounts" case . externalAccounts(let account, let id): return APIBase + APIVersion + "accounts/\(account)/external_accounts/\(id)" + + case .countrySpec: return APIBase + APIVersion + "country_specs" + case .countrySpecs(let country): return APIBase + APIVersion + "country_specs/\(country)" } } } diff --git a/Sources/Stripe/API/Routes/CountrySpecRoutes.swift b/Sources/Stripe/API/Routes/CountrySpecRoutes.swift new file mode 100644 index 0000000..99a3a0a --- /dev/null +++ b/Sources/Stripe/API/Routes/CountrySpecRoutes.swift @@ -0,0 +1,54 @@ +// +// CountrySpecRoutes.swift +// Stripe +// +// Created by Andrew Edwards on 3/23/19. +// + +import Vapor + +public protocol CountrySpecRoutes { + /// Lists all Country Spec objects available in the API. + /// + /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/country_specs/list) + /// - Returns: A `StripeCountrySpecList`. + /// - Throws: A `StripeError`. + func listAll(filter: [String: Any]?) throws -> EventLoopFuture + + /// Returns a Country Spec for a given Country code. + /// + /// - Parameter country: An ISO 3166-1 alpha-2 country code. Available country codes can be listed with the [List Country Specs](https://stripe.com/docs/api#list_country_specs) endpoint. + /// - Returns: A `StripeCountrySpec`. + /// - Throws: A `StripeError`. + func retrieve(country: String) throws -> EventLoopFuture +} + +extension CountrySpecRoutes { + public func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture { + return try listAll(filter: filter) + } + + public func retrieve(country: String) throws -> EventLoopFuture { + return try retrieve(country: country) + } +} + +public struct StripeCountrySpecRoutes: CountrySpecRoutes { + private let request: StripeRequest + + init(request: StripeRequest) { + self.request = request + } + + public func listAll(filter: [String: Any]?) throws -> EventLoopFuture { + var queryParams = "" + if let filter = filter { + queryParams = filter.queryParameters + } + return try request.send(method: .GET, path: StripeAPIEndpoint.countrySpec.endpoint, query: queryParams) + } + + public func retrieve(country: String) throws -> EventLoopFuture { + return try request.send(method: .GET, path: StripeAPIEndpoint.countrySpecs(country).endpoint) + } +} diff --git a/Sources/Stripe/Models/Connect/CountrySpec.swift b/Sources/Stripe/Models/Connect/CountrySpec.swift new file mode 100644 index 0000000..375b350 --- /dev/null +++ b/Sources/Stripe/Models/Connect/CountrySpec.swift @@ -0,0 +1,66 @@ +// +// CountrySpec.swift +// Stripe +// +// Created by Andrew Edwards on 3/23/19. +// + +import Vapor +/// Stripe needs to collect certain pieces of information about each account created. These requirements can differ depending on the account's country. The Country Specs API makes these rules available to your integration. +public struct StripeCountrySpec: StripeModel { + /// Unique identifier for the object. Represented as the ISO country code for this country. + public var id: String + /// String representing the object’s type. Objects of the same type share the same value. + public var object: String + /// The default currency for this country. This applies to both payment methods and bank accounts. + public var defaultCurrency: StripeCurrency? + /// Currencies that can be accepted in the specific country (for transfers). + public var supportedBankAccountCurrencies: [String: [String]]? + /// Currencies that can be accepted in the specified country (for payments). + public var supportedPaymentCurrencies: [StripeCurrency]? + /// Payment methods available in the specified country. You may need to enable some payment methods (e.g., [ACH](https://stripe.com/docs/ach)) on your account before they appear in this list. The `stripe` payment method refers to [charging through your platform](https://stripe.com/docs/connect/destination-charges). + public var supportedPaymentMethods: [String]? + /// Countries that can accept transfers from the specified country. + public var supportedTransferCountries: [String]? + /// Lists the types of verification data needed to keep an account open. + public var verificationFields: StripeCountrySpecVerificationFields? + + private enum CodingKeys: String, CodingKey { + case id + case object + case defaultCurrency = "default_currency" + case supportedBankAccountCurrencies = "supported_bank_account_currencies" + case supportedPaymentCurrencies = "supported_payment_currencies" + case supportedPaymentMethods = "supported_payment_methods" + case supportedTransferCountries = "supported_transfer_countries" + case verificationFields = "verification_fields" + } +} + +public struct StripeCountrySpecList: StripeModel { + public var object: String + public var hasMore: Bool + public var url: String? + public var data: [StripeCountrySpec]? + + private enum CodingKeys: String, CodingKey { + case object + case hasMore = "has_more" + case url + case data + } +} + +public struct StripeCountrySpecVerificationFields: StripeModel { + /// Verification types for company account. + public var company: StripeCountrySpecVerificationFieldsAttributes? + /// Verification types for individual account. + public var individual: StripeCountrySpecVerificationFieldsAttributes? +} + +public struct StripeCountrySpecVerificationFieldsAttributes: StripeModel { + /// Additional fields which are only required for some users. + public var additional: [String]? + /// Fields which every account must eventually provide. + public var minimum: [String]? +} diff --git a/Sources/Stripe/Provider/Provider.swift b/Sources/Stripe/Provider/Provider.swift index beb4506..3a661fc 100644 --- a/Sources/Stripe/Provider/Provider.swift +++ b/Sources/Stripe/Provider/Provider.swift @@ -72,6 +72,7 @@ public final class StripeClient: Service { public var applicationFee: ApplicationFeesRoutes public var applicationFeeRefunds: ApplicationFeeRefundRoutes public var externalAccounts: ExternalAccountsRoutes + public var countrySpecs: CountrySpecRoutes internal init(apiKey: String, testKey: String?, client: Client) { let apiRequest = StripeAPIRequest(httpClient: client, apiKey: apiKey, testApiKey: testKey) @@ -104,5 +105,6 @@ public final class StripeClient: Service { applicationFee = StripeApplicationFeeRoutes(request: apiRequest) applicationFeeRefunds = StripeApplicationFeeRefundRoutes(request: apiRequest) externalAccounts = StripeExternalAccountsRoutes(request: apiRequest) + countrySpecs = StripeCountrySpecRoutes(request: apiRequest) } } diff --git a/Tests/StripeTests/CountrySpecTests.swift b/Tests/StripeTests/CountrySpecTests.swift new file mode 100644 index 0000000..c6d9729 --- /dev/null +++ b/Tests/StripeTests/CountrySpecTests.swift @@ -0,0 +1,102 @@ +// +// CountrySpecTests.swift +// StripeTests +// +// Created by Andrew Edwards on 3/23/19. +// + +import XCTest +@testable import Stripe +@testable import Vapor + +class CountrySpecTests: XCTestCase { + let countrySpecString = """ +{ + "id": "US", + "object": "country_spec", + "default_currency": "usd", + "supported_bank_account_currencies": { + "usd": [ + "US" + ] + }, + "supported_payment_currencies": [ + "usd", + "aed", + "afn", + ], + "supported_payment_methods": [ + "card", + "stripe" + ], + "supported_transfer_countries": [ + "US" + ], + "verification_fields": { + "company": { + "additional": [ + "relationship.account_opener" + ], + "minimum": [ + "business_profile.mcc", + "business_profile.url", + "business_type", + "company.address.city", + "company.address.line1", + "company.address.postal_code", + "company.address.state", + "company.name", + "company.phone", + "company.tax_id", + "external_account", + "relationship.account_opener", + "relationship.owner", + "tos_acceptance.date", + "tos_acceptance.ip" + ] + }, + "individual": { + "additional": [ + "individual.id_number" + ], + "minimum": [ + "business_profile.mcc", + "business_profile.url", + "business_type", + "external_account", + "individual.address.city", + "individual.address.line1", + "individual.address.postal_code", + "individual.address.state", + "individual.dob.day", + "individual.dob.month", + "individual.dob.year", + "individual.email", + "individual.first_name", + "individual.last_name", + "individual.phone", + "individual.ssn_last_4", + "tos_acceptance.date", + "tos_acceptance.ip" + ] + } + } +} +""" + + func testCountrySpecParsesProperly() throws { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + let body = HTTPBody(string: countrySpecString) + var headers: HTTPHeaders = [:] + headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) + let request = HTTPRequest(headers: headers, body: body) + let spec = try decoder.decode(StripeCountrySpec.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() + + XCTAssertEqual(spec.supportedBankAccountCurrencies?["usd"], ["US"]) + XCTAssertEqual(spec.supportedPaymentCurrencies?.count, 3) + XCTAssertEqual(spec.verificationFields?.company?.additional?.count, 1) + XCTAssertEqual(spec.verificationFields?.individual?.minimum?.count, 18) + } +} From 3dde44d9bfb26927a93ebfbff53efe40f09ef09f Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Sun, 24 Mar 2019 18:55:52 -0400 Subject: [PATCH 08/14] Implemented TopUps --- README.md | 2 +- Sources/Stripe/API/Helpers/Endpoints.swift | 8 + Sources/Stripe/API/Routes/TopUpRoutes.swift | 166 ++++++++++++++++++++ Sources/Stripe/Models/Connect/TopUp.swift | 84 ++++++++++ Sources/Stripe/Provider/Provider.swift | 2 + Tests/StripeTests/TopUpTests.swift | 52 ++++++ Tests/StripeTests/XCTestManifests.swift | 14 ++ 7 files changed, 327 insertions(+), 1 deletion(-) create mode 100644 Sources/Stripe/API/Routes/TopUpRoutes.swift create mode 100644 Sources/Stripe/Models/Connect/TopUp.swift create mode 100644 Tests/StripeTests/TopUpTests.swift diff --git a/README.md b/README.md index 7443689..d57c26c 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ Also make sure to check out stripes documenation to add the client JS magic [her * [x] Country Specs * [x] External Accounts * [x] Persons -* [ ] Top-ups +* [x] Top-ups * [x] Transfers * [x] Transfer Reversals --- diff --git a/Sources/Stripe/API/Helpers/Endpoints.swift b/Sources/Stripe/API/Helpers/Endpoints.swift index 34e80a7..bb02fa7 100644 --- a/Sources/Stripe/API/Helpers/Endpoints.swift +++ b/Sources/Stripe/API/Helpers/Endpoints.swift @@ -139,6 +139,10 @@ internal enum StripeAPIEndpoint { case countrySpec case countrySpecs(String) + case topup + case topups(String) + case topupsCancel(String) + var endpoint: String { switch self { case .balance: return APIBase + APIVersion + "balance" @@ -241,6 +245,10 @@ internal enum StripeAPIEndpoint { case .countrySpec: return APIBase + APIVersion + "country_specs" case .countrySpecs(let country): return APIBase + APIVersion + "country_specs/\(country)" + + case .topup: return APIBase + APIVersion + "topups" + case .topups(let id): return APIBase + APIVersion + "topups/\(id)" + case .topupsCancel(let id): return APIBase + APIVersion + "topups/\(id)/cancel" } } } diff --git a/Sources/Stripe/API/Routes/TopUpRoutes.swift b/Sources/Stripe/API/Routes/TopUpRoutes.swift new file mode 100644 index 0000000..fac3f80 --- /dev/null +++ b/Sources/Stripe/API/Routes/TopUpRoutes.swift @@ -0,0 +1,166 @@ +// +// TopUpRoutes.swift +// Stripe +// +// Created by Andrew Edwards on 3/24/19. +// + +import Vapor + +public protocol TopUpRoutes { + /// Top up the balance of an account + /// + /// - Parameters: + /// - amount: A positive integer representing how much to transfer. + /// - currency: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + /// - description: An arbitrary string attached to the object. Often useful for displaying to users. This will be unset if you POST an empty value. + /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + /// - source: The ID of a source to transfer funds from. For most users, this should be left unspecified which will use the bank account that was set up in the dashboard for the specified currency. In test mode, this can be a test bank token (see [Testing Top-ups](https://stripe.com/docs/connect/testing#testing-top-ups)). + /// - statementDescriptor: Extra information about a top-up for the source’s bank statement. Limited to 15 ASCII characters. + /// - transferGroup: A string that identifies this top-up as part of a group. + /// - Returns: A `StripeTopUp`. + /// - Throws: A `StripeError`. + func create(amount: Int, + currency: StripeCurrency, + description: String?, + metadata: [String: String]?, + source: String?, + statementDescriptor: String?, + transferGroup: String?) throws -> EventLoopFuture + + /// Retrieves the details of a top-up that has previously been created. Supply the unique top-up ID that was returned from your previous request, and Stripe will return the corresponding top-up information. + /// + /// - Parameter id: The ID of the top-up to retrieve. + /// - Returns: A `StripeTopUp`. + /// - Throws: A `StripeError`. + func retrieve(id: String) throws -> EventLoopFuture + + /// Updates the metadata of a top-up. Other top-up details are not editable by design. + /// + /// - Parameters: + /// - topup: The ID of the top-up to retrieve. + /// - description: An arbitrary string attached to the object. Often useful for displaying to users. This will be unset if you POST an empty value. + /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + /// - Returns: A `StripeTopUp`. + /// - Throws: A `StripeError`. + func update(topup: String, description: String?, metadata: [String: String]?) throws -> EventLoopFuture + + /// Returns a list of top-ups. + /// + /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/topups/list). + /// - Returns: A `StripeTopUpList`. + /// - Throws: A `StripeError`. + func listAll(filter: [String: Any]?) throws -> EventLoopFuture + + /// Cancels a top-up. Only pending top-ups can be canceled. + /// + /// - Parameter topup: The ID of the top-up to cancel. + /// - Returns: A canceled `StripeTopUp`. + /// - Throws: A `StripeError`. + func cancel(topup: String) throws -> EventLoopFuture +} + +extension TopUpRoutes { + public func create(amount: Int, + currency: StripeCurrency, + description: String? = nil, + metadata: [String: String]? = nil, + source: String? = nil, + statementDescriptor: String? = nil, + transferGroup: String? = nil) throws -> EventLoopFuture { + return try create(amount: amount, + currency: currency, + description: description, + metadata: metadata, + source: source, + statementDescriptor: statementDescriptor, + transferGroup: transferGroup) + } + + public func retrieve(id: String) throws -> EventLoopFuture { + return try retrieve(id: id) + } + + public func update(topup: String, description: String? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { + return try update(topup: topup, description: description, metadata: metadata) + } + + public func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture { + return try listAll(filter: filter) + } + + public func cancel(topup: String) throws -> EventLoopFuture { + return try cancel(topup: topup) + } +} + +public struct StripeTopUpRoutes: TopUpRoutes { + private let request: StripeRequest + + init(request: StripeRequest) { + self.request = request + } + + public func create(amount: Int, + currency: StripeCurrency, + description: String?, + metadata: [String: String]?, + source: String?, + statementDescriptor: String?, + transferGroup: String?) throws -> EventLoopFuture { + var body: [String: Any] = ["amount": amount, + "currency": currency.rawValue] + + if let description = description { + body["description"] = description + } + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + if let source = source { + body["source"] = source + } + + if let statementDescriptor = statementDescriptor { + body["statement_descriptor"] = statementDescriptor + } + + if let transferGroup = transferGroup { + body["transfer_group"] = transferGroup + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.topup.endpoint, body: body.queryParameters) + } + + public func retrieve(id: String) throws -> EventLoopFuture { + return try request.send(method: .GET, path: StripeAPIEndpoint.topups(id).endpoint) + } + + public func update(topup: String, description: String?, metadata: [String: String]?) throws -> EventLoopFuture { + var body: [String: Any] = [:] + + if let description = description { + body["description"] = description + } + + if let metadata = metadata { + metadata.forEach { body["metadata[\($0)]"] = $1 } + } + + return try request.send(method: .POST, path: StripeAPIEndpoint.topups(topup).endpoint, body: body.queryParameters) + } + + public func listAll(filter: [String: Any]?) throws -> EventLoopFuture { + var queryParams = "" + if let filter = filter { + queryParams = filter.queryParameters + } + return try request.send(method: .GET, path: StripeAPIEndpoint.topup.endpoint, query: queryParams) + } + + public func cancel(topup: String) throws -> EventLoopFuture { + return try request.send(method: .POST, path: StripeAPIEndpoint.topupsCancel(topup).endpoint) + } +} diff --git a/Sources/Stripe/Models/Connect/TopUp.swift b/Sources/Stripe/Models/Connect/TopUp.swift new file mode 100644 index 0000000..1a07e27 --- /dev/null +++ b/Sources/Stripe/Models/Connect/TopUp.swift @@ -0,0 +1,84 @@ +// +// TopUp.swift +// Stripe +// +// Created by Andrew Edwards on 3/24/19. +// + +import Vapor +/// The top-up object [see here](https://stripe.com/docs/api/topups/object) +public struct StripeTopUp: StripeModel { + /// Unique identifier for the object. + public var id: String + /// String representing the object’s type. Objects of the same type share the same value. + public var object: String + /// Amount transferred. + public var amount: Int? + /// ID of the balance transaction that describes the impact of this top-up on your account balance. May not be specified depending on status of top-up. + public var balanceTransaction: String? + /// Time at which the object was created. Measured in seconds since the Unix epoch. + public var created: Date? + /// Three-letter ISO currency code, in lowercase. Must be a supported currency. + public var currency: StripeCurrency? + /// An arbitrary string attached to the object. Often useful for displaying to users. + public var description: String? + /// Date the funds are expected to arrive in your Stripe account for payouts. This factors in delays like weekends or bank holidays. May not be specified depending on status of top-up. + public var expectedAvailabilityDate: Date? + /// Error code explaining reason for top-up failure if available (see [the errors section](https://stripe.com/docs/api#errors) for a list of codes). + public var failureCode: String? + /// Message to user further explaining reason for top-up failure if available. + public var failureMessage: String? + /// Has the value true if the object exists in live mode or the value false if the object exists in test mode. + public var livemode: Bool? + /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. + public var metadata: [String: String]? + /// For most Stripe users, the source of every top-up is a bank account. This hash is then the [source object](https://stripe.com/docs/api/topups/object#source_object) describing that bank account. + public var source: StripeSource? + /// Extra information about a top-up. This will appear on your source’s bank statement. It must contain at least one letter. + public var statementDescriptor: String? + /// The status of the top-up is either `canceled`, `failed`, `pending`, `reversed`, or `succeeded`. + public var status: StripeTopUpStatus? + /// A string that identifies this top-up as part of a group. + public var transferGroup: String? + + private enum CodingKeys: String, CodingKey { + case id + case object + case amount + case balanceTransaction = "balance_transaction" + case created + case currency + case description + case expectedAvailabilityDate = "expected_availability_date" + case failureCode = "failure_code" + case failureMessage = "failure_message" + case livemode + case metadata + case source + case statementDescriptor = "statement_descriptor" + case status + case transferGroup = "transfer_group" + } +} + +public enum StripeTopUpStatus: String, StripeModel { + case canceled + case failed + case pending + case reversed + case succeeded +} + +public struct StripeTopUpList: StripeModel { + public var object: String + public var hasMore: Bool + public var url: String? + public var data: [StripeTopUp]? + + private enum CodingKeys: String, CodingKey { + case object + case hasMore = "has_more" + case url + case data + } +} diff --git a/Sources/Stripe/Provider/Provider.swift b/Sources/Stripe/Provider/Provider.swift index 3a661fc..b676978 100644 --- a/Sources/Stripe/Provider/Provider.swift +++ b/Sources/Stripe/Provider/Provider.swift @@ -73,6 +73,7 @@ public final class StripeClient: Service { public var applicationFeeRefunds: ApplicationFeeRefundRoutes public var externalAccounts: ExternalAccountsRoutes public var countrySpecs: CountrySpecRoutes + public var topup: TopUpRoutes internal init(apiKey: String, testKey: String?, client: Client) { let apiRequest = StripeAPIRequest(httpClient: client, apiKey: apiKey, testApiKey: testKey) @@ -106,5 +107,6 @@ public final class StripeClient: Service { applicationFeeRefunds = StripeApplicationFeeRefundRoutes(request: apiRequest) externalAccounts = StripeExternalAccountsRoutes(request: apiRequest) countrySpecs = StripeCountrySpecRoutes(request: apiRequest) + topup = StripeTopUpRoutes(request: apiRequest) } } diff --git a/Tests/StripeTests/TopUpTests.swift b/Tests/StripeTests/TopUpTests.swift new file mode 100644 index 0000000..aa5d09f --- /dev/null +++ b/Tests/StripeTests/TopUpTests.swift @@ -0,0 +1,52 @@ +// +// TopUpTests.swift +// StripeTests +// +// Created by Andrew Edwards on 3/24/19. +// + +import XCTest +@testable import Stripe +@testable import Vapor + +class TopUpTests: XCTestCase { + let topupString = """ +{ + "id": "tu_123456789", + "object": "topup", + "amount": 1000, + "balance_transaction": null, + "created": 123456789, + "currency": "usd", + "description": "Top-up description", + "expected_availability_date": 123456789, + "failure_code": "sorry", + "failure_message": "we're sorry", + "livemode": false, + "metadata": { + "order_id": "12345678" + }, + "source": null, + "statement_descriptor": null, + "status": "pending", + "transfer_group": null +} +""" + + func testTopUpParsesProperly() throws { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + let body = HTTPBody(string: topupString) + var headers: HTTPHeaders = [:] + headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) + let request = HTTPRequest(headers: headers, body: body) + let topup = try decoder.decode(StripeTopUp.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() + + XCTAssertEqual(topup.currency, .usd) + XCTAssertEqual(topup.expectedAvailabilityDate, Date(timeIntervalSince1970: 123456789)) + XCTAssertEqual(topup.failureCode, "sorry") + XCTAssertEqual(topup.failureMessage, "we're sorry") + XCTAssertEqual(topup.metadata?["order_id"], "12345678") + } +} diff --git a/Tests/StripeTests/XCTestManifests.swift b/Tests/StripeTests/XCTestManifests.swift index d25c25d..be8b652 100644 --- a/Tests/StripeTests/XCTestManifests.swift +++ b/Tests/StripeTests/XCTestManifests.swift @@ -26,6 +26,12 @@ extension ChargeTests { ] } +extension CountrySpecTests { + static let __allTests = [ + ("testCountrySpecParsesProperly", testCountrySpecParsesProperly), + ] +} + extension CustomerTests { static let __allTests = [ ("testCustomerParsedProperly", testCustomerParsedProperly), @@ -136,6 +142,12 @@ extension TokenTests { ] } +extension TopUpTests { + static let __allTests = [ + ("testTopUpParsesProperly", testTopUpParsesProperly), + ] +} + extension TransferTests { static let __allTests = [ ("testTransferParsedProperly", testTransferParsedProperly), @@ -149,6 +161,7 @@ public func __allTests() -> [XCTestCaseEntry] { testCase(ApplicationFeeTests.__allTests), testCase(BalanceTests.__allTests), testCase(ChargeTests.__allTests), + testCase(CountrySpecTests.__allTests), testCase(CustomerTests.__allTests), testCase(DisputeTests.__allTests), testCase(EphemeralKeyTests.__allTests), @@ -165,6 +178,7 @@ public func __allTests() -> [XCTestCaseEntry] { testCase(SourceTests.__allTests), testCase(SubscriptionTests.__allTests), testCase(TokenTests.__allTests), + testCase(TopUpTests.__allTests), testCase(TransferTests.__allTests), ] } From c0b6b093e20ffd2955dd05dfcd5004f27679e94b Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Fri, 14 Jun 2019 19:30:27 -0400 Subject: [PATCH 09/14] Implemented provider for Vapor 4. --- Package.swift | 9 +- README.md | 108 +-- Sources/Stripe/API/Helpers/Endpoints.swift | 254 ------ Sources/Stripe/API/Routes/AccountRoutes.swift | 313 ------- .../Routes/ApplicationFeeRefundRoutes.swift | 116 --- .../API/Routes/ApplicationFeesRoutes.swift | 54 -- Sources/Stripe/API/Routes/BalanceRoutes.swift | 59 -- Sources/Stripe/API/Routes/ChargeRoutes.swift | 282 ------ .../Stripe/API/Routes/CountrySpecRoutes.swift | 54 -- Sources/Stripe/API/Routes/CouponRoutes.swift | 145 ---- .../Stripe/API/Routes/CustomerRoutes.swift | 321 ------- Sources/Stripe/API/Routes/DisputeRoutes.swift | 85 -- .../API/Routes/EphemeralKeyRoutes.swift | 47 - .../API/Routes/ExternalAccountsRoutes.swift | 383 -------- .../Stripe/API/Routes/FileLinkRoutes.swift | 109 --- Sources/Stripe/API/Routes/FileRoutes.swift | 102 --- .../Stripe/API/Routes/InvoiceItemRoutes.swift | 159 ---- Sources/Stripe/API/Routes/InvoiceRoutes.swift | 258 ------ .../Stripe/API/Routes/OrderReturnRoutes.swift | 49 -- Sources/Stripe/API/Routes/OrderRoutes.swift | 233 ----- Sources/Stripe/API/Routes/PayoutRoutes.swift | 136 --- Sources/Stripe/API/Routes/PersonRoutes.swift | 350 -------- Sources/Stripe/API/Routes/PlanRoutes.swift | 154 ---- Sources/Stripe/API/Routes/ProductRoutes.swift | 273 ------ Sources/Stripe/API/Routes/RefundRoutes.swift | 116 --- Sources/Stripe/API/Routes/SKURoutes.swift | 205 ----- Sources/Stripe/API/Routes/SourceRoutes.swift | 161 ---- .../API/Routes/SubscriptionItemRoutes.swift | 173 ---- .../API/Routes/SubscriptionRoutes.swift | 312 ------- Sources/Stripe/API/Routes/TokenRoutes.swift | 114 --- Sources/Stripe/API/Routes/TopUpRoutes.swift | 166 ---- .../API/Routes/TransferReversalRoutes.swift | 112 --- .../Stripe/API/Routes/TransferRoutes.swift | 106 --- Sources/Stripe/API/StripeRequest.swift | 80 -- Sources/Stripe/Errors/StripeError.swift | 217 ----- .../Stripe/Helpers/AccountRejectReason.swift | 13 - Sources/Stripe/Helpers/ActionType.swift | 13 - Sources/Stripe/Helpers/CodeVerification.swift | 16 - Sources/Stripe/Helpers/InventoryType.swift | 21 - Sources/Stripe/Helpers/StripeCurrency.swift | 111 --- Sources/Stripe/Helpers/StripeDuration.swift | 32 - .../Stripe/Helpers/StripePlanInterval.swift | 16 - Sources/Stripe/Helpers/StripeStatus.swift | 43 - Sources/Stripe/Models/Balance/Balance.swift | 28 - .../Models/Balance/BalanceHistoryList.swift | 28 - .../Balance/BalanceTransactionItem.swift | 48 -- .../Balance/BalanceTransactionType.swift | 32 - .../Models/Balance/BalanceTransfer.swift | 24 - Sources/Stripe/Models/Balance/Fee.swift | 21 - .../Models/Balance/SourceBalanceType.swift | 12 - Sources/Stripe/Models/Charges/Charge.swift | 103 --- .../Stripe/Models/Charges/ChargeList.swift | 28 - .../Stripe/Models/Charges/FruadDetails.swift | 32 - Sources/Stripe/Models/Charges/Outcome.swift | 53 -- Sources/Stripe/Models/Charges/Review.swift | 23 - .../Stripe/Models/Charges/ReviewReason.swift | 20 - Sources/Stripe/Models/Connect/Account.swift | 224 ----- .../Models/Connect/ApplicationFee.swift | 70 -- .../Models/Connect/ApplicationFeeRefund.swift | 52 -- .../Models/Connect/ConnectLoginLink.swift | 20 - .../Stripe/Models/Connect/CountrySpec.swift | 66 -- .../Models/Connect/ExternalAccounts.swift | 46 - .../Models/Connect/PayoutSchedule.swift | 26 - Sources/Stripe/Models/Connect/Person.swift | 166 ---- .../Connect/StripeConnectedAccountType.swift | 18 - .../Stripe/Models/Connect/TOSAcceptance.swift | 26 - Sources/Stripe/Models/Connect/TopUp.swift | 84 -- Sources/Stripe/Models/Connect/Transfer.swift | 53 -- .../Stripe/Models/Connect/TransferList.swift | 29 - .../Models/Connect/TransferReversal.swift | 35 - .../Models/Connect/TransferReversalList.swift | 27 - Sources/Stripe/Models/Coupons/Coupon.swift | 48 -- .../Stripe/Models/Coupons/CouponList.swift | 28 - Sources/Stripe/Models/Coupons/Discount.swift | 24 - Sources/Stripe/Models/Customer/Customer.swift | 93 -- .../Stripe/Models/Customer/CustomerList.swift | 28 - Sources/Stripe/Models/Dispute/Dispute.swift | 47 - .../Models/Dispute/DisputeEvidence.swift | 71 -- .../Dispute/DisputeEvidenceDetails.swift | 27 - .../Stripe/Models/Dispute/DisputeList.swift | 28 - .../Stripe/Models/Dispute/DisputeReason.swift | 36 - .../Models/EphemeralKey/EphemeralKey.swift | 28 - Sources/Stripe/Models/Files/FileLink.swift | 42 - .../Stripe/Models/Files/FileLinkList.swift | 22 - Sources/Stripe/Models/Files/FileUpload.swift | 50 -- .../Stripe/Models/Files/FileUploadList.swift | 22 - .../Models/Invoices/BillingReason.swift | 18 - Sources/Stripe/Models/Invoices/Invoice.swift | 108 --- .../Stripe/Models/Invoices/InvoiceItem.swift | 56 -- .../Models/Invoices/InvoiceItemList.swift | 28 - .../Models/Invoices/InvoiceLineGroup.swift | 28 - .../Models/Invoices/InvoiceLineItem.swift | 50 -- .../Stripe/Models/Invoices/InvoiceList.swift | 27 - Sources/Stripe/Models/Invoices/Period.swift | 13 - .../Models/Orders/DeliveryEstimateType.swift | 15 - Sources/Stripe/Models/Orders/Order.swift | 66 -- Sources/Stripe/Models/Orders/OrderItem.swift | 22 - .../Stripe/Models/Orders/OrderItemType.swift | 14 - Sources/Stripe/Models/Orders/OrderList.swift | 28 - .../Stripe/Models/Orders/OrderReturn.swift | 26 - .../Models/Orders/OrderReturnList.swift | 28 - .../Stripe/Models/Orders/OrderStatus.swift | 15 - .../Stripe/Models/Other/DeletedObject.swift | 20 - Sources/Stripe/Models/Payouts/Payout.swift | 59 -- .../Stripe/Models/Payouts/PayoutEnums.swift | 48 -- .../Stripe/Models/Payouts/PayoutsList.swift | 27 - .../Stripe/Models/Plans/BillingScheme.swift | 51 -- Sources/Stripe/Models/Plans/Plans.swift | 58 -- Sources/Stripe/Models/Plans/PlansList.swift | 28 - .../Models/Products/PackageDimensions.swift | 21 - Sources/Stripe/Models/Products/Product.swift | 56 -- .../Stripe/Models/Products/ProductType.swift | 13 - .../Stripe/Models/Products/ProductsList.swift | 28 - Sources/Stripe/Models/Refunds/Refund.swift | 46 - .../Stripe/Models/Refunds/RefundList.swift | 28 - .../Stripe/Models/Refunds/RefundReason.swift | 18 - Sources/Stripe/Models/SKU/Inventory.swift | 18 - Sources/Stripe/Models/SKU/SKU.swift | 48 -- Sources/Stripe/Models/SKU/SKUList.swift | 28 - .../Models/Shipping/DeliveryEstimate.swift | 19 - .../Shipping/OrderStatusTransitions.swift | 21 - .../Models/Shipping/ShippingLabel.swift | 28 - .../Models/Shipping/ShippingMethod.swift | 28 - .../Models/Shipping/StripeAddress.swift | 30 - .../Stripe/Models/Sources/BankAccount.swift | 90 -- Sources/Stripe/Models/Sources/Card.swift | 145 ---- Sources/Stripe/Models/Sources/Flow.swift | 18 - Sources/Stripe/Models/Sources/Mandate.swift | 21 - .../Stripe/Models/Sources/OtherSources.swift | 161 ---- Sources/Stripe/Models/Sources/Owner.swift | 34 - .../Stripe/Models/Sources/PaymentSource.swift | 98 --- Sources/Stripe/Models/Sources/Receiver.swift | 30 - Sources/Stripe/Models/Sources/Source.swift | 131 --- .../Stripe/Models/Sources/SourceList.swift | 43 - .../Models/Sources/SourceRedirect.swift | 20 - .../Stripe/Models/Sources/SourceType.swift | 25 - Sources/Stripe/Models/StripeModel.swift | 123 --- .../StripeSubscriptionsList.swift | 28 - .../Models/Subscriptions/Subscription.swift | 68 -- .../Subscriptions/SubscriptionItem.swift | 34 - .../Subscriptions/SubscriptionItemsList.swift | 28 - Sources/Stripe/Models/Tokens/Token.swift | 38 - Sources/Stripe/Models/Tokens/TokenType.swift | 16 - Sources/Stripe/Provider/Provider.swift | 112 --- Sources/Stripe/StripeProvider.swift | 27 + Tests/LinuxMain.swift | 2 - Tests/StripeTests/AccountTests.swift | 332 ------- Tests/StripeTests/ApplicationFeeTests.swift | 111 --- Tests/StripeTests/BalanceTests.swift | 180 ---- Tests/StripeTests/ChargeTests.swift | 133 --- Tests/StripeTests/CountrySpecTests.swift | 102 --- Tests/StripeTests/CustomerTests.swift | 78 -- Tests/StripeTests/DisputeTests.swift | 132 --- Tests/StripeTests/EphemeralKeyTests.swift | 55 -- Tests/StripeTests/ErrorTests.swift | 53 -- Tests/StripeTests/FileTests.swift | 124 --- Tests/StripeTests/InvoiceTests.swift | 206 ----- Tests/StripeTests/OrderTests.swift | 160 ---- Tests/StripeTests/PaymentSourceTests.swift | 145 ---- Tests/StripeTests/PayoutTests.swift | 73 -- Tests/StripeTests/ProductTests.swift | 90 -- Tests/StripeTests/ProviderTests.swift | 1 - Tests/StripeTests/QueryEncodingTests.swift | 26 - Tests/StripeTests/RefundTests.swift | 64 -- Tests/StripeTests/SKUTests.swift | 89 -- Tests/StripeTests/SourceTests.swift | 814 ------------------ Tests/StripeTests/SubscriptionTests.swift | 295 ------- Tests/StripeTests/TokenTests.swift | 180 ---- Tests/StripeTests/TopUpTests.swift | 52 -- Tests/StripeTests/TransferTests.swift | 106 --- Tests/StripeTests/XCTestManifests.swift | 178 +--- 171 files changed, 46 insertions(+), 14356 deletions(-) delete mode 100644 Sources/Stripe/API/Helpers/Endpoints.swift delete mode 100644 Sources/Stripe/API/Routes/AccountRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/BalanceRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/ChargeRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/CountrySpecRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/CouponRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/CustomerRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/DisputeRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/EphemeralKeyRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/FileLinkRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/FileRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/InvoiceItemRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/InvoiceRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/OrderReturnRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/OrderRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/PayoutRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/PersonRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/PlanRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/ProductRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/RefundRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/SKURoutes.swift delete mode 100644 Sources/Stripe/API/Routes/SourceRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/SubscriptionItemRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/SubscriptionRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/TokenRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/TopUpRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/TransferReversalRoutes.swift delete mode 100644 Sources/Stripe/API/Routes/TransferRoutes.swift delete mode 100644 Sources/Stripe/API/StripeRequest.swift delete mode 100644 Sources/Stripe/Errors/StripeError.swift delete mode 100644 Sources/Stripe/Helpers/AccountRejectReason.swift delete mode 100644 Sources/Stripe/Helpers/ActionType.swift delete mode 100644 Sources/Stripe/Helpers/CodeVerification.swift delete mode 100644 Sources/Stripe/Helpers/InventoryType.swift delete mode 100644 Sources/Stripe/Helpers/StripeCurrency.swift delete mode 100644 Sources/Stripe/Helpers/StripeDuration.swift delete mode 100644 Sources/Stripe/Helpers/StripePlanInterval.swift delete mode 100644 Sources/Stripe/Helpers/StripeStatus.swift delete mode 100644 Sources/Stripe/Models/Balance/Balance.swift delete mode 100644 Sources/Stripe/Models/Balance/BalanceHistoryList.swift delete mode 100644 Sources/Stripe/Models/Balance/BalanceTransactionItem.swift delete mode 100644 Sources/Stripe/Models/Balance/BalanceTransactionType.swift delete mode 100644 Sources/Stripe/Models/Balance/BalanceTransfer.swift delete mode 100644 Sources/Stripe/Models/Balance/Fee.swift delete mode 100644 Sources/Stripe/Models/Balance/SourceBalanceType.swift delete mode 100644 Sources/Stripe/Models/Charges/Charge.swift delete mode 100644 Sources/Stripe/Models/Charges/ChargeList.swift delete mode 100644 Sources/Stripe/Models/Charges/FruadDetails.swift delete mode 100644 Sources/Stripe/Models/Charges/Outcome.swift delete mode 100644 Sources/Stripe/Models/Charges/Review.swift delete mode 100644 Sources/Stripe/Models/Charges/ReviewReason.swift delete mode 100644 Sources/Stripe/Models/Connect/Account.swift delete mode 100644 Sources/Stripe/Models/Connect/ApplicationFee.swift delete mode 100644 Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift delete mode 100644 Sources/Stripe/Models/Connect/ConnectLoginLink.swift delete mode 100644 Sources/Stripe/Models/Connect/CountrySpec.swift delete mode 100644 Sources/Stripe/Models/Connect/ExternalAccounts.swift delete mode 100644 Sources/Stripe/Models/Connect/PayoutSchedule.swift delete mode 100644 Sources/Stripe/Models/Connect/Person.swift delete mode 100644 Sources/Stripe/Models/Connect/StripeConnectedAccountType.swift delete mode 100644 Sources/Stripe/Models/Connect/TOSAcceptance.swift delete mode 100644 Sources/Stripe/Models/Connect/TopUp.swift delete mode 100644 Sources/Stripe/Models/Connect/Transfer.swift delete mode 100644 Sources/Stripe/Models/Connect/TransferList.swift delete mode 100644 Sources/Stripe/Models/Connect/TransferReversal.swift delete mode 100644 Sources/Stripe/Models/Connect/TransferReversalList.swift delete mode 100644 Sources/Stripe/Models/Coupons/Coupon.swift delete mode 100644 Sources/Stripe/Models/Coupons/CouponList.swift delete mode 100644 Sources/Stripe/Models/Coupons/Discount.swift delete mode 100644 Sources/Stripe/Models/Customer/Customer.swift delete mode 100644 Sources/Stripe/Models/Customer/CustomerList.swift delete mode 100644 Sources/Stripe/Models/Dispute/Dispute.swift delete mode 100644 Sources/Stripe/Models/Dispute/DisputeEvidence.swift delete mode 100644 Sources/Stripe/Models/Dispute/DisputeEvidenceDetails.swift delete mode 100644 Sources/Stripe/Models/Dispute/DisputeList.swift delete mode 100644 Sources/Stripe/Models/Dispute/DisputeReason.swift delete mode 100644 Sources/Stripe/Models/EphemeralKey/EphemeralKey.swift delete mode 100644 Sources/Stripe/Models/Files/FileLink.swift delete mode 100644 Sources/Stripe/Models/Files/FileLinkList.swift delete mode 100644 Sources/Stripe/Models/Files/FileUpload.swift delete mode 100644 Sources/Stripe/Models/Files/FileUploadList.swift delete mode 100644 Sources/Stripe/Models/Invoices/BillingReason.swift delete mode 100644 Sources/Stripe/Models/Invoices/Invoice.swift delete mode 100644 Sources/Stripe/Models/Invoices/InvoiceItem.swift delete mode 100644 Sources/Stripe/Models/Invoices/InvoiceItemList.swift delete mode 100644 Sources/Stripe/Models/Invoices/InvoiceLineGroup.swift delete mode 100644 Sources/Stripe/Models/Invoices/InvoiceLineItem.swift delete mode 100644 Sources/Stripe/Models/Invoices/InvoiceList.swift delete mode 100644 Sources/Stripe/Models/Invoices/Period.swift delete mode 100644 Sources/Stripe/Models/Orders/DeliveryEstimateType.swift delete mode 100644 Sources/Stripe/Models/Orders/Order.swift delete mode 100644 Sources/Stripe/Models/Orders/OrderItem.swift delete mode 100644 Sources/Stripe/Models/Orders/OrderItemType.swift delete mode 100644 Sources/Stripe/Models/Orders/OrderList.swift delete mode 100644 Sources/Stripe/Models/Orders/OrderReturn.swift delete mode 100644 Sources/Stripe/Models/Orders/OrderReturnList.swift delete mode 100644 Sources/Stripe/Models/Orders/OrderStatus.swift delete mode 100644 Sources/Stripe/Models/Other/DeletedObject.swift delete mode 100644 Sources/Stripe/Models/Payouts/Payout.swift delete mode 100644 Sources/Stripe/Models/Payouts/PayoutEnums.swift delete mode 100644 Sources/Stripe/Models/Payouts/PayoutsList.swift delete mode 100644 Sources/Stripe/Models/Plans/BillingScheme.swift delete mode 100644 Sources/Stripe/Models/Plans/Plans.swift delete mode 100644 Sources/Stripe/Models/Plans/PlansList.swift delete mode 100644 Sources/Stripe/Models/Products/PackageDimensions.swift delete mode 100644 Sources/Stripe/Models/Products/Product.swift delete mode 100644 Sources/Stripe/Models/Products/ProductType.swift delete mode 100644 Sources/Stripe/Models/Products/ProductsList.swift delete mode 100644 Sources/Stripe/Models/Refunds/Refund.swift delete mode 100644 Sources/Stripe/Models/Refunds/RefundList.swift delete mode 100644 Sources/Stripe/Models/Refunds/RefundReason.swift delete mode 100644 Sources/Stripe/Models/SKU/Inventory.swift delete mode 100644 Sources/Stripe/Models/SKU/SKU.swift delete mode 100644 Sources/Stripe/Models/SKU/SKUList.swift delete mode 100644 Sources/Stripe/Models/Shipping/DeliveryEstimate.swift delete mode 100644 Sources/Stripe/Models/Shipping/OrderStatusTransitions.swift delete mode 100644 Sources/Stripe/Models/Shipping/ShippingLabel.swift delete mode 100644 Sources/Stripe/Models/Shipping/ShippingMethod.swift delete mode 100644 Sources/Stripe/Models/Shipping/StripeAddress.swift delete mode 100644 Sources/Stripe/Models/Sources/BankAccount.swift delete mode 100644 Sources/Stripe/Models/Sources/Card.swift delete mode 100644 Sources/Stripe/Models/Sources/Flow.swift delete mode 100644 Sources/Stripe/Models/Sources/Mandate.swift delete mode 100644 Sources/Stripe/Models/Sources/OtherSources.swift delete mode 100644 Sources/Stripe/Models/Sources/Owner.swift delete mode 100644 Sources/Stripe/Models/Sources/PaymentSource.swift delete mode 100644 Sources/Stripe/Models/Sources/Receiver.swift delete mode 100644 Sources/Stripe/Models/Sources/Source.swift delete mode 100644 Sources/Stripe/Models/Sources/SourceList.swift delete mode 100644 Sources/Stripe/Models/Sources/SourceRedirect.swift delete mode 100644 Sources/Stripe/Models/Sources/SourceType.swift delete mode 100644 Sources/Stripe/Models/StripeModel.swift delete mode 100644 Sources/Stripe/Models/Subscriptions/StripeSubscriptionsList.swift delete mode 100644 Sources/Stripe/Models/Subscriptions/Subscription.swift delete mode 100644 Sources/Stripe/Models/Subscriptions/SubscriptionItem.swift delete mode 100644 Sources/Stripe/Models/Subscriptions/SubscriptionItemsList.swift delete mode 100644 Sources/Stripe/Models/Tokens/Token.swift delete mode 100644 Sources/Stripe/Models/Tokens/TokenType.swift delete mode 100644 Sources/Stripe/Provider/Provider.swift create mode 100644 Sources/Stripe/StripeProvider.swift delete mode 100644 Tests/StripeTests/AccountTests.swift delete mode 100644 Tests/StripeTests/ApplicationFeeTests.swift delete mode 100644 Tests/StripeTests/BalanceTests.swift delete mode 100644 Tests/StripeTests/ChargeTests.swift delete mode 100644 Tests/StripeTests/CountrySpecTests.swift delete mode 100644 Tests/StripeTests/CustomerTests.swift delete mode 100644 Tests/StripeTests/DisputeTests.swift delete mode 100644 Tests/StripeTests/EphemeralKeyTests.swift delete mode 100644 Tests/StripeTests/ErrorTests.swift delete mode 100644 Tests/StripeTests/FileTests.swift delete mode 100644 Tests/StripeTests/InvoiceTests.swift delete mode 100644 Tests/StripeTests/OrderTests.swift delete mode 100644 Tests/StripeTests/PaymentSourceTests.swift delete mode 100644 Tests/StripeTests/PayoutTests.swift delete mode 100644 Tests/StripeTests/ProductTests.swift delete mode 100644 Tests/StripeTests/ProviderTests.swift delete mode 100644 Tests/StripeTests/QueryEncodingTests.swift delete mode 100644 Tests/StripeTests/RefundTests.swift delete mode 100644 Tests/StripeTests/SKUTests.swift delete mode 100644 Tests/StripeTests/SourceTests.swift delete mode 100644 Tests/StripeTests/SubscriptionTests.swift delete mode 100644 Tests/StripeTests/TokenTests.swift delete mode 100644 Tests/StripeTests/TopUpTests.swift delete mode 100644 Tests/StripeTests/TransferTests.swift diff --git a/Package.swift b/Package.swift index 7753c3a..0be83ec 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:4.2 +// swift-tools-version:5.1 import PackageDescription let package = Package( @@ -7,10 +7,11 @@ let package = Package( .library(name: "Stripe", targets: ["Stripe"]) ], dependencies: [ - .package(url: "https://github.com/vapor/vapor.git", from: "3.3.0"), + .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-alpha"), + .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.0"), ], targets: [ - .target(name: "Stripe", dependencies: ["Vapor"]), - .testTarget(name: "StripeTests", dependencies: ["Vapor", "Stripe"]) + .target(name: "Stripe", dependencies: ["Vapor","StripeKit"]), + .testTarget(name: "StripeTests", dependencies: ["Vapor", "Stripe","StripeKit"]) ] ) diff --git a/README.md b/README.md index d57c26c..3cbe510 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,31 @@ -# Vapor Stripe Provider +# StripeProvider -![Swift](http://img.shields.io/badge/swift-4.1-brightgreen.svg) -![Vapor](http://img.shields.io/badge/vapor-3.0-brightgreen.svg) -[![CircleCI](https://circleci.com/gh/vapor-community/stripe-provider.svg?style=svg)](https://circleci.com/gh/vapor-community/stripe-provider) +![Swift](http://img.shields.io/badge/swift-5.1-brightgreen.svg) +![Vapor](http://img.shields.io/badge/vapor-4.0-brightgreen.svg) -[Stripe][stripe_home] is a payment platform that handles credit cards, bitcoin and ACH transfers. They have become one of the best platforms for handling payments for projects, services or products. -## Getting Started +### StripeProvider is a Vapor wrapper around [StripeKit](https://github.com/vapor-community/StripeKit) + +## Usage guide In your `Package.swift` file, add the following ~~~~swift -.package(url: "https://github.com/vapor-community/stripe-provider.git", from: "2.2.0") +.package(url: "https://github.com/vapor-community/stripe-provider.git", from: "3.0.0") ~~~~ -Register the config and the provider in `configure.swift` +Register the configuration and the provider in `configure.swift` ~~~~swift -let config = StripeConfig(productionKey: "sk_live_1234", testKey: "sk_test_1234") +import Stripe + +let stripeConfiguration = StripeConfiguration(apiKey: "sk_live_1234") services.register(config) try services.register(StripeProvider()) ~~~~ -And you are all set. Interacting with the API is quite easy from any route handler. +Now to make a charge ~~~~swift +import Stripe struct ChargeToken: Content { var stripeToken: String @@ -42,91 +45,6 @@ func chargeCustomer(_ req: Request) throws -> EventLoopFuture { } ~~~~ -And you can always check the documentation to see the required paramaters for specific API calls. - -## JS Stripe integration - -Also make sure to check out stripes documenation to add the client JS magic [here]( https://stripe.com/docs/checkout#integration-simple) or [here](https://stripe.com/docs/checkout#integration-custom) - -## Whats Implemented - -### Core Resources -* [x] Balance -* [x] Charges -* [x] Customers -* [x] Disputes -* [ ] Events -* [x] File Links -* [x] File Uploads -* [ ] PaymentIntents -* [x] Payouts -* [x] Products -* [x] Refunds -* [x] Tokens ---- -### Payment Methods -* [x] Bank Accounts -* [x] Cards -* [x] Sources ---- -### Checkout -* [ ] Sessions ---- -### Billing -* [x] Coupons -* [x] Discounts -* [x] Invoices -* [x] Invoice Items -* [x] Products -* [x] Plans -* [x] Subscriptions -* [x] Subscription items -* [ ] Usage Records ---- -### Connect -* [x] Account -* [x] Application Fee Refunds -* [x] Application Fees -* [x] Country Specs -* [x] External Accounts -* [x] Persons -* [x] Top-ups -* [x] Transfers -* [x] Transfer Reversals ---- -### Fraud -* [ ] Reviews -* [ ] Value Lists -* [ ] Value List Items ---- -### Issuing -* [ ] Authorizations -* [ ] Cardholders -* [ ] Cards -* [ ] Disputes -* [ ] Transactions ---- -### Terminal -* [ ] Connection Tokens -* [ ] Locations -* [ ] Readers ---- -### Orders -* [x] Orders -* [x] Order Items -* [x] Returns -* [x] SKUs -* [x] Ephemeral Keys ---- -### Sigma -* [ ] Scheduled Queries ---- -### Webhooks -* [ ] Webhook Endpoints - -[stripe_home]: http://stripe.com "Stripe" -[stripe_api]: https://stripe.com/docs/api "Stripe API Endpoints" - ## License Vapor Stripe Provider is available under the MIT license. See the [LICENSE](LICENSE) file for more info. diff --git a/Sources/Stripe/API/Helpers/Endpoints.swift b/Sources/Stripe/API/Helpers/Endpoints.swift deleted file mode 100644 index bb02fa7..0000000 --- a/Sources/Stripe/API/Helpers/Endpoints.swift +++ /dev/null @@ -1,254 +0,0 @@ -// -// Endpoints.swift -// Stripe -// -// Created by Anthony Castelli on 4/13/17. -// -// - -import Foundation - -internal let APIBase = "https://api.stripe.com/" -internal let FilesAPIBase = "https://files.stripe.com/" -internal let APIVersion = "v1/" - -internal enum StripeAPIEndpoint { - - // MARK: - BALANCE - case balance - case balanceHistory - case balanceHistoryTransaction(String) - - // MARK: - CHARGES - case charges - case charge(String) - case captureCharge(String) - - // MARK: - CUSTOMERS - case customers - case customer(String) - case customerSources(String) - case customerDetachSources(String,String) - case customerDiscount(String) - - // MARK: - TOKENS - case tokens - case token(String) - - // MARK: - REFUNDS - case refunds - case refund(String) - - // MARK: - COUPONS - case coupons - case coupon(String) - - // MARK: - PLANS - case plans - case plan(String) - - // MARK: - SOURCES - case sources - case source(String) - - // MARK: - SUBSCRIPTION ITEMS - case subscriptionItem - case subscriptionItems(String) - - // MARK: - SUBSCRIPTIONS - case subscription - case subscriptions(String) - case subscriptionDiscount(String) - - // MARK: - ACCOUNTS - case account - case accounts(String) - case accountsReject(String) - case accountsLoginLink(String) - - // MARK: - DISPUTES - case dispute - case disputes(String) - case closeDispute(String) - - // MARK: - SKUS - case sku - case skus(String) - - // MARK: - PRODUCTS - case product - case products(String) - - // MARK: - ORDERS - case order - case orders(String) - case ordersPay(String) - case ordersReturn(String) - - // MARK: - RETURNS - case orderReturn - case orderReturns(String) - - // MARK: - INVOICES - case invoices - case invoice(String) - case payInvoice(String) - case invoiceLines(String) - case upcomingInvoices - - // MARK: - INVOICE ITEMS - case invoiceItems - case invoiceItem(String) - - // MARK: - EPHEMERAL KEYS - case ephemeralKeys - case ephemeralKey(String) - - // MARK: - TRANSFERS - case transfer - case transfers(String) - case transferReversal(String) - case transfersReversal(String,String) - - // MARK: - PAYOUTS - case payout - case payouts(String) - case payoutsCancel(String) - - // MARK: - FILE LINKS - case fileLink - case fileLinks(String) - - // MARK: - FILE UPLOAD - case file - case files(String) - - // MARK: - PERSONS - case person(String) - case persons(String, String) - - case applicationFee - case applicationFees(String) - - case applicationFeeRefund(String) - case applicationFeeRefunds(String, String) - - case externalAccount(String) - case externalAccounts(String, String) - - case countrySpec - case countrySpecs(String) - - case topup - case topups(String) - case topupsCancel(String) - - var endpoint: String { - switch self { - case .balance: return APIBase + APIVersion + "balance" - case .balanceHistory: return APIBase + APIVersion + "balance/history" - case .balanceHistoryTransaction(let id): return APIBase + APIVersion + "balance/history/\(id)" - - case .charges: return APIBase + APIVersion + "charges" - case .charge(let id): return APIBase + APIVersion + "charges/\(id)" - case .captureCharge(let id): return APIBase + APIVersion + "charges/\(id)/capture" - - case .customers: return APIBase + APIVersion + "customers" - case .customer(let id): return APIBase + APIVersion + "customers/\(id)" - case .customerSources(let id): return APIBase + APIVersion + "customers/\(id)/sources" - case .customerDetachSources(let id, let src): return APIBase + APIVersion + "customers/\(id)/sources/\(src)" - case .customerDiscount(let id): return APIBase + APIVersion + "customers/\(id)/discount" - - case .tokens: return APIBase + APIVersion + "tokens" - case .token(let id): return APIBase + APIVersion + "tokens/\(id)" - - case .refunds: return APIBase + APIVersion + "refunds" - case .refund(let id): return APIBase + APIVersion + "refunds/\(id)" - - case .coupons: return APIBase + APIVersion + "coupons" - case .coupon(let id): return APIBase + APIVersion + "coupons/\(id)" - - case .plans: return APIBase + APIVersion + "plans" - case .plan(let id): return APIBase + APIVersion + "plans/\(id)" - - case .sources: return APIBase + APIVersion + "sources" - case .source(let id): return APIBase + APIVersion + "sources/\(id)" - - case .subscriptionItem: return APIBase + APIVersion + "subscription_items" - case .subscriptionItems(let id): return APIBase + APIVersion + "subscription_items/\(id)" - - case .subscription: return APIBase + APIVersion + "subscriptions" - case .subscriptions(let id): return APIBase + APIVersion + "subscriptions/\(id)" - case .subscriptionDiscount(let id): return APIBase + APIVersion + "subscriptions/\(id)/discount" - - case .account: return APIBase + APIVersion + "accounts" - case .accounts(let id): return APIBase + APIVersion + "accounts/\(id)" - case .accountsReject(let id): return APIBase + APIVersion + "accounts/\(id)/reject" - case .accountsLoginLink(let id): return APIBase + APIVersion + "accounts/\(id)/login_links" - - case .dispute: return APIBase + APIVersion + "disputes" - case .disputes(let id): return APIBase + APIVersion + "disputes/\(id)" - case .closeDispute(let id): return APIBase + APIVersion + "disputes/\(id)/close" - - case .sku: return APIBase + APIVersion + "skus" - case .skus(let id): return APIBase + APIVersion + "skus/\(id)" - - case .product: return APIBase + APIVersion + "products" - case .products(let id): return APIBase + APIVersion + "products/\(id)" - - case .order: return APIBase + APIVersion + "orders" - case .orders(let id): return APIBase + APIVersion + "orders/\(id)" - case .ordersPay(let id): return APIBase + APIVersion + "orders/\(id)/pay" - case .ordersReturn(let id): return APIBase + APIVersion + "orders/\(id)/returns" - - case .orderReturn: return APIBase + APIVersion + "order_returns" - case .orderReturns(let id): return APIBase + APIVersion + "order_returns/\(id)" - - case .invoices: return APIBase + APIVersion + "invoices" - case .invoice(let id): return APIBase + APIVersion + "invoices/\(id)" - case .payInvoice(let id): return APIBase + APIVersion + "invoices/\(id)/pay" - case .invoiceLines(let id): return APIBase + APIVersion + "invoices/\(id)/lines" - case .upcomingInvoices: return APIBase + APIVersion + "invoices/upcoming" - - case .invoiceItems: return APIBase + APIVersion + "invoiceitems" - case .invoiceItem(let id): return APIBase + APIVersion + "invoiceitems/\(id)" - - case .ephemeralKeys: return APIBase + APIVersion + "ephemeral_keys" - case .ephemeralKey(let id): return APIBase + APIVersion + "ephemeral_keys/\(id)" - - case .transfer: return APIBase + APIVersion + "transfers" - case .transfers(let id): return APIBase + APIVersion + "transfers/\(id)" - case .transferReversal(let id): return APIBase + APIVersion + "transfers/\(id)/reversals" - case .transfersReversal(let transfer, let reversal): return APIBase + APIVersion + "transfers/\(transfer)/reversals/\(reversal)" - - case .payout: return APIBase + APIVersion + "payouts" - case .payouts(let id): return APIBase + APIVersion + "payouts/\(id)" - case .payoutsCancel(let id): return APIBase + APIVersion + "payouts/\(id)/cancel" - - case .fileLink: return APIBase + APIVersion + "file_links" - case .fileLinks(let id): return APIBase + APIVersion + "file_links/\(id)" - - case .file: return FilesAPIBase + APIVersion + "files" - case .files(let id): return FilesAPIBase + APIVersion + "files/\(id)" - - case .person(let account): return APIBase + APIVersion + "accounts/\(account)/persons" - case .persons(let account, let person): return APIBase + APIVersion + "accounts/\(account)/persons/\(person)" - - case .applicationFee: return APIBase + APIVersion + "application_fees" - case .applicationFees(let fee): return APIBase + APIVersion + "application_fees/\(fee)" - - case .applicationFeeRefund(let fee): return APIBase + APIVersion + "application_fees/\(fee)/refunds" - case .applicationFeeRefunds(let fee, let refund): return APIBase + APIVersion + "application_fees/\(fee)/refunds/\(refund)" - - case . externalAccount(let account): return APIBase + APIVersion + "accounts/\(account)/external_accounts" - case . externalAccounts(let account, let id): return APIBase + APIVersion + "accounts/\(account)/external_accounts/\(id)" - - case .countrySpec: return APIBase + APIVersion + "country_specs" - case .countrySpecs(let country): return APIBase + APIVersion + "country_specs/\(country)" - - case .topup: return APIBase + APIVersion + "topups" - case .topups(let id): return APIBase + APIVersion + "topups/\(id)" - case .topupsCancel(let id): return APIBase + APIVersion + "topups/\(id)/cancel" - } - } -} diff --git a/Sources/Stripe/API/Routes/AccountRoutes.swift b/Sources/Stripe/API/Routes/AccountRoutes.swift deleted file mode 100644 index 8f47f22..0000000 --- a/Sources/Stripe/API/Routes/AccountRoutes.swift +++ /dev/null @@ -1,313 +0,0 @@ -// -// AccountRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 7/8/17. -// -// - -import Vapor - -public protocol AccountRoutes { - func create(type: StripeConnectAccountType, - country: String?, - email: String?, - accountToken: String?, - businessProfile: [String: Any]?, - businessType: StripeConnectAccountBusinessType?, - company: [String: Any]?, - defaultCurrency: StripeCurrency?, - externalAccount: Any?, - individual: [String: Any]?, - metadata: [String: String]?, - requestedCapabilities: [String]?, - settings: [String: Any]?, - tosAcceptance: [String: Any]?) throws -> Future - func retrieve(account: String) throws -> Future - func update(account accountId: String, - accountToken: String?, - businessProfile: [String: Any]?, - businessType: StripeConnectAccountBusinessType?, - company: [String: Any]?, - defaultCurrency: StripeCurrency?, - email: String?, - externalAccount: Any?, - individual: [String: Any]?, - metadata: [String: String]?, - requestedCapabilities: [String]?, - settings: [String: Any]?, - tosAcceptance: [String: Any]?) throws -> Future - func delete(account: String) throws -> Future - func reject(account: String, for: AccountRejectReason) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future - func createLoginLink(for: String) throws -> Future -} - -extension AccountRoutes { - public func create(type: StripeConnectAccountType, - country: String? = nil, - email: String? = nil, - accountToken: String? = nil, - businessProfile: [String: Any]? = nil, - businessType: StripeConnectAccountBusinessType? = nil, - company: [String: Any]? = nil, - defaultCurrency: StripeCurrency? = nil, - externalAccount: Any? = nil, - individual: [String: Any]? = nil, - metadata: [String: String]? = nil, - requestedCapabilities: [String]? = nil, - settings: [String: Any]? = nil, - tosAcceptance: [String: Any]? = nil) throws -> Future { - return try create(type: type, - country: country, - email: email, - accountToken: accountToken, - businessProfile: businessProfile, - businessType: businessType, - company: company, - defaultCurrency: defaultCurrency, - externalAccount: externalAccount, - individual: individual, - metadata: metadata, - requestedCapabilities: requestedCapabilities, - settings: settings, - tosAcceptance: tosAcceptance) - } - - public func retrieve(account: String) throws -> Future { - return try retrieve(account: account) - } - - public func update(account accountId: String, - accountToken: String? = nil, - businessProfile: [String: Any]? = nil, - businessType: StripeConnectAccountBusinessType? = nil, - company: [String: Any]? = nil, - defaultCurrency: StripeCurrency? = nil, - email: String? = nil, - externalAccount: Any? = nil, - individual: [String: Any]? = nil, - metadata: [String: String]? = nil, - requestedCapabilities: [String]? = nil, - settings: [String: Any]? = nil, - tosAcceptance: [String: Any]? = nil) throws -> Future { - return try update(account: accountId, - accountToken: accountToken, - businessProfile: businessProfile, - businessType: businessType, - company: company, - defaultCurrency: defaultCurrency, - email: email, - externalAccount: externalAccount, - individual: individual, - metadata: metadata, - requestedCapabilities: requestedCapabilities, - settings: settings, - tosAcceptance: tosAcceptance) - } - - public func delete(account: String) throws -> Future { - return try delete(account: account) - } - - public func reject(account: String, for: AccountRejectReason) throws -> Future { - return try reject(account: account, for: `for`) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - public func createLoginLink(for: String) throws -> Future { - return try createLoginLink(for: `for`) - } -} - -public struct StripeConnectAccountRoutes: AccountRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create an account - /// [Learn More →](https://stripe.com/docs/api/curl#create_account) - public func create(type: StripeConnectAccountType, - country: String?, - email: String?, - accountToken: String?, - businessProfile: [String: Any]?, - businessType: StripeConnectAccountBusinessType?, - company: [String: Any]?, - defaultCurrency: StripeCurrency?, - externalAccount: Any?, - individual: [String: Any]?, - metadata: [String: String]?, - requestedCapabilities: [String]?, - settings: [String: Any]?, - tosAcceptance: [String: Any]?) throws -> Future { - var body: [String: Any] = [:] - body["type"] = type.rawValue - - if let country = country { - body["country"] = country - } - - if let email = email { - body["email"] = email - } - - if let accountToken = accountToken { - body["account_token"] = accountToken - } - - if let businessProfile = businessProfile { - businessProfile.forEach { body["business_profile[\($0)]"] = $1 } - } - - if let businessType = businessType { - body["business_type"] = businessType.rawValue - } - - if let company = company { - company.forEach { body["company[\($0)]"] = $1 } - } - - if let currency = defaultCurrency { - body["default_currency"] = currency.rawValue - } - - if let externalAccountToken = externalAccount as? String { - body["external_account"] = externalAccountToken - } else if let externalHashAccount = externalAccount as? [String: Any] { - externalHashAccount.forEach { body["external_account[\($0)]"] = $1 } - } - - if let individual = individual { - individual.forEach { body["individual[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let requestedCapabilities = requestedCapabilities { - body["requested_capabilities"] = requestedCapabilities - } - - if let settings = settings { - settings.forEach { body["settings[\($0)]"] = $1 } - } - - if let tos = tosAcceptance { - tos.forEach { body["tos_acceptance[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.account.endpoint, body: body.queryParameters) - } - - /// Retrieve account details - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_account) - public func retrieve(account accountId: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.accounts(accountId).endpoint) - } - - /// Update an account - /// [Learn More →](https://stripe.com/docs/api/curl#update_account) - public func update(account accountId: String, - accountToken: String?, - businessProfile: [String: Any]?, - businessType: StripeConnectAccountBusinessType?, - company: [String: Any]?, - defaultCurrency: StripeCurrency?, - email: String?, - externalAccount: Any?, - individual: [String: Any]?, - metadata: [String: String]?, - requestedCapabilities: [String]?, - settings: [String: Any]?, - tosAcceptance: [String: Any]?) throws -> Future { - var body: [String: Any] = [:] - - if let accountToken = accountToken { - body["account_token"] = accountToken - } - - if let businessProfile = businessProfile { - businessProfile.forEach { body["business_profile[\($0)]"] = $1 } - } - - if let businessType = businessType { - body["business_type"] = businessType.rawValue - } - - if let company = company { - company.forEach { body["company[\($0)]"] = $1 } - } - - if let currency = defaultCurrency { - body["default_currency"] = currency.rawValue - } - - if let email = email { - body["email"] = email - } - - if let externalAccountToken = externalAccount as? String { - body["external_account"] = externalAccountToken - } else if let externalHashAccount = externalAccount as? [String: Any] { - externalHashAccount.forEach { body["external_account[\($0)]"] = $1 } - } - - if let individual = individual { - individual.forEach { body["individual[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let requestedCapabilities = requestedCapabilities { - body["requested_capabilities"] = requestedCapabilities - } - - if let settings = settings { - settings.forEach { body["settings[\($0)]"] = $1 } - } - - if let tos = tosAcceptance { - tos.forEach { body["tos_acceptance[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.accounts(accountId).endpoint, body: body.queryParameters) - } - - /// Delete an account - /// [Learn More →](https://stripe.com/docs/api/curl#delete_account) - public func delete(account accountId: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.accounts(accountId).endpoint) - } - - /// Reject an account - /// [Learn More →](https://stripe.com/docs/api/curl#reject_account) - public func reject(account accountId: String, for rejectReason: AccountRejectReason) throws -> Future { - let body = ["reason": rejectReason.rawValue].queryParameters - return try request.send(method: .POST, path: StripeAPIEndpoint.accountsReject(accountId).endpoint, body: body) - } - - /// List all connected accounts - /// [Learn More →](https://stripe.com/docs/api/curl#list_accounts) - public func listAll(filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.account.endpoint, query: queryParams) - } - - /// Create a login link - /// [Learn More →](https://stripe.com/docs/api/curl#create_login_link) - public func createLoginLink(for accountId: String) throws -> Future { - return try request.send(method: .POST, path: StripeAPIEndpoint.accountsLoginLink(accountId).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift b/Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift deleted file mode 100644 index e241976..0000000 --- a/Sources/Stripe/API/Routes/ApplicationFeeRefundRoutes.swift +++ /dev/null @@ -1,116 +0,0 @@ -// -// ApplicationFeeRefundRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 3/17/19. -// - -import Vapor - -public protocol ApplicationFeeRefundRoutes { - /// Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account from which the fee was originally collected. - /// You can optionally refund only part of an application fee. You can do so multiple times, until the entire fee has been refunded. - /// Once entirely refunded, an application fee can’t be refunded again. This method will return an error when called on an already-refunded application fee, or when trying to refund more money than is left on an application fee. - /// - /// - Parameters: - /// - fee: The identifier of the application fee to be refunded. - /// - amount: A positive integer, in `cents`, representing how much of this fee to refund. Can refund only up to the remaining unrefunded amount of the fee. - /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. - /// - Returns: A `StripeApplicationFeeRefund`. - /// - Throws: A `StripeError`. - func create(fee: String, amount: Int?, metadata: [String: String]?) throws -> EventLoopFuture - - - /// By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee. - /// - /// - Parameters: - /// - refund: ID of refund to retrieve. - /// - fee: ID of the application fee refunded. - /// - Returns: A `StripeApplicationFeeRefund`. - /// - Throws: A `StripeError`. - func retrieve(refund: String, fee: String) throws -> EventLoopFuture - - - /// Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged. - /// This request only accepts metadata as an argument. - /// - /// - Parameters: - /// - refund: ID of refund to retrieve. - /// - fee: ID of the application fee refunded. - /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. - /// - Returns: A `StripeApplicationFeeRefund`. - /// - Throws: A `StripeError`. - func update(refund: String, fee: String, metadata: [String: String]?) throws -> EventLoopFuture - - - /// You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page through additional refunds. - /// - /// - Parameters: - /// - fee: The ID of the application fee whose refunds will be retrieved. - /// - filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/fee_refunds/list) - /// - Returns: A `StripeApplicationFeeRefundList`. - /// - Throws: A `StripeError`. - func listAll(fee: String, filter: [String: Any]?) throws -> EventLoopFuture -} - -extension ApplicationFeeRefundRoutes { - public func create(fee: String, amount: Int? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { - return try create(fee: fee, amount: amount, metadata: metadata) - } - - public func retrieve(refund: String, fee: String) throws -> EventLoopFuture { - return try retrieve(refund: refund, fee: fee) - } - - public func update(refund: String, fee: String, metadata: [String: String]? = nil) throws -> EventLoopFuture { - return try update(refund: refund, fee: fee, metadata: metadata) - } - - public func listAll(fee: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { - return try listAll(fee: fee, filter: filter) - } -} - -public struct StripeApplicationFeeRefundRoutes: ApplicationFeeRefundRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func create(fee: String, amount: Int?, metadata: [String: String]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let amount = amount { - body["amount"] = amount - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.applicationFeeRefund(fee).endpoint, body: body.queryParameters) - } - - public func retrieve(refund: String, fee: String) throws -> EventLoopFuture { - return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFeeRefunds(fee, refund).endpoint) - } - - public func update(refund: String, fee: String, metadata: [String: String]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.applicationFeeRefunds(fee, refund).endpoint, body: body.queryParameters) - } - - public func listAll(fee: String, filter: [String: Any]?) throws -> EventLoopFuture { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFeeRefund(fee).endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift b/Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift deleted file mode 100644 index fa00023..0000000 --- a/Sources/Stripe/API/Routes/ApplicationFeesRoutes.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// ApplicationFeesRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 3/17/19. -// - -import Vapor - -public protocol ApplicationFeesRoutes { - /// Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee. - /// - /// - Parameter fee: The identifier of the fee to be retrieved. - /// - Returns: A `StripeApplicationFee`. - /// - Throws: A `StripeError`. - func retrieve(fee: String) throws -> EventLoopFuture - - /// Returns a list of application fees you’ve previously collected. The application fees are returned in sorted order, with the most recent fees appearing first. - /// - /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/application_fees/list?lang=curl) - /// - Returns: A `StripeApplicationFeeList`. - /// - Throws: A `StripeError`. - func listAll(filter: [String: Any]?) throws -> EventLoopFuture -} - -extension ApplicationFeesRoutes { - public func retrieve(fee: String) throws -> EventLoopFuture { - return try retrieve(fee: fee) - } - - public func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture { - return try listAll(filter: filter) - } -} - -public struct StripeApplicationFeeRoutes: ApplicationFeesRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func retrieve(fee: String) throws -> EventLoopFuture { - return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFees(fee).endpoint) - } - - public func listAll(filter: [String: Any]?) throws -> EventLoopFuture { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.applicationFee.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/BalanceRoutes.swift b/Sources/Stripe/API/Routes/BalanceRoutes.swift deleted file mode 100644 index 7aeff27..0000000 --- a/Sources/Stripe/API/Routes/BalanceRoutes.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// BalanceRoutes.swift -// Stripe -// -// Created by Anthony Castelli on 4/13/17. -// -// - -import Vapor - -public protocol BalanceRoutes { - func retrieve() throws -> Future - func retrieve(forTransaction: String) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension BalanceRoutes { - public func retrieve() throws -> Future { - return try retrieve() - } - - public func retrieve(forTransaction: String) throws -> Future { - return try retrieve(forTransaction: forTransaction) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeBalanceRoutes: BalanceRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Retrieve balance - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_balance) - public func retrieve() throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.balance.endpoint) - } - - /// Retrieve a balance transaction - /// [Learn More →](https://stripe.com/docs/api/curl#balance_transaction_retrieve) - public func retrieve(forTransaction transactionId: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.balanceHistoryTransaction(transactionId).endpoint) - } - - /// List all balance history - /// [Learn More →](https://stripe.com/docs/api/curl#balance_history) - public func listAll(filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.balanceHistory.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/ChargeRoutes.swift b/Sources/Stripe/API/Routes/ChargeRoutes.swift deleted file mode 100644 index 82c1411..0000000 --- a/Sources/Stripe/API/Routes/ChargeRoutes.swift +++ /dev/null @@ -1,282 +0,0 @@ -// -// ChargeRoutes.swift -// Stripe -// -// Created by Anthony Castelli on 4/16/17. -// -// - -import Vapor - -public protocol ChargeRoutes { - func create(amount: Int, - currency: StripeCurrency, - applicationFeeAmount: Int?, - capture: Bool?, - customer: String?, - description: String?, - metadata: [String: String]?, - onBehalfOf: String?, - receiptEmail: String?, - shipping: [String: Any]?, - source: Any?, - statementDescriptor: String?, - transferData: [String: Any]?, - transferGroup: String?) throws -> Future - func retrieve(charge: String) throws -> Future - func update(charge: String, - customer: String?, - description: String?, - fraudDetails: [String: Any]?, - metadata: [String: String]?, - receiptEmail: String?, - shipping: [String: Any]?, - transferGroup: String?) throws -> Future - func capture(charge: String, amount: Int?, applicationFee: Int?, destinationAmount: Int?, receiptEmail: String?, statementDescriptor: String?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension ChargeRoutes { - public func create(amount: Int, - currency: StripeCurrency, - applicationFeeAmount: Int? = nil, - capture: Bool? = nil, - customer: String? = nil, - description: String? = nil, - metadata: [String: String]? = nil, - onBehalfOf: String? = nil, - receiptEmail: String? = nil, - shipping: [String: Any]? = nil, - source: Any? = nil, - statementDescriptor: String? = nil, - transferData: [String: Any]? = nil, - transferGroup: String? = nil) throws -> Future { - return try create(amount: amount, - currency: currency, - applicationFeeAmount: applicationFeeAmount, - capture: capture, - customer: customer, - description: description, - metadata: metadata, - onBehalfOf: onBehalfOf, - receiptEmail: receiptEmail, - shipping: shipping, - source: source, - statementDescriptor: statementDescriptor, - transferData: transferData, - transferGroup: transferGroup) - } - - public func retrieve(charge: String) throws -> Future { - return try retrieve(charge: charge) - } - - public func update(charge chargeId: String, - customer: String? = nil, - description: String? = nil, - fraudDetails: [String: Any]? = nil, - metadata: [String: String]? = nil, - receiptEmail: String? = nil, - shipping: [String: Any]? = nil, - transferGroup: String? = nil) throws -> Future { - return try update(charge: chargeId, - customer: customer, - description: description, - fraudDetails: fraudDetails, - metadata: metadata, - receiptEmail: receiptEmail, - shipping: shipping, - transferGroup: transferGroup) - } - - public func capture(charge: String, - amount: Int? = nil, - applicationFee: Int? = nil, - destinationAmount: Int? = nil, - receiptEmail: String? = nil, - statementDescriptor: String? = nil) throws -> Future { - return try capture(charge: charge, - amount: amount, - applicationFee: applicationFee, - destinationAmount: destinationAmount, - receiptEmail: receiptEmail, - statementDescriptor: statementDescriptor) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeChargeRoutes: ChargeRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a charge - /// [Learn More →](https://stripe.com/docs/api/curl#create_charge) - public func create(amount: Int, - currency: StripeCurrency, - applicationFeeAmount: Int?, - capture: Bool?, - customer: String?, - description: String?, - metadata: [String: String]?, - onBehalfOf: String?, - receiptEmail: String?, - shipping: [String: Any]?, - source: Any?, - statementDescriptor: String?, - transferData: [String: Any]?, - transferGroup: String?) throws -> Future { - var body: [String: Any] = ["amount": amount, "currency": currency.rawValue] - if let applicationFeeAmount = applicationFeeAmount { - body["application_fee_amount"] = applicationFeeAmount - } - - if let capture = capture { - body["capture"] = capture - } - - if let customer = customer { - body["customer"] = customer - } - - if let description = description { - body["description"] = description - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1} - } - - if let onBehalfOf = onBehalfOf { - body["on_behalf_of"] = onBehalfOf - } - - if let receiptEmail = receiptEmail { - body["receipt_email"] = receiptEmail - } - - if let shipping = shipping { - shipping.forEach { body["shipping[\($0)]"] = $1 } - } - - if let tokenSource = source as? String { - body["source"] = tokenSource - } - - if let hashSource = source as? [String: Any] { - hashSource.forEach { body["source[\($0)]"] = $1 } - } - - if let statementDescriptor = statementDescriptor { - body["statement_descriptor"] = statementDescriptor - } - - if let transferData = transferData { - transferData.forEach { body["transfer_data[\($0)]"] = $1 } - } - - if let transferGroup = transferGroup { - body["transfer_group"] = transferGroup - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.charges.endpoint, body: body.queryParameters) - } - - /// Retrieve a charge - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_charge) - public func retrieve(charge: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.charge(charge).endpoint) - } - - /// Update a charge - /// [Learn More →](https://stripe.com/docs/api/curl#update_charge) - public func update(charge chargeId: String, - customer: String?, - description: String?, - fraudDetails: [String: Any]?, - metadata: [String: String]?, - receiptEmail: String?, - shipping: [String: Any]?, - transferGroup: String?) throws -> Future { - var body: [String: Any] = [:] - - if let customer = customer { - body["customer"] = customer - } - - if let description = description { - body["description"] = description - } - - if let fraud = fraudDetails { - fraud.forEach { body["fraud_details[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let receiptEmail = receiptEmail { - body["receipt_email"] = receiptEmail - } - - if let shipping = shipping { - shipping.forEach { body["shipping[\($0)]"] = $1 } - } - - if let transferGroup = transferGroup { - body["transfer_group"] = transferGroup - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.charge(chargeId).endpoint, body: body.queryParameters) - } - - /// Capture a charge - /// [Learn More →](https://stripe.com/docs/api/curl#capture_charge) - public func capture(charge: String, - amount: Int?, - applicationFee: Int?, - destinationAmount: Int?, - receiptEmail: String?, - statementDescriptor: String?) throws -> Future { - var body: [String: Any] = [:] - - if let amount = amount { - body["amount"] = amount - } - - if let applicationFee = applicationFee { - body["application_fee"] = applicationFee - } - - if let destinationAmount = destinationAmount { - body["destination[amount]"] = destinationAmount - } - - if let receiptEmail = receiptEmail { - body["receipt_email"] = receiptEmail - } - - if let statementDescriptor = statementDescriptor { - body["statement_descriptor"] = statementDescriptor - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.captureCharge(charge).endpoint, body: body.queryParameters) - } - - /// List all charges - /// [Learn More →](https://stripe.com/docs/api/curl#list_charges) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.charges.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/CountrySpecRoutes.swift b/Sources/Stripe/API/Routes/CountrySpecRoutes.swift deleted file mode 100644 index 99a3a0a..0000000 --- a/Sources/Stripe/API/Routes/CountrySpecRoutes.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// CountrySpecRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 3/23/19. -// - -import Vapor - -public protocol CountrySpecRoutes { - /// Lists all Country Spec objects available in the API. - /// - /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/country_specs/list) - /// - Returns: A `StripeCountrySpecList`. - /// - Throws: A `StripeError`. - func listAll(filter: [String: Any]?) throws -> EventLoopFuture - - /// Returns a Country Spec for a given Country code. - /// - /// - Parameter country: An ISO 3166-1 alpha-2 country code. Available country codes can be listed with the [List Country Specs](https://stripe.com/docs/api#list_country_specs) endpoint. - /// - Returns: A `StripeCountrySpec`. - /// - Throws: A `StripeError`. - func retrieve(country: String) throws -> EventLoopFuture -} - -extension CountrySpecRoutes { - public func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture { - return try listAll(filter: filter) - } - - public func retrieve(country: String) throws -> EventLoopFuture { - return try retrieve(country: country) - } -} - -public struct StripeCountrySpecRoutes: CountrySpecRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func listAll(filter: [String: Any]?) throws -> EventLoopFuture { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.countrySpec.endpoint, query: queryParams) - } - - public func retrieve(country: String) throws -> EventLoopFuture { - return try request.send(method: .GET, path: StripeAPIEndpoint.countrySpecs(country).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/CouponRoutes.swift b/Sources/Stripe/API/Routes/CouponRoutes.swift deleted file mode 100644 index 7eaefa1..0000000 --- a/Sources/Stripe/API/Routes/CouponRoutes.swift +++ /dev/null @@ -1,145 +0,0 @@ -// -// CouponRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 5/28/17. -// -// - -import Foundation -import Vapor - -public protocol CouponRoutes { - func create(id: String?, duration: StripeDuration, amountOff: Int?, currency: StripeCurrency?, durationInMonths: Int?, maxRedemptions: Int?, metadata: [String: String]?, percentOff: Int?, redeemBy: Date?) throws -> Future - func retrieve(coupon: String) throws -> Future - func update(coupon: String, metadata: [String: String]?) throws -> Future - func delete(coupon: String) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension CouponRoutes { - public func create(id: String? = nil, - duration: StripeDuration, - amountOff: Int? = nil, - currency: StripeCurrency? = nil, - durationInMonths: Int? = nil, - maxRedemptions: Int? = nil, - metadata: [String : String]? = nil, - percentOff: Int? = nil, - redeemBy: Date? = nil) throws -> Future { - return try create(id: id, - duration: duration, - amountOff: amountOff, - currency: currency, - durationInMonths: durationInMonths, - maxRedemptions: maxRedemptions, - metadata: metadata, - percentOff: percentOff, - redeemBy: redeemBy) - } - - public func retrieve(coupon: String) throws -> Future { - return try retrieve(coupon: coupon) - } - - public func update(coupon: String, metadata: [String : String]? = nil) throws -> Future { - return try update(coupon: coupon, metadata: metadata) - } - - public func delete(coupon: String) throws -> Future { - return try delete(coupon: coupon) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeCouponRoutes: CouponRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a coupon - /// [Learn More →](https://stripe.com/docs/api/curl#create_coupon) - public func create(id: String?, - duration: StripeDuration, - amountOff: Int?, - currency: StripeCurrency?, - durationInMonths: Int?, - maxRedemptions: Int?, - metadata: [String : String]?, - percentOff: Int?, - redeemBy: Date?) throws -> Future { - var body: [String: Any] = [:] - - body["duration"] = duration.rawValue - - if let amountOff = amountOff { - body["amount_off"] = amountOff - } - - if let currency = currency { - body["currency"] = currency.rawValue - } - - if let durationInMonths = durationInMonths { - body["duration_in_months"] = durationInMonths - } - - if let maxRedemptions = maxRedemptions { - body["max_redemptions"] = maxRedemptions - } - - if let percentOff = percentOff { - body["percent_off"] = percentOff - } - - if let redeemBy = redeemBy { - body["redeem_by"] = Int(redeemBy.timeIntervalSince1970) - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.coupons.endpoint, body: body.queryParameters) - } - - /// Retrieve coupon - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_coupon) - public func retrieve(coupon: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.coupon(coupon).endpoint) - } - - /// Update coupon - /// [Learn More →](https://stripe.com/docs/api/curl#update_coupon) - public func update(coupon: String, metadata: [String : String]?) throws -> Future { - var body: [String: Any] = [:] - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.coupon(coupon).endpoint, body: body.queryParameters) - } - - /// Delete coupon - /// [Learn More →](https://stripe.com/docs/api/curl#delete_coupon) - public func delete(coupon: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.coupon(coupon).endpoint) - } - - /// List all coupons - /// [Learn More →](https://stripe.com/docs/api/curl#list_coupons) - public func listAll(filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.coupons.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/CustomerRoutes.swift b/Sources/Stripe/API/Routes/CustomerRoutes.swift deleted file mode 100644 index b283f32..0000000 --- a/Sources/Stripe/API/Routes/CustomerRoutes.swift +++ /dev/null @@ -1,321 +0,0 @@ -// -// CustomerRoutes.swift -// Stripe -// -// Created by Anthony Castelli on 4/20/17. -// -// - -import Vapor - -public protocol CustomerRoutes { - func create(accountBalance: Int?, coupon: String?, description: String?, email: String?, invoicePrefix: String?, invoiceSettings: [String: Any]?, metadata: [String: String]?, shipping: [String: Any]?, source: Any?, taxInfo: [String: String]?) throws -> Future - func retrieve(customer: String) throws -> Future - func update(customer: String, accountBalance: Int?, businessVatId: String?, coupon: String?, defaultSource: String?, description: String?, email: String?, metadata: [String: String]?, shipping: ShippingLabel?, source: Any?) throws -> Future - func delete(customer: String) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future - func addNewSource(customer: String, source: String, toConnectedAccount: String?) throws -> Future - func addNewBankAccountSource(customer: String, source: Any, toConnectedAccount: String?, metadata: [String: String]?) throws -> Future - func addNewCardSource(customer: String, source: Any, toConnectedAccount: String?, metadata: [String : String]?) throws -> Future - func deleteSource(customer: String, source: String) throws -> Future - func deleteDiscount(customer: String) throws -> Future -} - -extension CustomerRoutes { - public func create(accountBalance: Int? = nil, - coupon: String? = nil, - description: String? = nil, - email: String? = nil, - invoicePrefix: String? = nil, - invoiceSettings: [String: Any]? = nil, - metadata: [String: String]? = nil, - shipping: [String: Any]? = nil, - source: Any? = nil, - taxInfo: [String: String]? = nil) throws -> Future { - return try create(accountBalance: accountBalance, - coupon: coupon, - description: description, - email: email, - invoicePrefix: invoicePrefix, - invoiceSettings: invoiceSettings, - metadata: metadata, - shipping: shipping, - source: source, - taxInfo: taxInfo) - } - - public func retrieve(customer: String) throws -> Future { - return try retrieve(customer: customer) - } - - public func update(customer: String, - accountBalance: Int? = nil, - businessVatId: String? = nil, - coupon: String? = nil, - defaultSource: String? = nil, - description: String? = nil, - email: String? = nil, - metadata: [String: String]? = nil, - shipping: ShippingLabel? = nil, - source: Any? = nil) throws -> Future { - return try update(customer: customer, - accountBalance: accountBalance, - businessVatId: businessVatId, - coupon: coupon, - defaultSource: defaultSource, - description: description, - email: email, - metadata: metadata, - shipping: shipping, - source: source) - } - - public func delete(customer: String) throws -> Future { - return try delete(customer: customer) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - public func addNewSource(customer: String, source: String, toConnectedAccount: String? = nil) throws -> Future { - return try addNewSource(customer: customer, source: source, toConnectedAccount: toConnectedAccount) - } - - public func addNewBankAccountSource(customer: String, source: Any, toConnectedAccount: String? = nil, metadata: [String : String]? = nil) throws -> Future { - return try addNewBankAccountSource(customer: customer, source: source, toConnectedAccount: toConnectedAccount, metadata: metadata) - } - - public func addNewCardSource(customer: String, source: Any, toConnectedAccount: String? = nil, metadata: [String : String]? = nil) throws -> Future { - return try addNewCardSource(customer: customer, source: source, toConnectedAccount: toConnectedAccount, metadata: metadata) - } - - public func deleteSource(customer: String, source: String) throws -> Future { - return try deleteSource(customer: customer, source: source) - } - - public func deleteDiscount(customer: String) throws -> Future { - return try deleteDiscount(customer: customer) - } -} - - -public struct StripeCustomerRoutes: CustomerRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a customer - /// [Learn More →](https://stripe.com/docs/api/curl#create_customer) - public func create(accountBalance: Int?, - coupon: String?, - description: String?, - email: String?, - invoicePrefix: String?, - invoiceSettings: [String: Any]?, - metadata: [String: String]?, - shipping: [String: Any]?, - source: Any?, - taxInfo: [String: String]?) throws -> Future { - var body: [String: Any] = [:] - - if let accountBalance = accountBalance { - body["account_balance"] = accountBalance - } - - if let coupon = coupon { - body["coupon"] = coupon - } - - if let description = description { - body["description"] = description - } - - if let email = email { - body["email"] = email - } - - if let invoicePrefix = invoicePrefix { - body["invoice_prefix"] = invoicePrefix - } - - if let invoiceSettings = invoiceSettings { - invoiceSettings.forEach { body["invoice_settings[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let shipping = shipping { - shipping.forEach { body["shipping[\($0)]"] = $1 } - } - - if let tokenSource = source as? String { - body["source"] = tokenSource - } - - if let dictionarySource = source as? [String: Any] { - dictionarySource.forEach { body["source[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.customers.endpoint, body: body.queryParameters) - } - - /// Retrieve customer - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_customer) - public func retrieve(customer: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.customer(customer).endpoint) - } - - /// Update customer - /// [Learn More →](https://stripe.com/docs/api/curl#update_customer) - public func update(customer: String, - accountBalance: Int?, - businessVatId: String?, - coupon: String?, - defaultSource: String?, - description: String?, - email: String?, - metadata: [String: String]?, - shipping: ShippingLabel?, - source: Any?) throws -> Future { - var body: [String: Any] = [:] - - if let accountBalance = accountBalance { - body["account_balance"] = accountBalance - } - - if let businessVatId = businessVatId { - body["business_vat_id"] = businessVatId - } - - if let coupon = coupon { - body["coupon"] = coupon - } - - if let defaultSource = defaultSource { - body["default_source"] = defaultSource - } - - if let description = description { - body["description"] = description - } - - if let email = email { - body["email"] = email - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let shipping = shipping { - try shipping.toEncodedDictionary().forEach { body["shipping[\($0)]"] = $1 } - } - - if let tokenSource = source as? String { - body["source"] = tokenSource - } - - if let cardDictionarySource = source as? [String: Any] { - cardDictionarySource.forEach { body["source[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.customer(customer).endpoint, body: body.queryParameters) - } - - /// Delete a customer - /// [Learn More →](https://stripe.com/docs/api/curl#delete_customer) - public func delete(customer: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.customer(customer).endpoint) - } - - /// List all customers - /// [Learn More →](https://stripe.com/docs/api/curl#list_customers) - public func listAll(filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.customers.endpoint, query: queryParams) - } - - /// Attach a source - /// [Learn More →](https://stripe.com/docs/api/curl#attach_source) - public func addNewSource(customer: String, source: String, toConnectedAccount: String?) throws -> Future { - let body: [String: Any] = ["source": source] - var headers: HTTPHeaders = [:] - - if let connectedAccount = toConnectedAccount { - headers.add(name: .stripeAccount, value: connectedAccount) - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.customerSources(customer).endpoint, body: body.queryParameters, headers: headers) - } - - /// Create a bank account - /// [Learn More →](https://stripe.com/docs/api/curl#customer_create_bank_account) - public func addNewBankAccountSource(customer: String, source: Any, toConnectedAccount: String?, metadata: [String : String]?) throws -> Future { - var body: [String: Any] = [:] - var headers: HTTPHeaders = [:] - - if let connectedAccount = toConnectedAccount { - headers.add(name: .stripeAccount, value: connectedAccount) - } - - if let source = source as? String { - body["source"] = source - } - - if let source = source as? [String: Any] { - source.forEach { body["source[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.customerSources(customer).endpoint, body: body.queryParameters, headers: headers) - } - - /// Create a card - /// [Learn More →](https://stripe.com/docs/api/curl#create_card) - public func addNewCardSource(customer: String, source: Any, toConnectedAccount: String?, metadata: [String : String]?) throws -> Future { - var body: [String: Any] = [:] - var headers: HTTPHeaders = [:] - - if let connectedAccount = toConnectedAccount { - headers.add(name: .stripeAccount, value: connectedAccount) - } - - if let source = source as? String { - body["source"] = source - } - - if let source = source as? [String: Any] { - source.forEach { body["source[\($1)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.customerSources(customer).endpoint, body: body.queryParameters, headers: headers) - } - - /// Detach a source - /// [Learn More →](https://stripe.com/docs/api/curl#detach_source) - public func deleteSource(customer: String, source: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.customerDetachSources(customer, source).endpoint) - } - - /// Delete a customer discount - /// [Learn More →](https://stripe.com/docs/api/curl#delete_discount) - public func deleteDiscount(customer: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.customerDiscount(customer).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/DisputeRoutes.swift b/Sources/Stripe/API/Routes/DisputeRoutes.swift deleted file mode 100644 index 1a6bfb5..0000000 --- a/Sources/Stripe/API/Routes/DisputeRoutes.swift +++ /dev/null @@ -1,85 +0,0 @@ -// -// DisputeRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 7/12/17. -// -// - -import Vapor - -public protocol DisputeRoutes { - func retrieve(dispute: String) throws -> Future - func update(dispute: String, disputeEvidence: StripeDisputeEvidence?, metadata: [String: String]?, submit: Bool?) throws -> Future - func close(dispute: String) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension DisputeRoutes { - public func retrieve(dispute: String) throws -> Future { - return try retrieve(dispute: dispute) - } - - public func update(dispute: String, disputeEvidence: StripeDisputeEvidence? = nil, metadata: [String : String]? = nil, submit: Bool? = nil) throws -> Future { - return try update(dispute: dispute, disputeEvidence: disputeEvidence, metadata: metadata, submit: submit) - } - - public func close(dispute: String) throws -> Future { - return try close(dispute: dispute) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeDisputeRoutes: DisputeRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Retrieve a dispute - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_dispute) - public func retrieve(dispute: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.disputes(dispute).endpoint) - } - - /// Update a dispute - /// [Learn More →](https://stripe.com/docs/api/curl#update_dispute) - public func update(dispute: String, disputeEvidence: StripeDisputeEvidence?, metadata: [String : String]?, submit: Bool?) throws -> Future { - var body: [String: Any] = [:] - - if let disputeEvidence = disputeEvidence { - try disputeEvidence.toEncodedDictionary().forEach { body["evidence[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let submit = submit { - body["submit"] = submit - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.disputes(dispute).endpoint, body: body.queryParameters) - } - - /// Close a dispute - /// [Learn More →](https://stripe.com/docs/api/curl#close_dispute) - public func close(dispute: String) throws -> Future { - return try request.send(method: .POST, path: StripeAPIEndpoint.closeDispute(dispute).endpoint) - } - - /// List all disputes - /// [Learn More →](https://stripe.com/docs/api/curl#list_disputes) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.dispute.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/EphemeralKeyRoutes.swift b/Sources/Stripe/API/Routes/EphemeralKeyRoutes.swift deleted file mode 100644 index 71e30ff..0000000 --- a/Sources/Stripe/API/Routes/EphemeralKeyRoutes.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// EphemeralKeyRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 10/17/17. -// - - -import Vapor - -public protocol EphemeralKeyRoutes { - func create(customer: String, apiVersion: String?) throws -> Future - func delete(ephemeralKey: String) throws -> Future -} - -extension EphemeralKeyRoutes { - public func create(customer: String, apiVersion: String? = nil) throws -> Future { - return try create(customer: customer, apiVersion: apiVersion) - } - - public func delete(ephemeralKey: String) throws -> Future { - return try delete(ephemeralKey: ephemeralKey) - } -} - -public struct StripeEphemeralKeyRoutes: EphemeralKeyRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func create(customer: String, apiVersion: String?) throws -> Future { - var headers: HTTPHeaders = [:] - - if let otherApiVersion = apiVersion { - headers.replaceOrAdd(name: .stripeVersion, value: otherApiVersion) - } - - let body = ["customer": customer] - return try request.send(method: .POST, path: StripeAPIEndpoint.ephemeralKeys.endpoint, body: body.queryParameters, headers: headers) - } - - public func delete(ephemeralKey: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.ephemeralKey(ephemeralKey).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift b/Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift deleted file mode 100644 index d338941..0000000 --- a/Sources/Stripe/API/Routes/ExternalAccountsRoutes.swift +++ /dev/null @@ -1,383 +0,0 @@ -// -// ExternalAccountsRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 3/23/19. -// - -import Vapor - -public protocol ExternalAccountsRoutes { - /// Creates a new bank account. When you create a new bank account, you must specify a [Custom account](https://stripe.com/docs/connect/custom-accounts) to create it on. - /// - /// - Parameters: - /// - account: The connect account this bank account should be created for. - /// - bankAccount: Either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe-js/reference), or a dictionary containing a user’s bank account details - /// - defaultForCurrency: When set to true, or if this is the first external account added in this currency, this account becomes the default external account for its currency. - - /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. - /// - Returns: A `StripeBankAccount`. - /// - Throws: A `StripeError`. - func create(account: String, bankAccount: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture - - /// By default, you can see the 10 most recent external accounts stored on a Custom account directly on the object, but you can also retrieve details about a specific bank account stored on the [Custom account](https://stripe.com/docs/connect/custom-accounts). - /// - /// - Parameters: - /// - account: The connect account associated with this bank account. - /// - id: The ID of the bank account to retrieve. - /// - Returns: A `StripeBankAccount`. - /// - Throws: A `StripeError`. - func retrieve(account: String, id: String) throws -> EventLoopFuture - - /// Updates the metadata, account holder name, and account holder type of a bank account belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts), and optionally sets it as the default for its currency. Other bank account details are not editable by design. \n You can re-enable a disabled bank account by performing an update call without providing any arguments or changes. - /// - /// - Parameters: - /// - account: The connect account associated with this bank account. - /// - id: The ID of the bank account to update. - /// - accountHolderName: The name of the person or business that owns the bank account. This will be unset if you POST an empty value. - /// - accountHolderType: The type of entity that holds the account. This can be either `individual` or `company`. This will be unset if you POST an empty value. - /// - defaultForCurrency: When set to true, this becomes the default external account for its currency. - /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. - /// - Returns: A `StripeBankAccount`. - /// - Throws: A `StripeError`. - func update(account: String, - id: String, - accountHolderName: String?, - accountHolderType: StripeBankAccountHolderType?, - defaultForCurrency: Bool?, - metadata: [String: String]?) throws -> EventLoopFuture - - /// Deletes a bank account. You can delete destination bank accounts from a [Custom account](https://stripe.com/docs/connect/custom-accounts). \n If a bank account's `default_for_currency` property is true, it can only be deleted if it is the only external account for that currency, and the currency is not the Stripe account's default currency. Otherwise, before deleting the account, you must set another external account to be the default for the currency. - - /// - /// - Parameters: - /// - account: The connect account associated with this bank account. - /// - id: The ID of the bank account to be deleted. - /// - Returns: A `StripeDeletedObject`. - /// - Throws: A `StripeError`. - func deleteBankAccount(account: String, id: String) throws -> EventLoopFuture - - /// List all bank accounts belonging to a connect account. You can see a list of the bank accounts belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts). Note that the 10 most recent external accounts are always available by default on the corresponding Stripe object. If you need more than those 10, you can use this API method and the `limit` and `starting_after` parameters to page through additional bank accounts. - /// - /// - Parameters: - /// - account: The connect account associated with the bank account(s). - /// - filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/external_account_bank_accounts/list) - /// - Returns: A `StripeBankAccountList`. - /// - Throws: A `StripeError`. - func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture - - /// Creates a new card. When you create a new card, you must specify a [Custom account](https://stripe.com/docs/connect/custom-accounts) to create it on. \n If the account has no default destination card, then the new card will become the default. However, if the owner already has a default then it will not change. To change the default, you should set `default_for_currency` to `true` when creating a card for a Custom account. - /// - /// - Parameters: - /// - account: The connect account this card should be created for. - /// - card: Either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe-js/reference), or a dictionary containing a user’s card details. - /// - defaultForCurrency: When set to true, or if this is the first external account added in this currency, this account becomes the default external account for its currency. - - /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. - /// - Returns: A `StripeCard`. - /// - Throws: A `StripeError`. - func create(account: String, card: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture - - /// By default, you can see the 10 most recent external accounts stored on a [Custom account](https://stripe.com/docs/connect/custom-accounts) directly on the object, but you can also retrieve details about a specific card stored on the [Custom account](https://stripe.com/docs/connect/custom-accounts). - /// - /// - Parameters: - /// - account: The connect account associated with this card. - /// - id: The ID of the card to retrieve. - /// - Returns: A `StripeCard`. - /// - Throws: A `StripeError`. - func retrieve(account: String, id: String) throws -> EventLoopFuture - - /// If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the full card details. Stripe also works directly with card networks so that your customers can [continue using your service](https://stripe.com/docs/saving-cards#automatic-card-updates) without interruption. - /// - Parameters: - /// - account: The connect account associated with this card. - /// - id: The ID of the card to update. - /// - addressCity: City/District/Suburb/Town/Village. This will be unset if you POST an empty value. - /// - addressCountry: Billing address country, if provided when creating card. This will be unset if you POST an empty value. - /// - addressLine1: Address line 1 (Street address/PO Box/Company name). This will be unset if you POST an empty value. - /// - addressLine2: Address line 2 (Apartment/Suite/Unit/Building). This will be unset if you POST an empty value. - /// - addressState: State/County/Province/Region. This will be unset if you POST an empty value. - /// - addressZip: ZIP or postal code. This will be unset if you POST an empty value. - /// - defaultForCurrency: When set to true, this becomes the default external account for its currency. - /// - expMonth: Two digit number representing the card’s expiration month. - /// - expYear: Four digit number representing the card’s expiration year. - /// - metadata: A set of key-value pairs that you can attach to an external account object. It can be useful for storing additional information about the external account in a structured format. - /// - name: Cardholder name. This will be unset if you POST an empty value. - /// - Returns: A `StripeCard`. - /// - Throws: A `StripeError`. - func update(account: String, - id: String, - addressCity: String?, - addressCountry: String?, - addressLine1: String?, - addressLine2: String?, - addressState: String?, - addressZip: String?, - defaultForCurrency: Bool?, - expMonth: Int?, - expYear: Int?, - metadata: [String: String]?, - name: String?) throws -> EventLoopFuture - - /// Deletes a card. If a card's default_for_currency property is true, it can only be deleted if it is the only external account for that currency, and the currency is not the Stripe account's default currency. Otherwise, before deleting the card, you must set another external account to be the default for the currency. - /// - /// - Parameters: - /// - account: The connect account associated with this card. - /// - id: The ID of the card to be deleted. - /// - Returns: A `StripeDeletedObject`. - /// - Throws: A `StripeError`. - func deleteCard(account: String, id: String) throws -> EventLoopFuture - - /// List all cards belonging to a connect account. You can see a list of the cards belonging to a [Custom account](https://stripe.com/docs/connect/custom-accounts). Note that the 10 most recent external accounts are always available by default on the corresponding Stripe object. If you need more than those 10, you can use this API method and the `limit` and `starting_after` parameters to page through additional bank accounts. - /// - /// - Parameters: - /// - account: The connect account associated with the card(s). - /// - filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/external_account_cards/list) - /// - Returns: A `StripeCardList`. - /// - Throws: A `StripeError`. - func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture -} - -extension ExternalAccountsRoutes { - public func create(account: String, bankAccount: Any, defaultForCurrency: Bool? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { - return try create(account: account, bankAccount: bankAccount, defaultForCurrency: defaultForCurrency, metadata: metadata) - } - - public func retrieve(account: String, id: String) throws -> EventLoopFuture { - return try retrieve(account: account, id: id) - } - - public func update(account: String, - id: String, - accountHolderName: String? = nil, - accountHolderType: StripeBankAccountHolderType? = nil, - defaultForCurrency: Bool? = nil, - metadata: [String: String]? = nil) throws -> EventLoopFuture { - return try update(account: account, - id: id, - accountHolderName: accountHolderName, - accountHolderType: accountHolderType, - defaultForCurrency: defaultForCurrency, - metadata: metadata) - } - - public func deleteBankAccount(account: String, id: String) throws -> EventLoopFuture { - return try deleteBankAccount(account: account, id: id) - } - - public func listAll(account: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { - return try listAll(account: account, filter: filter) - } - - public func create(account: String, card: Any, defaultForCurrency: Bool? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { - return try create(account: account, card: card, defaultForCurrency: defaultForCurrency, metadata: metadata) - } - - public func retrieve(account: String, id: String) throws -> EventLoopFuture { - return try retrieve(account: account, id: id) - } - - public func update(account: String, - id: String, - addressCity: String? = nil, - addressCountry: String? = nil, - addressLine1: String? = nil, - addressLine2: String? = nil, - addressState: String? = nil, - addressZip: String? = nil, - defaultForCurrency: Bool? = nil, - expMonth: Int? = nil, - expYear: Int? = nil, - metadata: [String: String]? = nil, - name: String?) throws -> EventLoopFuture { - return try update(account: account, - id: id, - addressCity: addressCity, - addressCountry: addressCountry, - addressLine1: addressLine1, - addressLine2: addressLine2, - addressState: addressState, - addressZip: addressZip, - defaultForCurrency: defaultForCurrency, - expMonth: expMonth, - expYear: expYear, - metadata: metadata, - name: name) - } - - public func deleteCard(account: String, id: String) throws -> EventLoopFuture { - return try deleteCard(account: account, id: id) - } - - public func listAll(account: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { - return try listAll(account: account, filter: filter) - } -} - -public struct StripeExternalAccountsRoutes: ExternalAccountsRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func create(account: String, bankAccount: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let bankToken = bankAccount as? String { - body["external_account"] = bankToken - } else if let bankDetails = bankAccount as? [String: Any] { - bankDetails.forEach { body["external_account[\($0)]"] = $1 } - } - - if let defaultForCurrency = defaultForCurrency { - body["default_for_currency"] = defaultForCurrency - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccount(account).endpoint, body: body.queryParameters) - } - - public func retrieve(account: String, id: String) throws -> EventLoopFuture { - return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) - } - - public func update(account: String, - id: String, - accountHolderName: String?, - accountHolderType: StripeBankAccountHolderType?, - defaultForCurrency: Bool?, - metadata: [String: String]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let accountHolderName = accountHolderName { - body["account_holder_name"] = accountHolderName - } - - if let accountHolderType = accountHolderType { - body["account_holder_type"] = accountHolderType.rawValue - } - - if let defaultForCurrency = defaultForCurrency { - body["default_for_currency"] = defaultForCurrency - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint, body: body.queryParameters) - } - - public func deleteBankAccount(account: String, id: String) throws -> EventLoopFuture { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) - } - - public func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccount(account).endpoint, query: queryParams) - } - - public func create(account: String, card: Any, defaultForCurrency: Bool?, metadata: [String: String]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let cardToken = card as? String { - body["external_account"] = cardToken - } else if let cardDetails = card as? [String: Any] { - cardDetails.forEach { body["external_account[\($0)]"] = $1 } - } - - if let defaultForCurrency = defaultForCurrency { - body["default_for_currency"] = defaultForCurrency - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccount(account).endpoint, body: body.queryParameters) - } - - public func retrieve(account: String, id: String) throws -> EventLoopFuture { - return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) - } - - public func update(account: String, - id: String, - addressCity: String?, - addressCountry: String?, - addressLine1: String?, - addressLine2: String?, - addressState: String?, - addressZip: String?, - defaultForCurrency: Bool?, - expMonth: Int?, - expYear: Int?, - metadata: [String: String]?, - name: String?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let addressCity = addressCity { - body["address_city"] = addressCity - } - - if let addressCountry = addressCountry { - body["address_country"] = addressCountry - } - - if let addressLine1 = addressLine1 { - body["address_line1"] = addressLine1 - } - - if let addressLine2 = addressLine2 { - body["address_line2"] = addressLine2 - } - - if let addressState = addressState { - body["address_state"] = addressState - } - - if let addressZip = addressZip { - body["address_zip"] = addressZip - } - - if let defaultForCurrency = defaultForCurrency { - body["default_for_currency"] = defaultForCurrency - } - - if let expMonth = expMonth { - body["exp_month"] = expMonth - } - - if let expYear = expYear { - body["exp_year"] = expYear - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let name = name { - body["name"] = name - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint, body: body.queryParameters) - } - - public func deleteCard(account: String, id: String) throws -> EventLoopFuture { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.externalAccounts(account, id).endpoint) - } - - public func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.externalAccount(account).endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/FileLinkRoutes.swift b/Sources/Stripe/API/Routes/FileLinkRoutes.swift deleted file mode 100644 index beed218..0000000 --- a/Sources/Stripe/API/Routes/FileLinkRoutes.swift +++ /dev/null @@ -1,109 +0,0 @@ -// -// FileLinkRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 9/14/18. -// - -import Vapor - -public protocol FileLinkRoutes { - /// Creates a new file link object. - /// - /// - Parameters: - /// - file: The ID of the file. - /// - expires: A future timestamp after which the link will no longer be usable. - /// - metadata: Set of key-value pairs that you can attach to an object. - /// - Returns: Returns the file link object if successful, and returns an error otherwise. - func create(file: String, expires: Date?, metadata: [String: String]?) throws -> Future - - /// Retrieves the file link with the given ID. - /// - /// - Parameter link: The identifier of the file link to be retrieved. - /// - Returns: Returns a file link object if a valid identifier was provided, and returns an error otherwise. - func retrieve(link: String) throws -> Future - - /// Updates an existing file link object. Expired links can no longer be updated - /// - /// - Parameters: - /// - link: The ID of the file link. - /// - expires: A future timestamp after which the link will no longer be usable, or `now` to expire the link immediately. - /// - metadata: Set of key-value pairs that you can attach to an object. - /// - Returns: Returns the file link object if successful, and returns an error otherwise. - func update(link: String, expires: Any?, metadata: [String: String]?) throws -> Future - - - /// Returns a list of file links. - /// - /// - Parameter filter: A dictionary that contains the filters. More info [here](https://stripe.com/docs/api/curl#list_file_links). - /// - Returns: A `FileLinkList`. - func listAll(filter: [String: Any]?) throws -> Future -} - -extension FileLinkRoutes { - public func create(file: String, expires: Date? = nil, metadata: [String: String]? = nil) throws -> Future { - return try create(file: file, expires: expires, metadata: metadata) - } - - public func retrieve(link: String) throws -> Future { - return try retrieve(link: link) - } - - public func update(link: String, expires: Any? = nil, metadata: [String: String]? = nil) throws -> Future { - return try update(link: link, expires: expires, metadata: metadata) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeFileLinkRoutes: FileLinkRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func create(file: String, expires: Date?, metadata: [String: String]?) throws -> Future { - var body: [String: Any] = [:] - if let expires = expires { - body["expires_at"] = Int(expires.timeIntervalSince1970) - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1} - } - return try request.send(method: .POST, path: StripeAPIEndpoint.fileLink.endpoint, body: body.queryParameters) - } - - public func retrieve(link: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.fileLinks(link).endpoint) - } - - public func update(link: String, expires: Any?, metadata: [String: String]?) throws -> Future { - var body: [String: Any] = [:] - - if let expires = expires as? Date { - body["expires_at"] = Int(expires.timeIntervalSince1970) - } - - if let expires = expires as? String { - body["expires_at"] = expires - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1} - } - return try request.send(method: .POST, path: StripeAPIEndpoint.fileLinks(link).endpoint, body: body.queryParameters) - } - - public func listAll(filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.fileLink.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/FileRoutes.swift b/Sources/Stripe/API/Routes/FileRoutes.swift deleted file mode 100644 index 375fb82..0000000 --- a/Sources/Stripe/API/Routes/FileRoutes.swift +++ /dev/null @@ -1,102 +0,0 @@ -// -// FileRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 9/15/18. -// - -import Vapor - -public protocol FileRoutes { - /// Uploads a file to Stripe - /// - /// - Parameters: - /// - file: A file to upload. - /// - purpose: The purpose of the uploaded file. - /// - filename: The name of the file. - /// - type: The MIME type of the file. - /// - Returns: The file object. - func upload(file: Data, purpose: FilePurpose, filename: String, type: FileType) throws -> Future - - /// Retrieves the details of an existing file object. Supply the unique file upload ID from a file creation request, and Stripe will return the corresponding transfer information. - /// - /// - Parameter id: The identifier of the file upload to be retrieved. - /// - Returns: Returns a file upload object if a valid identifier was provided, and returns an error otherwise. - func retrieve(id: String) throws -> Future - - /// Returns a list of the files that you have uploaded to Stripe. The file uploads are returned sorted by creation date, with the most recently created file uploads appearing first. - /// - /// - Parameter filter: A dictionary that contains the filters. More info [here](https://stripe.com/docs/api/curl#list_file_uploads). - /// - Returns: A `FileUploadList` - func listAll(filter: [String: Any]?) throws -> Future -} - -extension FileRoutes { - public func upload(file: Data, purpose: FilePurpose, filename: String, type: FileType) throws -> Future { - return try upload(file: file, purpose: purpose, filename: filename, type: type) - } - - public func retrieve(id: String) throws -> Future { - return try retrieve(id: id) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeFileRoutes: FileRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func upload(file: Data, purpose: FilePurpose, filename: String, type: FileType) throws -> Future { - var headers: HTTPHeaders = [:] - var body: Data = Data() - - guard let fileType = MediaType.fileExtension(type.rawValue) else { - throw StripeUploadError.unsupportedFileType - } - - // Fordm data structure found here. - // https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4 - - let boundary = "Stripe-Vapor-\(UUID().uuidString)" - headers.replaceOrAdd(name: .contentType, value: MediaType(type: "multipart", - subType: "form-data", - parameters: ["boundary": boundary]).description) - body.append("\r\n--\(boundary)\r\n") - body.append("Content-Disposition: form-data; name=\"purpose\"\"\r\n\r\n") - body.append("\(purpose.rawValue)") - body.append("\r\n--\(boundary)\r\n") - body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n") - body.append("Content-Type: \(fileType.description)\r\n\r\n") - body.append(file) - body.append("\r\n--\(boundary)--") - - return try request.send(method: .POST, path: StripeAPIEndpoint.file.endpoint, body: body, headers: headers) - } - - public func retrieve(id: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.files(id).endpoint) - } - - public func listAll(filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.file.endpoint, query: queryParams) - } -} - -/// Thank you @vzsg for this nice little clean snippet -private extension Data { - mutating func append(_ string: String) { - guard let data = string.data(using: .utf8) else { return } - self.append(data) - } -} diff --git a/Sources/Stripe/API/Routes/InvoiceItemRoutes.swift b/Sources/Stripe/API/Routes/InvoiceItemRoutes.swift deleted file mode 100644 index 04a8585..0000000 --- a/Sources/Stripe/API/Routes/InvoiceItemRoutes.swift +++ /dev/null @@ -1,159 +0,0 @@ -// -// InvoiceItemRoutes.swift -// Stripe -// -// Created by Anthony Castelli on 9/5/17. -// -// - -import Vapor - -public protocol InvoiceItemRoutes { - func create(amount: Int, currency: StripeCurrency, customer: String, description: String?, discountable: Bool?, invoice: String?, metadata: [String: String]?, subscription: String?) throws -> Future - func retrieve(invoiceItem: String) throws -> Future - func update(invoiceItem: String, amount: Int?, description: String?, discountable: Bool?, metadata: [String: String]?) throws -> Future - func delete(invoiceItem: String) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension InvoiceItemRoutes { - public func create(amount: Int, - currency: StripeCurrency, - customer: String, - description: String? = nil, - discountable: Bool? = nil, - invoice: String? = nil, - metadata: [String : String]? = nil, - subscription: String? = nil) throws -> Future { - return try create(amount: amount, - currency: currency, - customer: customer, - description: description, - discountable: discountable, - invoice: invoice, - metadata: metadata, - subscription: subscription) - } - - public func retrieve(invoiceItem: String) throws -> Future { - return try retrieve(invoiceItem: invoiceItem) - } - - public func update(invoiceItem: String, - amount: Int? = nil, - description: String? = nil, - discountable: Bool? = nil, - metadata: [String : String]? = nil) throws -> Future { - return try update(invoiceItem: invoiceItem, - amount: amount, - description: description, - discountable: discountable, - metadata: metadata) - } - - public func delete(invoiceItem: String) throws -> Future { - return try delete(invoiceItem: invoiceItem) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeInvoiceItemRoutes: InvoiceItemRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create an invoice item - /// [Learn More →](https://stripe.com/docs/api/curl#create_invoiceitem) - public func create(amount: Int, - currency: StripeCurrency, - customer: String, - description: String?, - discountable: Bool?, - invoice: String?, - metadata: [String : String]?, - subscription: String?) throws -> Future { - var body: [String: Any] = [:] - - body["amount"] = amount - body["currency"] = currency.rawValue - body["customer"] = customer - - if let description = description { - body["description"] = description - } - - if let discountable = discountable { - body["discountable"] = discountable - } - - if let invoice = invoice { - body["invoice"] = invoice - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let subscription = subscription { - body["subscription"] = subscription - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.invoiceItems.endpoint, body: body.queryParameters) - } - - /// Retrieve an invoice item - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_invoiceitem) - public func retrieve(invoiceItem: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.invoiceItem(invoiceItem).endpoint) - } - - /// Update an invoice item - /// [Learn More →](https://stripe.com/docs/api/curl#update_invoiceitem) - public func update(invoiceItem: String, - amount: Int?, - description: String?, - discountable: Bool?, - metadata: [String : String]?) throws -> Future { - var body: [String: Any] = [:] - - if let amount = amount { - body["amount"] = amount - } - - if let description = description { - body["description"] = description - } - - if let discountable = discountable { - body["discountable"] = discountable - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.invoiceItem(invoiceItem).endpoint, body: body.queryParameters) - } - - /// Delete an invoice item - /// [Learn More →](https://stripe.com/docs/api/curl#delete_invoiceitem) - public func delete(invoiceItem: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.invoiceItem(invoiceItem).endpoint) - } - - /// List all invoice items - /// [Learn More →](https://stripe.com/docs/api/curl#list_invoiceitems) - public func listAll(filter: [String: Any]? = nil) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.invoiceItems.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/InvoiceRoutes.swift b/Sources/Stripe/API/Routes/InvoiceRoutes.swift deleted file mode 100644 index 6cbfa67..0000000 --- a/Sources/Stripe/API/Routes/InvoiceRoutes.swift +++ /dev/null @@ -1,258 +0,0 @@ -// -// InvoiceRoutes.swift -// Stripe -// -// Created by Anthony Castelli on 9/4/17. -// -// - -import Vapor -import Foundation - -public protocol InvoiceRoutes { - func create(customer: String, applicationFee: Int?, connectAccount: String?, billing: String?, daysUntilDue: Int?, description: String?, dueDate: Date?, metadata: [String: String]?, statementDescriptor: String?, subscription: String?, taxPercent: Decimal?) throws -> Future - func retrieve(invoice: String) throws -> Future - func retrieveLineItems(invoice: String, filter: [String: Any]?) throws -> Future - func retrieveUpcomingInvoice(customer: String, filter: [String: Any]?) throws -> Future - func update(invoice: String, applicationFee: Int?, connectAccount: String?, closed: Bool?, description: String?, forgiven: Bool?, metadata: [String: String]?, paid: Bool?, statementDescriptor: String?, taxPercent: Decimal?) throws -> Future - func pay(invoice: String, source: String?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension InvoiceRoutes { - public func create(customer: String, - applicationFee: Int? = nil, - connectAccount: String? = nil, - billing: String? = nil, - daysUntilDue: Int? = nil, - description: String? = nil, - dueDate: Date? = nil, - metadata: [String : String]? = nil, - statementDescriptor: String? = nil, - subscription: String? = nil, - taxPercent: Decimal? = nil) throws -> Future { - return try create(customer: customer, - applicationFee: applicationFee, - connectAccount: connectAccount, - billing: billing, - daysUntilDue: daysUntilDue, - description: description, - dueDate: dueDate, - metadata: metadata, - statementDescriptor: statementDescriptor, - subscription: subscription, - taxPercent: taxPercent) - } - - public func retrieve(invoice: String) throws -> Future { - return try retrieve(invoice: invoice) - } - - public func retrieveLineItems(invoice: String, filter: [String: Any]? = nil) throws -> Future { - return try retrieveLineItems(invoice: invoice, filter: filter) - } - - public func retrieveUpcomingInvoice(customer: String, filter: [String: Any]? = nil) throws -> Future { - return try retrieveUpcomingInvoice(customer: customer, filter: filter) - } - - public func update(invoice: String, - applicationFee: Int? = nil, - connectAccount: String? = nil, - closed: Bool? = nil, - description: String? = nil, - forgiven: Bool? = nil, - metadata: [String : String]? = nil, - paid: Bool? = nil, - statementDescriptor: String? = nil, - taxPercent: Decimal? = nil) throws -> Future { - return try update(invoice: invoice, - applicationFee: applicationFee, - connectAccount: connectAccount, - closed: closed, - description: description, - forgiven: forgiven, - metadata: metadata, - paid: paid, - statementDescriptor: statementDescriptor, - taxPercent: taxPercent) - } - - public func pay(invoice: String, source: String? = nil) throws -> Future { - return try pay(invoice: invoice, source: source) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeInvoiceRoutes: InvoiceRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create an invoice - /// [Learn More →](https://stripe.com/docs/api/curl#create_invoice) - public func create(customer: String, - applicationFee: Int?, - connectAccount: String?, - billing: String?, - daysUntilDue: Int?, - description: String?, - dueDate: Date?, - metadata: [String : String]?, - statementDescriptor: String?, - subscription: String?, - taxPercent: Decimal?) throws -> Future { - var body: [String: Any] = [:] - var headers: HTTPHeaders = [:] - - body["customer"] = customer - - if let applicationFee = applicationFee { - body["application_fee"] = applicationFee - } - - if let connectAccount = connectAccount { - headers.add(name: .stripeAccount, value: connectAccount) - } - - if let billing = billing { - body["billing"] = billing - } - - if let daysUntilDue = daysUntilDue { - body["days_until_due"] = daysUntilDue - } - - if let description = description { - body["description"] = description - } - - if let dueDate = dueDate { - body["due_date"] = Int(dueDate.timeIntervalSince1970) - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let statementDescriptor = statementDescriptor { - body["statement_descriptor"] = statementDescriptor - } - - if let subscription = subscription { - body["subscription"] = subscription - } - - if let taxPercent = taxPercent { - body["tax_percent"] = taxPercent - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.invoices.endpoint, body: body.queryParameters, headers: headers) - } - - /// Retrieve an invoice - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_invoice) - public func retrieve(invoice: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.invoice(invoice).endpoint) - } - - /// Retrieve an invoice's line items - /// [Learn More →](https://stripe.com/docs/api/curl#invoice_lines) - public func retrieveLineItems(invoice: String, filter: [String: Any]?) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.invoiceLines(invoice).endpoint, query: filter?.queryParameters ?? "") - } - - /// Retrieve an upcoming invoice - /// [Learn More →](https://stripe.com/docs/api/curl#upcoming_invoice) - public func retrieveUpcomingInvoice(customer: String, filter: [String: Any]?) throws -> Future { - var query: [String: Any] = ["customer": customer] - - if let filter = filter { - filter.forEach { query["\($0)"] = $1 } - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.upcomingInvoices.endpoint, query: query.queryParameters) - } - - /// Update an invoice - /// [Learn More →](https://stripe.com/docs/api/curl#update_invoice) - public func update(invoice: String, - applicationFee: Int?, - connectAccount: String?, - closed: Bool?, - description: String?, - forgiven: Bool?, - metadata: [String : String]?, - paid: Bool?, - statementDescriptor: String?, - taxPercent: Decimal?) throws -> Future { - var body: [String: Any] = [:] - var headers: HTTPHeaders = [:] - - if let applicationFee = applicationFee { - body["application_fee"] = applicationFee - } - - if let connectAccount = connectAccount { - headers.add(name: .stripeAccount, value: connectAccount) - } - - if let closed = closed { - body["closed"] = closed - } - - if let description = description { - body["description"] = description - } - - if let forgiven = forgiven { - body["forgiven"] = forgiven - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let paid = paid { - body["paid"] = paid - } - - if let statementDescriptor = statementDescriptor { - body["statement_descriptor"] = statementDescriptor - } - - if let taxPercent = taxPercent { - body["tax_percent"] = taxPercent - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.invoice(invoice).endpoint, body: body.queryParameters, headers: headers) - } - - /// Pay an invoice - /// [Learn More →](https://stripe.com/docs/api/curl#pay_invoice) - public func pay(invoice: String, source: String?) throws -> Future { - var body: [String: Any] = [:] - - if let source = source { - body["source"] = source - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.payInvoice(invoice).endpoint, body: body.queryParameters) - } - - /// List all invoices - /// [Learn More →](https://stripe.com/docs/api/curl#list_invoices) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.invoices.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/OrderReturnRoutes.swift b/Sources/Stripe/API/Routes/OrderReturnRoutes.swift deleted file mode 100644 index 53aced3..0000000 --- a/Sources/Stripe/API/Routes/OrderReturnRoutes.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// OrderReturnRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 8/25/17. -// -// - -import Vapor - -public protocol OrderReturnRoutes { - func retrieve(order: String) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension OrderReturnRoutes { - public func retrieve(order: String) throws -> Future { - return try retrieve(order: order) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeOrderReturnRoutes: OrderReturnRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Retrieve an order return - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_order_return) - public func retrieve(order: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.orderReturns(order).endpoint) - } - - /// List all order returns - /// [Learn More →](https://stripe.com/docs/api/curl#list_order_returns) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.orderReturn.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/OrderRoutes.swift b/Sources/Stripe/API/Routes/OrderRoutes.swift deleted file mode 100644 index 26abc76..0000000 --- a/Sources/Stripe/API/Routes/OrderRoutes.swift +++ /dev/null @@ -1,233 +0,0 @@ -// -// OrderRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -import Vapor - -public protocol OrderRoutes { - func create(currency: StripeCurrency, coupon: String?, customer: String?, email: String?, items: [[String: Any]]?, metadata: [String: String]?, shipping: ShippingLabel?) throws -> Future - func retrieve(order: String) throws -> Future - func update(order: String, coupon: String?, metadata: [String: String]?, selectedShippingMethod: String?, shipping: ShippingLabel?, status: String?) throws -> Future - func pay(order: String, customer: String?, source: Any?, applicationFee: Int?, connectAccount: String?, email: String?, metadata: [String: String]?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future - func `return`(order: String, items: [[String: Any]]?) throws -> Future -} - -extension OrderRoutes { - public func create(currency: StripeCurrency, - coupon: String? = nil, - customer: String? = nil, - email: String? = nil, - items: [[String: Any]]? = nil, - metadata: [String: String]? = nil, - shipping: ShippingLabel? = nil) throws -> Future { - return try create(currency: currency, - coupon: coupon, - customer: customer, - email: email, - items: items, - metadata: metadata, - shipping: shipping) - } - - public func retrieve(order: String) throws -> Future { - return try retrieve(order: order) - } - - public func update(order: String, - coupon: String? = nil, - metadata: [String: String]? = nil, - selectedShippingMethod: String? = nil, - shipping: ShippingLabel? = nil, - status: String? = nil) throws -> Future { - return try update(order: order, - coupon: coupon, - metadata: metadata, - selectedShippingMethod: selectedShippingMethod, - shipping: shipping, - status: status) - } - - public func pay(order: String, - customer: String? = nil, - source: Any? = nil, - applicationFee: Int? = nil, - connectAccount: String? = nil, - email: String? = nil, - metadata: [String: String]? = nil) throws -> Future { - return try pay(order: order, - customer: customer, - source: source, - applicationFee: applicationFee, - connectAccount: connectAccount, - email: email, - metadata: metadata) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - public func `return`(order: String, items: [[String: Any]]? = nil) throws -> Future { - return try `return`(order: order, items: items) - } -} - -public struct StripeOrderRoutes: OrderRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Creating a new order - /// [Learn More →](https://stripe.com/docs/api/curl#create_order) - public func create(currency: StripeCurrency, - coupon: String?, - customer: String?, - email: String?, - items: [[String: Any]]?, - metadata: [String: String]?, - shipping: ShippingLabel?) throws -> Future { - var body: [String: Any] = [:] - - if let coupon = coupon { - body["coupon"] = coupon - } - - if let customer = customer { - body["customer"] = customer - } - - if let email = email { - body["email"] = email - } - - if let items = items { - for i in 0.. Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.orders(order).endpoint) - } - - /// Update an order - /// [Learn More →](https://stripe.com/docs/api/curl#update_order) - public func update(order: String, - coupon: String?, - metadata: [String: String]?, - selectedShippingMethod: String?, - shipping: ShippingLabel?, - status: String?) throws -> Future { - var body: [String: Any] = [:] - - if let coupon = coupon { - body["coupon"] = coupon - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let selectedShippingMethod = selectedShippingMethod { - body["selected_shipping_method"] = selectedShippingMethod - } - - if let shipping = shipping { - try shipping.toEncodedDictionary().forEach { body["shipping[\($0)]"] = $1 } - } - - if let status = status { - body["status"] = status - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.orders(order).endpoint, body: body.queryParameters) - } - - /// Pay an order - /// [Learn More →](https://stripe.com/docs/api/curl#pay_order) - public func pay(order: String, - customer: String?, - source: Any?, - applicationFee: Int?, - connectAccount: String?, - email: String?, - metadata: [String: String]?) throws -> Future { - var body: [String: Any] = [:] - var headers: HTTPHeaders = [:] - - if let customer = customer { - body["customer"] = customer - } - - if let source = source as? String { - body["source"] = source - } - - if let source = source as? [String: Any] { - source.forEach { body["source[\($0)]"] = $1 } - } - - if let applicationfee = applicationFee { - body["application_fee"] = applicationfee - } - - if let connectAccount = connectAccount { - headers.add(name: .stripeAccount, value: connectAccount) - } - - if let email = email { - body["email"] = email - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.ordersPay(order).endpoint, body: body.queryParameters, headers: headers) - } - - /// List all orders - /// [Learn More →](https://stripe.com/docs/api/curl#list_orders) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.order.endpoint, query: queryParams) - } - - /// Return an order - /// [Learn More →](https://stripe.com/docs/api/curl#return_order) - public func `return`(order: String, items: [[String: Any]]?) throws -> Future { - var body: [String: Any] = [:] - - if let items = items { - for i in 0.. Future - func retrieve(payout: String) throws -> Future - func update(payout: String, metadata: [String: String]?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future - func cancel(payout: String) throws -> Future -} - -extension PayoutRoutes { - func create(amount: Int, - currency: StripeCurrency, - description: String? = nil, - destination: String? = nil, - metadata: [String: String]? = nil, - method: StripePayoutMethod? = nil, - sourceType: StripePayoutSourceType? = nil, - statementDescriptor: String? = nil) throws -> Future { - return try create(amount: amount, - currency: currency, - description: description, - destination: destination, - metadata: metadata, - method: method, - sourceType: sourceType, - statementDescriptor: statementDescriptor) - } - - func retrieve(payout: String) throws -> Future { - return try retrieve(payout: payout) - } - - func update(payout: String, metadata: [String: String]? = nil) throws -> Future { - return try update(payout: payout, metadata: metadata) - } - - func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - func cancel(payout: String) throws -> Future { - return try cancel(payout: payout) - } -} - -public struct StripePayoutRoutes: PayoutRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a payout - /// [Learn More →](https://stripe.com/docs/api/curl#create_payout) - public func create(amount: Int, - currency: StripeCurrency, - description: String?, - destination: String?, - metadata: [String: String]?, - method: StripePayoutMethod?, - sourceType: StripePayoutSourceType?, - statementDescriptor: String?) throws -> Future { - var body: [String: Any] = [:] - - body["amount"] = amount - body["currency"] = currency.rawValue - - if let description = description { - body["description"] = description - } - - if let destination = destination { - body["destination"] = destination - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let method = method { - body["method"] = method.rawValue - } - - if let sourceType = sourceType { - body["source_type"] = sourceType.rawValue - } - - if let statementDescriptor = statementDescriptor { - body["statement_descriptor"] = statementDescriptor - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.payout.endpoint, body: body.queryParameters) - } - - /// Retrieve a payout - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_payout) - public func retrieve(payout: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.payouts(payout).endpoint) - } - - /// Update a payout - /// [Learn More →](https://stripe.com/docs/api/curl#update_payout) - public func update(payout: String, metadata: [String: String]?) throws -> Future { - var body: [String: Any] = [:] - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - return try request.send(method: .POST, path: StripeAPIEndpoint.payouts(payout).endpoint, body: body.queryParameters) - } - - /// List payouts - /// [Learn More →](https://stripe.com/docs/api/curl#list_payouts) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.payout.endpoint, query: queryParams) - } - - /// Cancel payout - /// [Learn More →](https://stripe.com/docs/api/curl#cancel_payout) - public func cancel(payout: String) throws -> Future { - return try request.send(method: .POST, path: StripeAPIEndpoint.payoutsCancel(payout).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/PersonRoutes.swift b/Sources/Stripe/API/Routes/PersonRoutes.swift deleted file mode 100644 index d586f30..0000000 --- a/Sources/Stripe/API/Routes/PersonRoutes.swift +++ /dev/null @@ -1,350 +0,0 @@ -// -// PersonRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 2/28/19. -// - -import Vapor - -public protocol PersonRoutes { - /// Creates a new person. - /// - /// - Parameters: - /// - account: The unique identifier of the account the person is associated with. - /// - address: The person’s address. - /// - dob: The person’s date of birth. - /// - email: The person’s email address. - /// - firstName: The person’s first name. - /// - gender: The person’s gender (International regulations require either “male” or “female”). - /// - idNumber: The person’s ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a PII token provided by Stripe.js. - /// - lastName: The person’s last name. - /// - maidenName: The person’s maiden name. - /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to metadata. - /// - phone: The person’s phone number. - /// - relationship: The relationship that this person has with the account’s legal entity. - /// - ssnLast4: The last 4 digits of the person’s social security number. - /// - verification: The person’s verification status. - /// - Returns: Returns a person object. - /// - Throws: A `StripeError` - func create(account: String, - address: [String: Any]?, - dob: [String: Any]?, - email: String?, - firstName: String?, - gender: StripePersonGender?, - idNumber: String?, - lastName: String?, - maidenName: String?, - metadata: [String: String]?, - phone: String?, - relationship: [String: Any]?, - ssnLast4: String?, - verification: [String: Any]?) throws -> EventLoopFuture - - /// Retrieves an existing person. - /// - /// - Parameters: - /// - account: The unique identifier of the account the person is associated with. - /// - person: The ID of a person to retrieve. - /// - Returns: Returns a person object. - /// - Throws: A `StripeError` - func retrieve(account: String, person: String) throws -> EventLoopFuture - - /// Updates an existing person. - /// - /// - Parameters: - /// - account: The unique identifier of the account the person is associated with. - /// - person: The ID of a person to update. - /// - address: The person’s address. - /// - dob: The person’s date of birth. - /// - email: The person’s email address. - /// - firstName: The person’s first name. - /// - gender: The person’s gender (International regulations require either “male” or “female”). - /// - idNumber: The person’s ID number, as appropriate for their country. For example, a social security number in the U.S., social insurance number in Canada, etc. Instead of the number itself, you can also provide a PII token provided by Stripe.js. - /// - lastName: The person’s last name. - /// - maidenName: The person’s maiden name. - /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to metadata. - /// - phone: The person’s phone number. - /// - relationship: The relationship that this person has with the account’s legal entity. - /// - ssnLast4: The last 4 digits of the person’s social security number. - /// - verification: The person’s verification status. - /// - Returns: Returns a person object. - /// - Throws: A `StripeError` - func update(account: String, - person: String, - address: [String: Any]?, - dob: [String: Any]?, - email: String?, - firstName: String?, - gender: StripePersonGender?, - idNumber: String?, - lastName: String?, - maidenName: String?, - metadata: [String: String]?, - phone: String?, - relationship: [String: Any]?, - ssnLast4: String?, - verification: [String: Any]?) throws -> EventLoopFuture - - /// Deletes an existing person’s relationship to the account’s legal entity. - /// - /// - Parameters: - /// - account: The unique identifier of the account the person is associated with. - /// - person: The ID of a person to update. - /// - Returns: Returns the deleted person object. - /// - Throws: A `StripeError` - func delete(account: String, person: String) throws -> EventLoopFuture - - /// Returns a list of people associated with the account’s legal entity. The people are returned sorted by creation date, with the most recent people appearing first. - /// - /// - Parameters: - /// - account: The unique identifier of the account the person is associated with. - /// - filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/persons/list?&lang=curl) - /// - Returns: A `PersonsList` - /// - Throws: A `StripeError` - func listAll(account: String, filter: [String: Any]?) throws -> EventLoopFuture -} - -extension PersonRoutes { - public func create(account: String, - address: [String: Any]? = nil, - dob: [String: Any]? = nil, - email: String? = nil, - firstName: String? = nil, - gender: StripePersonGender? = nil, - idNumber: String? = nil, - lastName: String? = nil, - maidenName: String? = nil, - metadata: [String: String]? = nil, - phone: String? = nil, - relationship: [String: Any]? = nil, - ssnLast4: String?, - verification: [String: Any]? = nil) throws -> EventLoopFuture { - return try create(account: account, - address: address, - dob: dob, - email: email, - firstName: firstName, - gender: gender, - idNumber: idNumber, - lastName: lastName, - maidenName: maidenName, - metadata: metadata, - phone: phone, - relationship: relationship, - ssnLast4: ssnLast4, - verification: verification) - } - - public func retrieve(account: String, person: String) throws -> EventLoopFuture { - return try retrieve(account: account, person: person) - } - - public func update(account: String, - person: String, - address: [String: Any]? = nil, - dob: [String: Any]? = nil, - email: String? = nil, - firstName: String? = nil, - gender: StripePersonGender? = nil, - idNumber: String? = nil, - lastName: String? = nil, - maidenName: String? = nil, - metadata: [String: String]? = nil, - phone: String? = nil, - relationship: [String: Any]? = nil, - ssnLast4: String? = nil, - verification: [String: Any]? = nil) throws -> EventLoopFuture { - return try update(account: account, - person: person, - address: address, - dob: dob, - email: email, - firstName: firstName, - gender: gender, - idNumber: idNumber, - lastName: lastName, - maidenName: maidenName, - metadata: metadata, - phone: phone, - relationship: relationship, - ssnLast4: ssnLast4, - verification: verification) - } - - public func delete(account: String, person: String) throws -> EventLoopFuture { - return try delete(account: account, person: person) - } - - public func listAll(account: String, filter: [String: Any]? = nil) throws -> EventLoopFuture { - return try listAll(account: account, filter: filter) - } -} - -public struct StripePersonRoutes: PersonRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func create(account: String, - address: [String: Any]?, - dob: [String: Any]?, - email: String?, - firstName: String?, - gender: StripePersonGender?, - idNumber: String?, - lastName: String?, - maidenName: String?, - metadata: [String: String]?, - phone: String?, - relationship: [String: Any]?, - ssnLast4: String?, - verification: [String: Any]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let address = address { - address.forEach { body["address[\($0)]"] = $1 } - } - - if let dob = dob { - dob.forEach { body["dob[\($0)]"] = $1 } - } - - if let email = email { - body["email"] = email - } - - if let firstName = firstName { - body["first_name"] = firstName - } - - if let gender = gender { - body["gender"] = gender.rawValue - } - - if let idNumber = idNumber { - body["id_number"] = idNumber - } - - if let lastName = lastName { - body["last_name"] = lastName - } - - if let maidenName = maidenName { - body["maiden_name"] = maidenName - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let phone = phone { - body["phone"] = phone - } - - if let relationship = relationship { - relationship.forEach { body["relationship[\($0)]"] = $1 } - } - - if let ssnLast4 = ssnLast4 { - body["ssn_last_4"] = ssnLast4 - } - - if let verification = verification { - verification.forEach { body["verification[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.person(account).endpoint, body: body.queryParameters) - } - - public func retrieve(account: String, person: String) throws -> EventLoopFuture { - return try request.send(method: .GET, path: StripeAPIEndpoint.persons(account, person).endpoint) - } - - public func update(account: String, - person: String, - address: [String: Any]?, - dob: [String: Any]?, - email: String?, - firstName: String?, - gender: StripePersonGender?, - idNumber: String?, - lastName: String?, - maidenName: String?, - metadata: [String: String]?, - phone: String?, - relationship: [String: Any]?, - ssnLast4: String?, - verification: [String: Any]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let address = address { - address.forEach { body["address[\($0)]"] = $1 } - } - - if let dob = dob { - dob.forEach { body["dob[\($0)]"] = $1 } - } - - if let email = email { - body["email"] = email - } - - if let firstName = firstName { - body["first_name"] = firstName - } - - if let gender = gender { - body["gender"] = gender.rawValue - } - - if let idNumber = idNumber { - body["id_number"] = idNumber - } - - if let lastName = lastName { - body["last_name"] = lastName - } - - if let maidenName = maidenName { - body["maiden_name"] = maidenName - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let phone = phone { - body["phone"] = phone - } - - if let relationship = relationship { - relationship.forEach { body["relationship[\($0)]"] = $1 } - } - - if let ssnLast4 = ssnLast4 { - body["ssn_last_4"] = ssnLast4 - } - - if let verification = verification { - verification.forEach { body["verification[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.persons(account, person).endpoint, body: body.queryParameters) - } - - public func delete(account: String, person: String) throws -> EventLoopFuture { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.persons(account, person).endpoint) - } - - public func listAll(account: String, filter: [String : Any]?) throws -> EventLoopFuture { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.person(account).endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/PlanRoutes.swift b/Sources/Stripe/API/Routes/PlanRoutes.swift deleted file mode 100644 index c56f41b..0000000 --- a/Sources/Stripe/API/Routes/PlanRoutes.swift +++ /dev/null @@ -1,154 +0,0 @@ -// -// PlanRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 5/29/17. -// -// - -import Vapor - -public protocol PlanRoutes { - func create(id: String?, currency: StripeCurrency, interval: StripePlanInterval, product: String, amount: Int?, intervalCount: Int?, metadata: [String: String]?, nickname: String?) throws -> Future - func retrieve(plan: String) throws -> Future - func update(plan: String, metadata: [String: String]?, nickname: String?, product: String?) throws -> Future - func delete(plan: String) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension PlanRoutes { - public func create(id: String? = nil, - currency: StripeCurrency, - interval: StripePlanInterval, - product: String, - amount: Int? = nil, - intervalCount: Int? = nil, - metadata: [String: String]? = nil, - nickname: String? = nil) throws -> Future { - return try create(id: id, - currency: currency, - interval: interval, - product: product, - amount: amount, - intervalCount: intervalCount, - metadata: metadata, - nickname: nickname) - } - - public func retrieve(plan: String) throws -> Future { - return try retrieve(plan: plan) - } - - public func update(plan: String, - metadata: [String : String]? = nil, - nickname: String? = nil, - product: String? = nil) throws -> Future { - return try update(plan: plan, - metadata: metadata, - nickname: nickname, - product: product) - } - - public func delete(plan: String) throws -> Future { - return try delete(plan: plan) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - -} - -public struct StripePlanRoutes: PlanRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a plan - /// [Learn More →](https://stripe.com/docs/api/curl#create_plan) - public func create(id: String?, - currency: StripeCurrency, - interval: StripePlanInterval, - product: String, - amount: Int?, - intervalCount: Int?, - metadata: [String: String]?, - nickname: String?) throws -> Future { - var body: [String: Any] = [:] - - body["currency"] = currency.rawValue - body["interval"] = interval.rawValue - body["product"] = product - - if let id = id { - body["id"] = id - } - - if let amount = amount { - body["amount"] = amount - } - - if let intervalCount = intervalCount { - body["interval_count"] = intervalCount - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let nickname = nickname { - body["nickname"] = nickname - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.plans.endpoint, body: body.queryParameters) - } - - /// Retrieve a plan - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_plan) - public func retrieve(plan: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.plan(plan).endpoint) - } - - /// Update a plan - /// [Learn More →](https://stripe.com/docs/api/curl#update_plan) - public func update(plan: String, - metadata: [String : String]?, - nickname: String?, - product: String?) throws -> Future { - var body: [String: Any] = [:] - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let nickname = nickname { - body["nickname"] = nickname - } - - if let product = product { - body["product"] = product - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.plan(plan).endpoint, body: body.queryParameters) - } - - /// Delete a plan - /// [Learn More →](https://stripe.com/docs/api/curl#delete_plan) - public func delete(plan: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.plan(plan).endpoint) - } - - /// List all plans - /// [Learn More →](https://stripe.com/docs/api/curl#list_plans) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.plans.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/ProductRoutes.swift b/Sources/Stripe/API/Routes/ProductRoutes.swift deleted file mode 100644 index 2dac406..0000000 --- a/Sources/Stripe/API/Routes/ProductRoutes.swift +++ /dev/null @@ -1,273 +0,0 @@ -// -// ProductRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -import Vapor - -public protocol ProductRoutes { - func create(id: String?, name: String, type: String, active: Bool?, attributes: [String]?, caption: String?, deactivateOn: [String]?, description: String?, images: [String]?, metadata: [String: String]?, packageDimensions: StripePackageDimensions?, shippable: Bool?, statementDescriptor: String?, url: String?) throws -> Future - func retrieve(id: String) throws -> Future - func update(product: String, active: Bool?, attributes: [String]?, caption: String?, deactivateOn: [String]?, description: String?, images: [String]?, metadata: [String: String]?, name: String?, packageDimensions: StripePackageDimensions?, shippable: Bool?, statementDescriptor: String?, url: String?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future - func delete(id: String) throws -> Future -} - -extension ProductRoutes { - public func create(id: String? = nil, - name: String, - type: String, - active: Bool? = nil, - attributes: [String]? = nil, - caption: String? = nil, - deactivateOn: [String]? = nil, - description: String? = nil, - images: [String]? = nil, - metadata: [String : String]? = nil, - packageDimensions: StripePackageDimensions? = nil, - shippable: Bool? = nil, - statementDescriptor: String? = nil, - url: String? = nil) throws -> Future { - return try create(id: id, - name: name, - type: type, - active: active, - attributes: attributes, - caption: caption, - deactivateOn: deactivateOn, - description: description, - images: images, - metadata: metadata, - packageDimensions: packageDimensions, - shippable: shippable, - statementDescriptor: statementDescriptor, - url: url) - } - - public func retrieve(id: String) throws -> Future { - return try retrieve(id: id) - } - - public func update(product: String, - active: Bool? = nil, - attributes: [String]? = nil, - caption: String? = nil, - deactivateOn: [String]? = nil, - description: String? = nil, - images: [String]? = nil, - metadata: [String : String]? = nil, - name: String? = nil, - packageDimensions: StripePackageDimensions? = nil, - shippable: Bool? = nil, - statementDescriptor: String? = nil, - url: String? = nil) throws -> Future { - return try update(product: product, - active: active, - attributes: attributes, - caption: caption, - deactivateOn: deactivateOn, - description: description, - images: images, - metadata: metadata, - name: name, - packageDimensions: packageDimensions, - shippable: shippable, - statementDescriptor: statementDescriptor, - url: url) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - public func delete(id: String) throws -> Future { - return try delete(id: id) - } -} - -public struct StripeProductRoutes: ProductRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a product - /// [Learn More →](https://stripe.com/docs/api/curl#create_product) - public func create(id: String?, - name: String, - type: String, - active: Bool?, - attributes: [String]?, - caption: String?, - deactivateOn: [String]?, - description: String?, - images: [String]?, - metadata: [String : String]?, - packageDimensions: StripePackageDimensions?, - shippable: Bool?, - statementDescriptor: String?, - url: String?) throws -> Future { - var body: [String: Any] = [:] - - body["name"] = name - - body["type"] = type - - if let id = id { - body["id"] = id - } - - if let active = active { - body["active"] = active - } - - if let attributes = attributes { - for i in 0.. Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.products(id).endpoint) - } - - /// Update a product - /// [Learn More →](https://stripe.com/docs/api/curl#update_product) - public func update(product: String, - active: Bool?, - attributes: [String]?, - caption: String?, - deactivateOn: [String]?, - description: String?, - images: [String]?, - metadata: [String : String]?, - name: String?, - packageDimensions: StripePackageDimensions?, - shippable: Bool?, - statementDescriptor: String?, - url: String?) throws -> Future { - var body: [String: Any] = [:] - - if let active = active { - body["active"] = active - } - - if let attributes = attributes { - for i in 0.. Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.product.endpoint, query: queryParams) - } - - /// Delete a product - /// [Learn More →](https://stripe.com/docs/api/curl#delete_product) - public func delete(id: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.products(id).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/RefundRoutes.swift b/Sources/Stripe/API/Routes/RefundRoutes.swift deleted file mode 100644 index 5448d26..0000000 --- a/Sources/Stripe/API/Routes/RefundRoutes.swift +++ /dev/null @@ -1,116 +0,0 @@ -// -// RefundRoutes.swift -// Stripe -// -// Created by Anthony Castelli on 5/13/17. -// -// - -import Vapor - -public protocol RefundRoutes { - func create(charge: String, amount: Int?, metadata: [String: String]?, reason: RefundReason?, refundApplicationFee: Bool?, reverseTransfer: Bool?) throws -> Future - func retrieve(refund: String) throws -> Future - func update(refund: String, metadata: [String: String]?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension RefundRoutes { - public func create(charge: String, - amount: Int? = nil, - metadata: [String : String]? = nil, - reason: RefundReason? = nil, - refundApplicationFee: Bool? = nil, - reverseTransfer: Bool? = nil) throws -> Future { - return try create(charge: charge, - amount: amount, - metadata: metadata, - reason: reason, - refundApplicationFee: refundApplicationFee, - reverseTransfer: reverseTransfer) - } - - public func retrieve(refund: String) throws -> Future { - return try retrieve(refund: refund) - } - - public func update(refund: String, metadata: [String : String]? = nil) throws -> Future { - return try update(refund: refund, metadata: metadata) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeRefundRoutes: RefundRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a refund - /// [Learn More →](https://stripe.com/docs/api/curl#create_refund) - public func create(charge: String, - amount: Int?, - metadata: [String : String]?, - reason: RefundReason?, - refundApplicationFee: Bool?, - reverseTransfer: Bool?) throws -> Future { - var body: [String: Any] = [:] - - body["charge"] = charge - - if let amount = amount { - body["amount"] = amount - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let refundReason = reason { - body["reason"] = refundReason.rawValue - } - - if let refundApplicationFee = refundApplicationFee { - body["refund_application_fee"] = refundApplicationFee - } - - if let reverseTransfer = reverseTransfer { - body["reverse_transfer"] = reverseTransfer - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.refunds.endpoint, body: body.queryParameters) - } - - /// Retrieve a refund - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_refund) - public func retrieve(refund: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.refund(refund).endpoint) - } - - /// Update a refund - /// [Learn More →](https://stripe.com/docs/api/curl#update_refund) - public func update(refund: String, metadata: [String : String]?) throws -> Future { - var body: [String: Any] = [:] - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.refund(refund).endpoint, body: body.queryParameters) - } - - /// List all refunds - /// [Learn More →](https://stripe.com/docs/api/curl#list_refunds) - public func listAll(filter: [String : Any]? = nil) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.refunds.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/SKURoutes.swift b/Sources/Stripe/API/Routes/SKURoutes.swift deleted file mode 100644 index 21623b0..0000000 --- a/Sources/Stripe/API/Routes/SKURoutes.swift +++ /dev/null @@ -1,205 +0,0 @@ -// -// SKURoutes.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -import Vapor - -public protocol SKURoutes { - func create(id: String?, currency: StripeCurrency, inventory: StripeInventory, price: Int, product: String, active: Bool?, attributes: [String]?, image: String?, metadata: [String: String]?, packageDimensions: StripePackageDimensions?) throws -> Future - func retrieve(id: String) throws -> Future - func update(sku: String, active: Bool?, attributes: [String]?, currency: StripeCurrency?, image: String?, inventory: StripeInventory?, metadata: [String: String]?, packageDimensions: StripePackageDimensions?, price: Int?, product: String?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future - func delete(sku: String) throws -> Future -} - -extension SKURoutes { - public func create(id: String? = nil, - currency: StripeCurrency, - inventory: StripeInventory, - price: Int, - product: String, - active: Bool? = nil, - attributes: [String]? = nil, - image: String? = nil, - metadata: [String: String]? = nil, - packageDimensions: StripePackageDimensions? = nil) throws -> Future { - return try create(id: id, - currency: currency, - inventory: inventory, - price: price, - product: product, - active: active, - attributes: attributes, - image: image, - metadata: metadata, - packageDimensions: packageDimensions) - } - - public func retrieve(id: String) throws -> Future { - return try retrieve(id: id) - } - - public func update(sku: String, - active: Bool? = nil, - attributes: [String]? = nil, - currency: StripeCurrency? = nil, - image: String? = nil, - inventory: StripeInventory? = nil, - metadata: [String: String]? = nil, - packageDimensions: StripePackageDimensions? = nil, - price: Int? = nil, - product: String? = nil) throws -> Future { - return try update(sku: sku, - active: active, - attributes: attributes, - currency: currency, - image: image, - inventory: inventory, - metadata: metadata, - packageDimensions: packageDimensions, - price: price, - product: product) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - public func delete(sku: String) throws -> Future { - return try delete(sku: sku) - } -} - -public struct StripeSKURoutes: SKURoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a SKU - /// [Learn More →](https://stripe.com/docs/api/curl#create_sku) - public func create(id: String?, - currency: StripeCurrency, - inventory: StripeInventory, - price: Int, - product: String, - active: Bool?, - attributes: [String]?, - image: String?, - metadata: [String: String]?, - packageDimensions: StripePackageDimensions?) throws -> Future { - var body: [String: Any] = [:] - - body["currency"] = currency.rawValue - try inventory.toEncodedDictionary().forEach { body["inventory[\($0)]"] = $1 } - body["price"] = price - body["product"] = product - - if let active = active { - body["active"] = active - } - - if let attributes = attributes { - for i in 0.. Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.skus(id).endpoint) - } - - /// Update a SKU - /// [Learn More →](https://stripe.com/docs/api/curl#update_sku) - public func update(sku: String, - active: Bool?, - attributes: [String]?, - currency: StripeCurrency?, - image: String?, - inventory: StripeInventory?, - metadata: [String: String]?, - packageDimensions: StripePackageDimensions?, - price: Int?, - product: String?) throws -> Future { - var body: [String: Any] = [:] - - if let active = active { - body["active"] = active - } - - if let attributes = attributes { - for i in 0.. Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.sku.endpoint, query: queryParams) - } - - /// Delete a SKU - /// [Learn More →](https://stripe.com/docs/api/curl#delete_sku) - public func delete(sku: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.skus(sku).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/SourceRoutes.swift b/Sources/Stripe/API/Routes/SourceRoutes.swift deleted file mode 100644 index 260e89b..0000000 --- a/Sources/Stripe/API/Routes/SourceRoutes.swift +++ /dev/null @@ -1,161 +0,0 @@ -// -// SourceRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 6/1/17. -// -// - -import Vapor - -public protocol SourceRoutes { - func create(type: SourceType, amount: Int?, currency: StripeCurrency?, flow: Flow?, mandate: StripeMandate?, metadata: [String: String]?, owner: StripeOwner?, receiver: [String: String]?, redirect: [String: String]?, statementDescriptor: String?, token: String?, usage: String?) throws -> Future - func retrieve(source: String, clientSecret: String?) throws -> Future - func update(source: String, mandate: StripeMandate?, metadata: [String: String]?, owner: StripeOwner?) throws -> Future -} - -extension SourceRoutes { - public func create(type: SourceType, - amount: Int? = nil, - currency: StripeCurrency? = nil, - flow: Flow? = nil, - mandate: StripeMandate? = nil, - metadata: [String: String]? = nil, - owner: StripeOwner? = nil, - receiver: [String: String]? = nil, - redirect: [String: String]? = nil, - statementDescriptor: String? = nil, - token: String? = nil, - usage: String? = nil) throws -> Future { - return try create(type: type, - amount: amount, - currency: currency, - flow: flow, - mandate: mandate, - metadata: metadata, - owner: owner, - receiver: receiver, - redirect: redirect, - statementDescriptor: statementDescriptor, - token: token, - usage: usage) - } - - public func retrieve(source: String, clientSecret: String? = nil) throws -> Future { - return try retrieve(source: source, clientSecret: clientSecret) - } - - public func update(source: String, - mandate: StripeMandate? = nil, - metadata: [String: String]? = nil, - owner: StripeOwner? = nil) throws -> Future { - return try update(source: source, - mandate: mandate, - metadata: metadata, - owner: owner) - } - -} - -public struct StripeSourceRoutes: SourceRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a source - /// [Learn More →](https://stripe.com/docs/api/curl#create_source) - public func create(type: SourceType, - amount: Int?, - currency: StripeCurrency?, - flow: Flow?, - mandate: StripeMandate?, - metadata: [String: String]?, - owner: StripeOwner?, - receiver: [String: String]?, - redirect: [String: String]?, - statementDescriptor: String?, - token: String?, - usage: String?) throws -> Future { - var body: [String: Any] = [:] - - body["type"] = type.rawValue - - if let currency = currency { - body["currency"] = currency.rawValue - } - - if let flow = flow { - body["flow"] = flow.rawValue - } - - if let mandate = mandate { - try mandate.toEncodedDictionary().forEach { body["mandate[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let owner = owner { - try owner.toEncodedDictionary().forEach { body["owner[\($0)]"] = $1 } - } - - if let receiver = receiver { - receiver.forEach { body["receiver[\($0)]"] = $1 } - } - - if let redirect = redirect { - redirect.forEach { body["redirect[\($0)]"] = $1 } - } - - if let statementDescriptor = statementDescriptor { - body["statement_descriptor"] = statementDescriptor - } - - if let token = token { - body["token"] = token - } - - if let usage = usage { - body["usage"] = usage - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.sources.endpoint, body: body.queryParameters) - } - - /// Retrieve a source - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_source) - public func retrieve(source: String, clientSecret: String?) throws -> Future { - var query = "" - if let clientSecret = clientSecret { - query = "client_secret=\(clientSecret)" - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.source(source).endpoint, query: query) - } - - /// Update a source - /// [Learn More →](https://stripe.com/docs/api/curl#update_source) - public func update(source: String, - mandate: StripeMandate?, - metadata: [String: String]?, - owner: StripeOwner?) throws -> Future { - var body: [String: Any] = [:] - - if let mandate = mandate { - try mandate.toEncodedDictionary().forEach { body["mandate[\($0)]"] = $1 } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let owner = owner { - try owner.toEncodedDictionary().forEach { body["owner[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.source(source).endpoint, body: body.queryParameters) - } -} diff --git a/Sources/Stripe/API/Routes/SubscriptionItemRoutes.swift b/Sources/Stripe/API/Routes/SubscriptionItemRoutes.swift deleted file mode 100644 index ddc0340..0000000 --- a/Sources/Stripe/API/Routes/SubscriptionItemRoutes.swift +++ /dev/null @@ -1,173 +0,0 @@ -// -// SubscriptionItemRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 6/6/17. -// -// - -import Vapor -import Foundation - -public protocol SubscriptionItemRoutes { - func create(plan: String, subscription: String, metadata: [String: String]?, prorate: Bool?, prorationDate: Date?, quantity: Int?) throws -> Future - func retrieve(item: String) throws -> Future - func update(item: String, metadata: [String: String]?, plan: String?, prorate: Bool?, prorationDate: Date?, quantity: Int?) throws -> Future - func delete(item: String, prorate: Bool?, prorationDate: Date?) throws -> Future - func listAll(subscription: String, filter: [String: Any]?) throws -> Future -} - -extension SubscriptionItemRoutes { - public func create(plan: String, - subscription: String, - metadata: [String : String]? = nil, - prorate: Bool? = nil, - prorationDate: Date? = nil, - quantity: Int? = nil) throws -> Future { - return try create(plan: plan, - subscription: subscription, - metadata: metadata, - prorate: prorate, - prorationDate: prorationDate, - quantity: quantity) - } - - public func retrieve(item: String) throws -> Future { - return try retrieve(item: item) - } - - public func update(item: String, - metadata: [String : String]? = nil, - plan: String? = nil, - prorate: Bool? = nil, - prorationDate: Date? = nil, - quantity: Int? = nil) throws -> Future { - return try update(item: item, - metadata: metadata, - plan: plan, - prorate: prorate, - prorationDate: prorationDate, - quantity: quantity) - } - - public func delete(item: String, - prorate: Bool? = nil, - prorationDate: Date? = nil) throws -> Future { - return try delete(item: item, - prorate: prorate, - prorationDate: prorationDate) - } - - public func listAll(subscription: String, filter: [String : Any]? = nil) throws -> Future { - return try listAll(subscription: subscription, filter: filter) - } - -} - -public struct StripeSubscriptionItemRoutes: SubscriptionItemRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a subscription item - /// [Learn More →](https://stripe.com/docs/api/curl#create_subscription_item) - public func create(plan: String, - subscription: String, - metadata: [String : String]?, - prorate: Bool?, - prorationDate: Date?, - quantity: Int?) throws -> Future { - var body: [String: Any] = [:] - - body["plan"] = plan - body["subscription"] = subscription - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let prorate = prorate { - body["prorate"] = prorate - } - - if let prorationDate = prorationDate { - body["proration_date"] = Int(prorationDate.timeIntervalSince1970) - } - - if let quantity = quantity { - body["quantity"] = quantity - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.subscriptionItem.endpoint, body: body.queryParameters) - } - - /// Retrieve a subscription item - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_subscription_item) - public func retrieve(item: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.subscriptionItems(item).endpoint) - } - - /// Update a subscription item - /// [Learn More →](https://stripe.com/docs/api/curl#update_subscription_item) - public func update(item: String, - metadata: [String : String]?, - plan: String?, - prorate: Bool?, - prorationDate: Date?, - quantity: Int?) throws -> Future { - var body: [String: Any] = [:] - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let plan = plan { - body["plan"] = plan - } - - if let prorate = prorate { - body["prorate"] = prorate - } - - if let prorationDate = prorationDate { - body["proration_date"] = Int(prorationDate.timeIntervalSince1970) - } - - if let quantity = quantity { - body["quantity"] = quantity - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.subscriptionItems(item).endpoint, body: body.queryParameters) - } - - /// Delete a subscription item - /// [Learn More →](https://stripe.com/docs/api/curl#delete_subscription_item) - public func delete(item: String, - prorate: Bool?, - prorationDate: Date?) throws -> Future { - var body: [String: Any] = [:] - - if let prorate = prorate { - body["prorate"] = prorate - } - - if let prorationDate = prorationDate { - body["proration_date"] = Int(prorationDate.timeIntervalSince1970) - } - - return try request.send(method: .DELETE, path: StripeAPIEndpoint.subscriptionItems(item).endpoint, body: body.queryParameters) - } - - /// List all subscription items - /// [Learn More →](https://stripe.com/docs/api/curl#list_subscription_item) - public func listAll(subscription: String, filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.subscriptionItems(subscription).endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/Routes/SubscriptionRoutes.swift b/Sources/Stripe/API/Routes/SubscriptionRoutes.swift deleted file mode 100644 index c8e5f21..0000000 --- a/Sources/Stripe/API/Routes/SubscriptionRoutes.swift +++ /dev/null @@ -1,312 +0,0 @@ -// -// SubscriptionRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 6/9/17. -// -// - -import Vapor -import Foundation - -public protocol SubscriptionRoutes { - func create(customer: String, applicationFeePercent: Decimal?, billing: String?, billingCycleAnchor: Date?, cancelAtPeriodEnd: Bool?, coupon: String?, daysUntilDue: Int?, items: [[String : Any]]?, metadata: [String: String]?, prorate: Bool?, taxPercent: Decimal?, trialEnd: Any?, trialFromPlan: Bool?, trialPeriodDays: Int?) throws -> Future - func retrieve(id: String) throws -> Future - func update(subscription: String, applicationFeePercent: Decimal?, billing: String?, billingCycleAnchor: String?, cancelAtPeriodEnd: Bool?, coupon: String?, daysUntilDue: Int?, items: [[String: Any]]?, metadata: [String: String]?, prorate: Bool?, prorationDate: Date?, taxPercent: Decimal?, trialEnd: Any?, trialFromPlan: Bool?) throws -> Future - func cancel(subscription: String, invoiceNow: Bool?, prorate: Bool?) throws -> Future - @available(*, deprecated, message: "Use update(subscription:cancelAtPeriodEnd:) instead") - func cancel(subscription: String, atPeriodEnd: Bool) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future - func deleteDiscount(subscription: String) throws -> Future -} - -extension SubscriptionRoutes { - public func create(customer: String, - applicationFeePercent: Decimal? = nil, - billing: String? = nil, - billingCycleAnchor: Date? = nil, - cancelAtPeriodEnd: Bool? = nil, - coupon: String? = nil, - daysUntilDue: Int? = nil, - items: [[String: Any]]? = nil, - metadata: [String: String]? = nil, - prorate: Bool? = nil, - taxPercent: Decimal? = nil, - trialEnd: Any? = nil, - trialFromPlan: Bool? = nil, - trialPeriodDays: Int? = nil) throws -> Future { - return try create(customer: customer, - applicationFeePercent: applicationFeePercent, - billing: billing, - billingCycleAnchor: billingCycleAnchor, - cancelAtPeriodEnd: cancelAtPeriodEnd, - coupon: coupon, - daysUntilDue: daysUntilDue, - items: items, - metadata: metadata, - prorate: prorate, - taxPercent: taxPercent, - trialEnd: trialEnd, - trialFromPlan: trialFromPlan, - trialPeriodDays: trialPeriodDays) - } - - public func retrieve(id: String) throws -> Future { - return try retrieve(id: id) - } - - public func update(subscription: String, - applicationFeePercent: Decimal? = nil, - billing: String? = nil, - billingCycleAnchor: String? = nil, - cancelAtPeriodEnd: Bool? = nil, - coupon: String? = nil, - daysUntilDue: Int? = nil, - items: [[String: Any]]? = nil, - metadata: [String: String]? = nil, - prorate: Bool? = nil, - prorationDate: Date? = nil, - taxPercent: Decimal? = nil, - trialEnd: Any? = nil, - trialFromPlan: Bool? = nil) throws -> Future { - return try update(subscription: subscription, - applicationFeePercent: applicationFeePercent, - billing: billing, - billingCycleAnchor: billingCycleAnchor, - cancelAtPeriodEnd: cancelAtPeriodEnd, - coupon: coupon, - daysUntilDue: daysUntilDue, - items: items, - metadata: metadata, - prorate: prorate, - prorationDate: prorationDate, - taxPercent: taxPercent, - trialEnd: trialEnd, - trialFromPlan: trialFromPlan) - } - - public func cancel(subscription: String, invoiceNow: Bool? = nil, prorate: Bool? = nil) throws -> Future { - return try cancel(subscription: subscription, invoiceNow: invoiceNow, prorate: prorate) - } - - public func listAll(filter: [String : Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } - - public func deleteDiscount(subscription: String) throws -> Future { - return try deleteDiscount(subscription: subscription) - } -} - -public struct StripeSubscriptionRoutes: SubscriptionRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a subscription - /// [Learn More →](https://stripe.com/docs/api/curl#create_subscription) - public func create(customer: String, - applicationFeePercent: Decimal?, - billing: String?, - billingCycleAnchor: Date?, - cancelAtPeriodEnd: Bool?, - coupon: String?, - daysUntilDue: Int?, - items: [[String : Any]]?, - metadata: [String : String]?, - prorate: Bool?, - taxPercent: Decimal?, - trialEnd: Any?, - trialFromPlan: Bool?, - trialPeriodDays: Int?) throws -> Future { - var body: [String: Any] = [:] - - body["customer"] = customer - - if let applicationFeePercent = applicationFeePercent { - body["application_fee_percent"] = applicationFeePercent - } - - if let billing = billing { - body["billing"] = billing - } - - if let billingCycleAnchor = billingCycleAnchor { - body["billing_cycle_anchor"] = Int(billingCycleAnchor.timeIntervalSince1970) - } - - if let cancelAtPeriodEnd = cancelAtPeriodEnd { - body["cancel_at_period_end"] = cancelAtPeriodEnd - } - - if let coupon = coupon { - body["coupon"] = coupon - } - - if let daysUntilDue = daysUntilDue { - body["days_until_due"] = daysUntilDue - } - - if let items = items { - for (index, item) in items.enumerated() { - item.forEach { body["items[\(index)][\($0)]"] = $1 } - } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let prorate = prorate { - body["prorate"] = prorate - } - - if let taxPercent = taxPercent { - body["tax_percent"] = taxPercent - } - - if let trialEnd = trialEnd as? Date { - body["trial_end"] = Int(trialEnd.timeIntervalSince1970) - } - - if let trialEnd = trialEnd as? String { - body["trial_end"] = trialEnd - } - - if let trialFromPlan = trialFromPlan { - body["trial_from_plan"] = trialFromPlan - } - - if let trialPeriodDays = trialPeriodDays { - body["trial_period_days"] = trialPeriodDays - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.subscription.endpoint, body: body.queryParameters) - } - - /// Retrieve a subscription - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_subscription) - public func retrieve(id: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.subscriptions(id).endpoint) - } - - /// Update a subscription - /// [Learn More →](https://stripe.com/docs/api/curl#update_subscription) - public func update(subscription: String, - applicationFeePercent: Decimal?, - billing: String?, - billingCycleAnchor: String?, - cancelAtPeriodEnd: Bool?, - coupon: String?, - daysUntilDue: Int?, - items: [[String : Any]]?, - metadata: [String : String]?, - prorate: Bool?, - prorationDate: Date?, - taxPercent: Decimal?, - trialEnd: Any?, - trialFromPlan: Bool?) throws -> Future { - var body: [String: Any] = [:] - - if let applicationFeePercent = applicationFeePercent { - body["application_fee_percent"] = applicationFeePercent - } - - if let billing = billing { - body["billing"] = billing - } - - if let billingCycleAnchor = billingCycleAnchor { - body["billing_cycle_anchor"] = billingCycleAnchor - } - - if let cancelAtPeriodEnd = cancelAtPeriodEnd { - body["cancel_at_period_end"] = cancelAtPeriodEnd - } - - if let coupon = coupon { - body["coupon"] = coupon - } - - if let daysUntilDue = daysUntilDue { - body["days_until_due"] = daysUntilDue - } - - if let items = items { - for (index, item) in items.enumerated() { - item.forEach { body["items[\(index)][\($0)]"] = $1 } - } - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let prorate = prorate { - body["prorate"] = prorate - } - - if let prorationDate = prorationDate { - body["proration_date"] = Int(prorationDate.timeIntervalSince1970) - } - - if let taxPercent = taxPercent { - body["tax_percent"] = taxPercent - } - - if let trialEnd = trialEnd as? Date { - body["trial_end"] = Int(trialEnd.timeIntervalSince1970) - } - - if let trialEnd = trialEnd as? String { - body["trial_end"] = trialEnd - } - - if let trialFromPlan = trialFromPlan { - body["trial_from_plan"] = trialFromPlan - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.subscriptions(subscription).endpoint, body: body.queryParameters) - } - - /// Cancel a subscription - /// [Learn More →](https://stripe.com/docs/api/curl#cancel_subscription) - public func cancel(subscription: String, invoiceNow: Bool?, prorate: Bool?) throws -> Future { - var body: [String: Any] = [:] - - if let invoiceNow = invoiceNow { - body["invoice_now"] = invoiceNow - } - - if let prorate = prorate { - body["prorate"] = prorate - } - - return try request.send(method: .DELETE, path: StripeAPIEndpoint.subscriptions(subscription).endpoint, body: body.queryParameters) - } - - @available(*, deprecated, message: "Use update(subscription:cancelAtPeriodEnd:) instead") - public func cancel(subscription: String, atPeriodEnd: Bool) throws -> Future { - let body = ["at_period_end": atPeriodEnd] - return try request.send(method: .DELETE, path: StripeAPIEndpoint.subscriptions(subscription).endpoint, body: body.queryParameters) - } - - /// List subscriptions - /// [Learn More →](https://stripe.com/docs/api/curl#list_subscriptions) - public func listAll(filter: [String : Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - - return try request.send(method: .GET, path: StripeAPIEndpoint.subscription.endpoint, query: queryParams) - } - - /// Delete a subscription discount - /// [Learn More →](https://stripe.com/docs/api/curl#delete_subscription_discount) - public func deleteDiscount(subscription: String) throws -> Future { - return try request.send(method: .DELETE, path: StripeAPIEndpoint.subscriptionDiscount(subscription).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/TokenRoutes.swift b/Sources/Stripe/API/Routes/TokenRoutes.swift deleted file mode 100644 index 83e42fd..0000000 --- a/Sources/Stripe/API/Routes/TokenRoutes.swift +++ /dev/null @@ -1,114 +0,0 @@ -// -// TokenRoutes.swift -// Stripe -// -// Created by Anthony Castelli on 5/12/17. -// -// - -import Vapor - -public protocol TokenRoutes { - func createCard(card: [String: Any]?, customer: String?, connectAccount: String?) throws -> Future - func createBankAccount(bankAcocunt: [String: Any]?, customer: String?, connectAccount: String?) throws -> Future - func createPII(personalId: String?) throws -> Future - func retrieve(token: String) throws -> Future -} - -extension TokenRoutes { - public func createCard(card: [String: Any]? = nil, - customer: String? = nil, - connectAccount: String? = nil) throws -> Future { - return try createCard(card: card, - customer: customer, - connectAccount: connectAccount) - } - - public func createBankAccount(bankAcocunt: [String: Any]? = nil, - customer: String? = nil, - connectAccount: String? = nil) throws -> Future { - return try createBankAccount(bankAcocunt: bankAcocunt, - customer: customer, - connectAccount: connectAccount) - } - - public func createPII(personalId: String? = nil) throws -> Future { - return try createPII(personalId: personalId) - } - - public func retrieve(token: String) throws -> Future { - return try retrieve(token: token) - } -} - -public struct StripeTokenRoutes: TokenRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a card token - /// [Learn More →](https://stripe.com/docs/api/curl#create_card_token) - public func createCard(card: [String: Any]?, - customer: String?, - connectAccount: String?) throws -> Future { - var body: [String: Any] = [:] - var headers: HTTPHeaders = [:] - - if let card = card { - card.forEach { body["card[\($0)]"] = $1 } - } - - if let customer = customer { - body["customer"] = customer - } - - if let connectAccount = connectAccount { - headers.add(name: .stripeAccount, value: connectAccount) - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.tokens.endpoint, body: body.queryParameters, headers: headers) - } - - /// Create a bank account token - /// [Learn More →](https://stripe.com/docs/api/curl#create_bank_account_token) - public func createBankAccount(bankAcocunt: [String: Any]?, - customer: String?, - connectAccount: String?) throws -> Future { - var body: [String: Any] = [:] - var headers: HTTPHeaders = [:] - - if let bankAcocunt = bankAcocunt { - bankAcocunt.forEach { body["bank_account[\($0)]"] = $1 } - } - - if let customer = customer { - body["customer"] = customer - } - - if let connectAccount = connectAccount { - headers.add(name: .stripeAccount, value: connectAccount) - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.tokens.endpoint, body: body.queryParameters, headers: headers) - } - - /// Create a PII token - /// [Learn More →](https://stripe.com/docs/api/curl#create_pii_token) - public func createPII(personalId: String?) throws -> Future { - var body: [String: Any] = [:] - - if let personalId = personalId { - body["personal_id_number"] = personalId - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.tokens.endpoint, body: body.queryParameters) - } - - /// Retrieve a token - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_token) - public func retrieve(token: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.token(token).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/TopUpRoutes.swift b/Sources/Stripe/API/Routes/TopUpRoutes.swift deleted file mode 100644 index fac3f80..0000000 --- a/Sources/Stripe/API/Routes/TopUpRoutes.swift +++ /dev/null @@ -1,166 +0,0 @@ -// -// TopUpRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 3/24/19. -// - -import Vapor - -public protocol TopUpRoutes { - /// Top up the balance of an account - /// - /// - Parameters: - /// - amount: A positive integer representing how much to transfer. - /// - currency: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). - /// - description: An arbitrary string attached to the object. Often useful for displaying to users. This will be unset if you POST an empty value. - /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. - /// - source: The ID of a source to transfer funds from. For most users, this should be left unspecified which will use the bank account that was set up in the dashboard for the specified currency. In test mode, this can be a test bank token (see [Testing Top-ups](https://stripe.com/docs/connect/testing#testing-top-ups)). - /// - statementDescriptor: Extra information about a top-up for the source’s bank statement. Limited to 15 ASCII characters. - /// - transferGroup: A string that identifies this top-up as part of a group. - /// - Returns: A `StripeTopUp`. - /// - Throws: A `StripeError`. - func create(amount: Int, - currency: StripeCurrency, - description: String?, - metadata: [String: String]?, - source: String?, - statementDescriptor: String?, - transferGroup: String?) throws -> EventLoopFuture - - /// Retrieves the details of a top-up that has previously been created. Supply the unique top-up ID that was returned from your previous request, and Stripe will return the corresponding top-up information. - /// - /// - Parameter id: The ID of the top-up to retrieve. - /// - Returns: A `StripeTopUp`. - /// - Throws: A `StripeError`. - func retrieve(id: String) throws -> EventLoopFuture - - /// Updates the metadata of a top-up. Other top-up details are not editable by design. - /// - /// - Parameters: - /// - topup: The ID of the top-up to retrieve. - /// - description: An arbitrary string attached to the object. Often useful for displaying to users. This will be unset if you POST an empty value. - /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. - /// - Returns: A `StripeTopUp`. - /// - Throws: A `StripeError`. - func update(topup: String, description: String?, metadata: [String: String]?) throws -> EventLoopFuture - - /// Returns a list of top-ups. - /// - /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/topups/list). - /// - Returns: A `StripeTopUpList`. - /// - Throws: A `StripeError`. - func listAll(filter: [String: Any]?) throws -> EventLoopFuture - - /// Cancels a top-up. Only pending top-ups can be canceled. - /// - /// - Parameter topup: The ID of the top-up to cancel. - /// - Returns: A canceled `StripeTopUp`. - /// - Throws: A `StripeError`. - func cancel(topup: String) throws -> EventLoopFuture -} - -extension TopUpRoutes { - public func create(amount: Int, - currency: StripeCurrency, - description: String? = nil, - metadata: [String: String]? = nil, - source: String? = nil, - statementDescriptor: String? = nil, - transferGroup: String? = nil) throws -> EventLoopFuture { - return try create(amount: amount, - currency: currency, - description: description, - metadata: metadata, - source: source, - statementDescriptor: statementDescriptor, - transferGroup: transferGroup) - } - - public func retrieve(id: String) throws -> EventLoopFuture { - return try retrieve(id: id) - } - - public func update(topup: String, description: String? = nil, metadata: [String: String]? = nil) throws -> EventLoopFuture { - return try update(topup: topup, description: description, metadata: metadata) - } - - public func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture { - return try listAll(filter: filter) - } - - public func cancel(topup: String) throws -> EventLoopFuture { - return try cancel(topup: topup) - } -} - -public struct StripeTopUpRoutes: TopUpRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - public func create(amount: Int, - currency: StripeCurrency, - description: String?, - metadata: [String: String]?, - source: String?, - statementDescriptor: String?, - transferGroup: String?) throws -> EventLoopFuture { - var body: [String: Any] = ["amount": amount, - "currency": currency.rawValue] - - if let description = description { - body["description"] = description - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let source = source { - body["source"] = source - } - - if let statementDescriptor = statementDescriptor { - body["statement_descriptor"] = statementDescriptor - } - - if let transferGroup = transferGroup { - body["transfer_group"] = transferGroup - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.topup.endpoint, body: body.queryParameters) - } - - public func retrieve(id: String) throws -> EventLoopFuture { - return try request.send(method: .GET, path: StripeAPIEndpoint.topups(id).endpoint) - } - - public func update(topup: String, description: String?, metadata: [String: String]?) throws -> EventLoopFuture { - var body: [String: Any] = [:] - - if let description = description { - body["description"] = description - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.topups(topup).endpoint, body: body.queryParameters) - } - - public func listAll(filter: [String: Any]?) throws -> EventLoopFuture { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.topup.endpoint, query: queryParams) - } - - public func cancel(topup: String) throws -> EventLoopFuture { - return try request.send(method: .POST, path: StripeAPIEndpoint.topupsCancel(topup).endpoint) - } -} diff --git a/Sources/Stripe/API/Routes/TransferReversalRoutes.swift b/Sources/Stripe/API/Routes/TransferReversalRoutes.swift deleted file mode 100644 index 021db99..0000000 --- a/Sources/Stripe/API/Routes/TransferReversalRoutes.swift +++ /dev/null @@ -1,112 +0,0 @@ -// -// TransferReversalRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 4/3/18. -// - -import Vapor - -public protocol TransferReversalRoutes { - func create(id: String, amount: Int?, description: String?, metadata: [String: String]?, refundApplicationFee: Bool?) throws -> Future - func retrieve(transfer: String, reversal: String) throws -> Future - func update(transfer: String, reversal: String, metadata: [String: String]?) throws -> Future - func listAll(reversal: String, filter: [String: Any]?) throws -> Future -} - -extension TransferReversalRoutes { - public func create(id: String, - amount: Int? = nil, - description: String? = nil, - metadata: [String: String]? = nil, - refundApplicationFee: Bool? = nil) throws -> Future { - return try create(id: id, - amount: amount, - description: description, - metadata: metadata, - refundApplicationFee: refundApplicationFee) - } - - public func retrieve(transfer: String, reversal: String) throws -> Future { - return try retrieve(transfer: transfer, reversal: reversal) - } - - public func update(transfer: String, - reversal: String, - metadata: [String: String]? = nil) throws -> Future { - return try update(transfer: transfer, - reversal: reversal, - metadata: metadata) - } - - public func listAll(reversal: String, filter: [String: Any]? = nil) throws -> Future { - return try listAll(reversal: reversal, filter: filter) - } - -} - -public struct StripeTransferReversalRoutes: TransferReversalRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a transfer reversal - /// [Learn More →](https://stripe.com/docs/api/curl#create_transfer_reversal) - public func create(id: String, - amount: Int?, - description: String?, - metadata: [String: String]?, - refundApplicationFee: Bool?) throws -> Future { - var body: [String: Any] = [:] - - if let amount = amount { - body["amount"] = amount - } - - if let description = description { - body["description"] = description - } - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let refundApplicationFee = refundApplicationFee { - body["refund_application_fee"] = refundApplicationFee - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.transferReversal(id).endpoint, body: body.queryParameters) - } - - /// Retrieve a reversal - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_transfer_reversal) - public func retrieve(transfer: String, reversal: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.transfersReversal(transfer, reversal).endpoint) - } - - /// Update a reversal - /// [Learn More →](https://stripe.com/docs/api/curl#update_transfer_reversal) - public func update(transfer: String, - reversal: String, - metadata: [String: String]?) throws -> Future { - var body: [String: Any] = [:] - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.transfersReversal(transfer, reversal).endpoint, body: body.queryParameters) - } - - /// List all reversals - /// [Learn More →](https://stripe.com/docs/api/curl#list_transfer_reversals) - public func listAll(reversal: String, filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.transferReversal(reversal).endpoint, query: queryParams) - } -} - diff --git a/Sources/Stripe/API/Routes/TransferRoutes.swift b/Sources/Stripe/API/Routes/TransferRoutes.swift deleted file mode 100644 index cd639b5..0000000 --- a/Sources/Stripe/API/Routes/TransferRoutes.swift +++ /dev/null @@ -1,106 +0,0 @@ -// -// TransferRoutes.swift -// Stripe -// -// Created by Andrew Edwards on 4/3/18. -// - -import Vapor - -public protocol TransferRoutes { - func create(amount: Int, currency: StripeCurrency, destination: String, metadata: [String: String]?, sourceTransaction: String?, transferGroup: String?) throws -> Future - func retrieve(transfer: String) throws -> Future - func update(transfer: String, metadata: [String: String]?) throws -> Future - func listAll(filter: [String: Any]?) throws -> Future -} - -extension TransferRoutes { - public func create(amount: Int, - currency: StripeCurrency, - destination: String, - metadata: [String: String]? = nil, - sourceTransaction: String? = nil, - transferGroup: String? = nil) throws -> EventLoopFuture { - return try create(amount: amount, - currency: currency, - destination: destination, - metadata: metadata, - sourceTransaction: sourceTransaction, - transferGroup: transferGroup) - } - - public func retrieve(transfer: String) throws -> Future { - return try retrieve(transfer: transfer) - } - - public func update(transfer: String, metadata: [String: String]? = nil) throws -> Future { - return try update(transfer: transfer, metadata: metadata) - } - - public func listAll(filter: [String: Any]? = nil) throws -> Future { - return try listAll(filter: filter) - } -} - -public struct StripeTransferRoutes: TransferRoutes { - private let request: StripeRequest - - init(request: StripeRequest) { - self.request = request - } - - /// Create a transfer - /// [Learn More →](https://stripe.com/docs/api/curl#create_transfer) - public func create(amount: Int, - currency: StripeCurrency, - destination: String, - metadata: [String: String]?, - sourceTransaction: String?, - transferGroup: String?) throws -> Future { - var body: [String: Any] = [:] - body["amount"] = amount - body["currency"] = currency.rawValue - body["destination"] = destination - - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - if let sourceTransaction = sourceTransaction { - body["source_transaction"] = sourceTransaction - } - - if let transferGroup = transferGroup { - body["transfer_group"] = transferGroup - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.transfer.endpoint, body: body.queryParameters) - } - - /// Retrieve a transfer - /// [Learn More →](https://stripe.com/docs/api/curl#retrieve_transfer) - public func retrieve(transfer: String) throws -> Future { - return try request.send(method: .GET, path: StripeAPIEndpoint.transfers(transfer).endpoint) - } - - /// Update a transfer - /// [Learn More →](https://stripe.com/docs/api/curl#update_transfer) - public func update(transfer: String, metadata: [String: String]?) throws -> Future { - var body: [String: Any] = [:] - if let metadata = metadata { - metadata.forEach { body["metadata[\($0)]"] = $1 } - } - - return try request.send(method: .POST, path: StripeAPIEndpoint.transfers(transfer).endpoint, body: body.queryParameters) - } - - /// List all transfers - /// [Learn More →](https://stripe.com/docs/api/curl#list_transfers) - public func listAll(filter: [String: Any]?) throws -> Future { - var queryParams = "" - if let filter = filter { - queryParams = filter.queryParameters - } - return try request.send(method: .GET, path: StripeAPIEndpoint.transfer.endpoint, query: queryParams) - } -} diff --git a/Sources/Stripe/API/StripeRequest.swift b/Sources/Stripe/API/StripeRequest.swift deleted file mode 100644 index baa8971..0000000 --- a/Sources/Stripe/API/StripeRequest.swift +++ /dev/null @@ -1,80 +0,0 @@ -// -// StripeRequest.swift -// Stripe -// -// Created by Anthony Castelli on 4/13/17. -// -// - -import Foundation -import Vapor -import HTTP - -public protocol StripeRequest: class { - func serializedResponse(response: HTTPResponse, worker: EventLoop) throws -> Future - func send(method: HTTPMethod, path: String, query: String, body: LosslessHTTPBodyRepresentable, headers: HTTPHeaders) throws -> Future -} - -public extension StripeRequest { - public func send(method: HTTPMethod, path: String, query: String = "", body: LosslessHTTPBodyRepresentable = HTTPBody(string: ""), headers: HTTPHeaders = [:]) throws -> Future { - return try send(method: method, path: path, query: query, body: body, headers: headers) - } - - public func serializedResponse(response: HTTPResponse, worker: EventLoop) throws -> Future { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - guard response.status == .ok else { - return try decoder.decode(StripeError.self, from: response, maxSize: 1_000_000, on: worker).map(to: SM.self){ error in - throw error - } - } - - return try decoder.decode(SM.self, from: response, maxSize: 1_000_000, on: worker) - } -} - -extension HTTPHeaderName { - public static var stripeVersion: HTTPHeaderName { - return .init("Stripe-Version") - } - public static var stripeAccount: HTTPHeaderName { - return .init("Stripe-Account") - } -} - -extension HTTPHeaders { - public static var stripeDefault: HTTPHeaders { - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .stripeVersion, value: "2019-02-19") - headers.replaceOrAdd(name: .contentType, value: MediaType.urlEncodedForm.description) - return headers - } -} - -public class StripeAPIRequest: StripeRequest { - private let httpClient: Client - private let apiKey: String - private let testApiKey: String? - - init(httpClient: Client, apiKey: String, testApiKey: String?) { - self.httpClient = httpClient - self.apiKey = apiKey - self.testApiKey = testApiKey - } - - public func send(method: HTTPMethod, path: String, query: String, body: LosslessHTTPBodyRepresentable, headers: HTTPHeaders) throws -> Future { - var finalHeaders: HTTPHeaders = .stripeDefault - - // Get the appropiate API key based on the environment and if the test key is present - let apiKey = self.httpClient.container.environment == .development ? (self.testApiKey ?? self.apiKey) : self.apiKey - finalHeaders.add(name: .authorization, value: "Bearer \(apiKey)") - headers.forEach { finalHeaders.replaceOrAdd(name: $0.name, value: $0.value) } - - return httpClient.send(method, headers: finalHeaders, to: "\(path)?\(query)") { (request) in - request.http.body = body.convertToHTTPBody() - }.flatMap(to: SM.self) { (response) -> Future in - return try self.serializedResponse(response: response.http, worker: self.httpClient.container.eventLoop) - } - } -} diff --git a/Sources/Stripe/Errors/StripeError.swift b/Sources/Stripe/Errors/StripeError.swift deleted file mode 100644 index d790811..0000000 --- a/Sources/Stripe/Errors/StripeError.swift +++ /dev/null @@ -1,217 +0,0 @@ -// -// StripeError.swift -// Stripe -// -// Created by Anthony Castelli on 4/13/17. -// -// - -import Foundation -import Vapor -/** - Error object - https://stripe.com/docs/api#errors - */ - -public enum StripeUploadError: Error, Debuggable { - case unsupportedFileType - - public var localizedDescription: String { - return "Unsupported file type used for file upload." - } - - public var identifier: String { - return "file-upload-error" - } - - public var reason: String { - return localizedDescription - } - - public var possibleCauses: [String] { - return ["Unsupported file type used for file upload."] - } - - public var suggestedFixes: [String] { - return ["Use one of the following supported filetypes for uploads.", - "CSV", - "DOCX", - "GIF", - "JPEG", - "PDF", - "PNG", - "XLS", - "XLSX"] - } -} - -public struct StripeError: StripeModel, Error, Debuggable { - public var identifier: String { - return self.error.type.rawValue - } - public var reason: String { - return self.error.message - } - public var error: StripeAPIError -} - -public struct StripeAPIError: StripeModel { - public var type: StripeErrorType - public var charge: String? - public var code: StripeErrorCode? - public var declineCode: StripeDeclineCode? - public var docUrl: String? - public var message: String - public var param: String? - - public enum CodingKeys: String, CodingKey { - case type - case charge - case code - case declineCode = "decline_code" - case docUrl = "doc_url" - case message - case param - } -} - - -// https://stripe.com/docs/api#errors-type -public enum StripeErrorType: String, StripeModel { - case apiConnectionError = "api_connection_error" - case apiError = "api_error" - case authenticationError = "authentication_error" - case cardError = "card_error" - case idempotencyError = "idempotency_error" - case invalidRequestError = "invalid_request_error" - case rateLimitError = "rate_limit_error" - case validationError = "validation_error" -} - -// https://stripe.com/docs/api#errors-code -// https://stripe.com/docs/error-codes -public enum StripeErrorCode: String, StripeModel { - case accountAlreadyExists = "account_already_exists" - case accountCountryInvalidAddress = "account_country_invalid_address" - case accountInvalid = "account_invalid" - case accountNumberInvalid = "account_number_invalid" - case alipayUpgradeRequired = "alipay_upgrade_required" - case amountTooLarge = "amount_too_large" - case amountTooSmall = "amount_too_small" - case apiKeyExpired = "api_key_expired" - case balanceInsufficient = "balance_insufficient" - case bankAccountExists = "bank_account_exists" - case bankAccountUnusable = "bank_account_unsuable" - case bankAccountUnverified = "bank_account_unverified" - case bitcoinUpgradeRequired = "bitcoin_upgrade_required" - case cardDeclined = "card_declined" - case chargeAlreadyCaptured = "charge_already_captured" - case chargeAlreadyRefunded = "charge_already_refunded" - case chargeDisputed = "charge_disputed" - case chargeExpiredForCapture = "charge_expired_for_capture" - case countryUnsupported = "country_unsupported" - case couponExpired = "coupon_expired" - case customerMaxSubscriptions = "customer_max_subscriptions" - case emailInvalid = "email_invalid" - case expiredCard = "expired_card" - case incorrectAddress = "incorrect_address" - case incorrectCVC = "incorrect_cvc" - case incorrectNumber = "incorrect_number" - case incorrectZip = "incorrect_zip" - case instantPayoutUnsupported = "instant_payouts_unsupported" - case invalidCardType = "invalid_card_type" - case invalidChargeAmount = "invalid_charge_amount" - case invalidCVC = "invalid_cvc" - case invalidExpiryMonth = "invalid_expiry_month" - case invalidExpiryYear = "invalid_expiry_year" - case invalidNumber = "invalid_number" - case invalidSourceUsage = "invalid_source_usage" - case invoiceNoCustomerLineItems = "invoice_no_customer_line_items" - case invoiceNoSubscriptionLineItems = "invoice_no_subscription_line_items" - case invoiceUpcomingNone = "invoice_upcoming_none" - case livemodeMismatch = "livemode_mismatch" - case missing - case orderCreationFailed = "order_creation_failed" - case orderRequiredSettings = "order_required_settings" - case orderStatusInvalid = "order_status_invalid" - case orderUpstreamTimeout = "order_upstream_timeout" - case outOfInventory = "out_of_inventory" - case parameterInvalidEmpty = "parameter_invalid_empty" - case parameterInvalidInteger = "parameter_invalid_integer" - case parameterInvalidStringBlank = "parameter_invalid_string_blank" - case parameterInvalidStringEmpty = "parameter_invalid_string_empty" - case parameterMissing = "parameter_missing" - case parameterUnknown = "parameter_unknown" - case paymentMethodUnactivated = "payment_method_unactivated" - case payoutsNotAllowed = "payouts_not_allowed" - case platformApiKeyExpired = "platform_api_key_expired" - case postalCodeInvalid = "postal_code_invalid" - case processingError = "processing_error" - case productInactive = "product_inactive" - case rateLimit = "rate_limit" - case resourceAlreadyExists = "resource_already_exists" - case resourceMissing = "resource_missing" - case routingNumberInvalid = "routing_number_invalid" - case secretKeyRequired = "secret_key_required" - case sepaUnsupportedAccount = "sepa_unsupported_account" - case shippingCalculationFailed = "shipping_calculation_failed" - case skuInactive = "sku_inactive" - case stateUnsupported = "state_unsupported" - case taxIdInvalid = "tax_id_invalid" - case taxesCalculationFailed = "taxes_calculation_failed" - case testmodeChargesOnly = "testmode_charges_only" - case tlsVersionUnsupported = "tls_version_unsupported" - case tokenAlreadyUsed = "token_already_used" - case tokenInUse = "token_in_use" - case transfersNotAllowed = "transfers_not_allowed" - case upstreamOrderCreationFailed = "upstream_order_creation_failed" - case urlInvalid = "url_invalid" -} - -// https://stripe.com/docs/api#errors-decline-code -// https://stripe.com/docs/declines/codes -public enum StripeDeclineCode: String, StripeModel { - case approveWithId = "approve_with_id" - case callIssuer = "call_issuer" - case cardNotSupported = "card_not_supported" - case cardVelocityExceeded = "card_velocity_exceeded" - case currencyNotSupported = "currency_not_supported" - case doNotHonor = "do_not_honor" - case doNotTryAgain = "do_not_try_again" - case duplicateTransaction = "duplicate_transaction" - case expiredCard = "expired_card" - case fradulent - case genericDecline = "generic_decline" - case incorrectNumber = "incorrect_number" - case incorrectCVC = "incorrect_cvc" - case incorrectPin = "incorrect_pin" - case incorrectZip = "incorrect_zip" - case insufficientFunds = "insufficient_funds" - case invalidAccount = "invalid_account" - case invalidAmount = "invalid_amount" - case invalidCVC = "invalid_cvc" - case invalidExpiryYear = "invalid_expiry_year" - case invalidNumber = "invalid_number" - case invalidPin = "invalid_pin" - case issuerNotAvailable = "issuer_not_available" - case lostCard = "lost_card" - case newAccountInformationAvailable = "new_account_information_available" - case noActionTaken = "no_action_taken" - case notPermitted = "not_permitted" - case pickupCard = "pickup_card" - case pinTryExceeded = "pin_try_exceeded" - case processingError = "processing_error" - case reenterTransaction = "reenter_transaction" - case restrictedCard = "restricted_card" - case revocationOfAllAuthorizations = "revocation_of_all_authorizations" - case revocationOfAuthorization = "revocation_of_authorization" - case securityViolation = "security_violation" - case serviceNotAllowed = "service_not_allowed" - case stolenCard = "stolen_card" - case stopPaymentOrder = "stop_payment_order" - case testmodeDecline = "testmode_decline" - case testModeLiveCard = "test_mode_live_card" - case transactionNotAllowed = "transaction_not_allowed" - case tryAgainLater = "try_again_later" - case withdrawalCountLimitExceeded = "withdrawal_count_limit_exceeded" -} diff --git a/Sources/Stripe/Helpers/AccountRejectReason.swift b/Sources/Stripe/Helpers/AccountRejectReason.swift deleted file mode 100644 index 67fb9ac..0000000 --- a/Sources/Stripe/Helpers/AccountRejectReason.swift +++ /dev/null @@ -1,13 +0,0 @@ -// -// AccountRejectReason.swift -// Stripe -// -// Created by Andrew Edwards on 7/9/17. -// -// - -public enum AccountRejectReason: String, Codable { - case fraud - case termsOfService = "terms_of_service" - case other -} diff --git a/Sources/Stripe/Helpers/ActionType.swift b/Sources/Stripe/Helpers/ActionType.swift deleted file mode 100644 index 57ce536..0000000 --- a/Sources/Stripe/Helpers/ActionType.swift +++ /dev/null @@ -1,13 +0,0 @@ -// -// ActionType.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -public enum ActionType: String, Codable { - case applicationFee = "application_fee" - case stripeFee = "stripe_fee" - case tax -} diff --git a/Sources/Stripe/Helpers/CodeVerification.swift b/Sources/Stripe/Helpers/CodeVerification.swift deleted file mode 100644 index 21c9dd6..0000000 --- a/Sources/Stripe/Helpers/CodeVerification.swift +++ /dev/null @@ -1,16 +0,0 @@ -// -// CodeVerification.swift -// Stripe -// -// Created by Andrew Edwards on 12/4/17. -// - -public struct CodeVerification: StripeModel { - public var attemptsRemaining: Int? - public var status: StripeStatus? - - public enum CodingKeys: String, CodingKey { - case attemptsRemaining = "attempts_remaining" - case status - } -} diff --git a/Sources/Stripe/Helpers/InventoryType.swift b/Sources/Stripe/Helpers/InventoryType.swift deleted file mode 100644 index 28fdfba..0000000 --- a/Sources/Stripe/Helpers/InventoryType.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// InventoryType.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -public enum InventoryType: String, Codable { - case finite - case bucket - case infinite - case unknown -} - -public enum InventoryTypeValue: String, Codable { - case inStock = "in_stock" - case limited - case outOfStock = "out_of_stock" - case unknown -} diff --git a/Sources/Stripe/Helpers/StripeCurrency.swift b/Sources/Stripe/Helpers/StripeCurrency.swift deleted file mode 100644 index 8813a9d..0000000 --- a/Sources/Stripe/Helpers/StripeCurrency.swift +++ /dev/null @@ -1,111 +0,0 @@ -// -// Currency.swift -// Stripe -// -// Created by Anthony Castelli on 4/14/17. -// -// - -public enum StripeCurrency: String, Codable { - case usd - case aed - case afn - case all - case amd - case ang - case aoa - case ars - case aud - case awg - case azn - case bam - case bbd - case bdt - case bgn - case bif - case bmd - case bnd - case bob - case brl - case bsd - case bwp - case bzd - case cad - case cdf - case chf - case clp - case cny - case cop - case crc - case cve - case czk - case djf - case dkk - case dop - case dzd - case egp - case eur - case fjd - case gbp - case gel - case gip - case gmd - case gyd - case hkd - case hrk - case htg - case idr - case jpy - case nok - case sek - case nzd - case sgd - case lkr - case lrd - case lsl - case mad - case mdl - case mkd - case mmk - case mnt - case mop - case mro - case mvr - case mwk - case mxn - case myr - case mzn - case nad - case ngn - case npr - case pgk - case php - case pkr - case pln - case qar - case ron - case rsd - case rub - case sar - case sbd - case scr - case sll - case sos - case std - case szl - case thb - case tjs - case top - case ttd - case twd - case tzs - case uah - case ugx - case uzs - case wts - case xcd - case yer - case zar - case zmw - // TODO: - finish adding stripe currecies -} diff --git a/Sources/Stripe/Helpers/StripeDuration.swift b/Sources/Stripe/Helpers/StripeDuration.swift deleted file mode 100644 index 7251f98..0000000 --- a/Sources/Stripe/Helpers/StripeDuration.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// StripeDuration.swift -// Stripe -// -// Created by Andrew Edwards on 5/28/17. -// -// - -public enum StripeDuration: String, Codable { - case forever - case once - case repeating -} - -// https://stripe.com/docs/api/curl#account_object-payout_schedule-interval -public enum StripePayoutInterval: String, Codable { - case manual - case daily - case weekly - case monthly -} - -// https://stripe.com/docs/api/curl#account_object-payout_schedule-weekly_anchor -public enum StripeWeeklyAnchor: String, Codable { - case sunday - case monday - case tuesday - case wednesday - case thursday - case friday - case saturday -} diff --git a/Sources/Stripe/Helpers/StripePlanInterval.swift b/Sources/Stripe/Helpers/StripePlanInterval.swift deleted file mode 100644 index 276fb71..0000000 --- a/Sources/Stripe/Helpers/StripePlanInterval.swift +++ /dev/null @@ -1,16 +0,0 @@ -// -// StripeInterval.swift -// Stripe -// -// Created by Andrew Edwards on 5/29/17. -// -// - -import Foundation - -public enum StripePlanInterval: String, Codable { - case day - case week - case month - case year -} diff --git a/Sources/Stripe/Helpers/StripeStatus.swift b/Sources/Stripe/Helpers/StripeStatus.swift deleted file mode 100644 index bf93d11..0000000 --- a/Sources/Stripe/Helpers/StripeStatus.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// StripeStatus.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -import Foundation - -public enum StripeStatus: String, Codable { - case success - case succeeded - case failed - case pending - case canceled - case chargeable - case available -} - -// https://stripe.com/docs/api/curl#subscription_object-status -public enum StripeSubscriptionStatus: String, Codable { - case trialing - case active - case pastDue = "past_due" - case canceled - case unpaid -} - -// https://stripe.com/docs/api/invoices/object#invoice_object-status -public enum StripeInvoiceStatus: String, Codable { - case draft - case open - case paid - case uncollectible - case void -} - -public enum StripeConnectAccountCapabilitiesStatus: String, Codable { - case active - case inactive - case pending -} diff --git a/Sources/Stripe/Models/Balance/Balance.swift b/Sources/Stripe/Models/Balance/Balance.swift deleted file mode 100644 index dd119dd..0000000 --- a/Sources/Stripe/Models/Balance/Balance.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// Balance.swift -// Stripe -// -// Created by Anthony Castelli on 4/13/17. -// -// - -/** - Balance object - https://stripe.com/docs/api/curl#balance_object - */ - -public struct StripeBalance: StripeModel { - public var object: String - public var available: [StripeBalanceTransfer]? - public var connectReserved: [StripeBalanceTransfer]? - public var livemode: Bool? - public var pending: [StripeBalanceTransfer]? - - public enum CodingKeys: String, CodingKey { - case object - case available - case connectReserved = "connect_reserved" - case livemode - case pending - } -} diff --git a/Sources/Stripe/Models/Balance/BalanceHistoryList.swift b/Sources/Stripe/Models/Balance/BalanceHistoryList.swift deleted file mode 100644 index f4b2fb9..0000000 --- a/Sources/Stripe/Models/Balance/BalanceHistoryList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// BalanceHistoryList.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -/** - BalanceHistory list - https://stripe.com/docs/api#balance_history - */ - -public struct BalanceHistoryList: StripeModel { - public var object: String - public var hasMore: Bool? - public var totalCount: Int? - public var url: String? - public var data: [StripeBalanceTransactionItem]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Balance/BalanceTransactionItem.swift b/Sources/Stripe/Models/Balance/BalanceTransactionItem.swift deleted file mode 100644 index 1699dc2..0000000 --- a/Sources/Stripe/Models/Balance/BalanceTransactionItem.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// BalanceTransactionItem.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -import Foundation - -/** - BalanceTransaction object - https://stripe.com/docs/api/curl#balance_transaction_object - */ - -public struct StripeBalanceTransactionItem: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var availableOn: Date? - public var created: Date? - public var currency: StripeCurrency? - public var exchangeRate: Decimal? - public var description: String? - public var fee: Int? - public var feeDetails: [StripeFee]? - public var net: Int? - public var source: String? - public var status: StripeStatus? - public var type: BalanceTransactionType? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case availableOn = "available_on" - case created - case currency - case exchangeRate = "exchange_rate" - case description - case fee - case feeDetails = "fee_details" - case net - case source - case status - case type - } -} diff --git a/Sources/Stripe/Models/Balance/BalanceTransactionType.swift b/Sources/Stripe/Models/Balance/BalanceTransactionType.swift deleted file mode 100644 index bc20c1d..0000000 --- a/Sources/Stripe/Models/Balance/BalanceTransactionType.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// BalanceTransactionType.swift -// Stripe -// -// Created by Anthony Castelli on 4/16/17. -// -// - -import Foundation - -/** - BalanceTransactionType - https://stripe.com/docs/api/curl#balance_transaction_object-type - */ - -public enum BalanceTransactionType: String, Codable { - case adjustment - case applicationFee = "application_fee" - case applicationFeeRefund = "application_fee_refund" - case charge - case payment - case paymentFailureRefund = "payment_failure_refund" - case paymentRefund = "payment_refund" - case refund - case transfer - case transferRefund = "transfer_refund" - case payout - case payoutCancel = "payout_cancel" - case payoutFailure = "payout_failure" - case validation - case stripeFee = "stripe_fee" -} diff --git a/Sources/Stripe/Models/Balance/BalanceTransfer.swift b/Sources/Stripe/Models/Balance/BalanceTransfer.swift deleted file mode 100644 index 4ebfb7f..0000000 --- a/Sources/Stripe/Models/Balance/BalanceTransfer.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// BalanceTransfer.swift -// Stripe -// -// Created by Anthony Castelli on 4/14/17. -// -// - -/** - Balance transfer is the body object of available array. - https://stripe.com/docs/api/curl#balance_object - */ -// TODO: - Use BalanceTransfer SourceTypes enum -public struct StripeBalanceTransfer: StripeModel { - public var currency: StripeCurrency? - public var amount: Int? - public var sourceTypes: [String: Int]? - - public enum CodingKeys: String, CodingKey { - case currency - case amount - case sourceTypes = "source_types" - } -} diff --git a/Sources/Stripe/Models/Balance/Fee.swift b/Sources/Stripe/Models/Balance/Fee.swift deleted file mode 100644 index 8e236d9..0000000 --- a/Sources/Stripe/Models/Balance/Fee.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// Fee.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -import Vapor - -/** - Fee - https://stripe.com/docs/api/curl#balance_transaction_object-fee_details - */ - -public struct StripeFee: StripeModel { - public var amount: Int? - public var currency: StripeCurrency? - public var description: String? - public var type: ActionType? -} diff --git a/Sources/Stripe/Models/Balance/SourceBalanceType.swift b/Sources/Stripe/Models/Balance/SourceBalanceType.swift deleted file mode 100644 index 545284a..0000000 --- a/Sources/Stripe/Models/Balance/SourceBalanceType.swift +++ /dev/null @@ -1,12 +0,0 @@ -// -// SourceBalanceType.swift -// Stripe -// -// Created by Andrew Edwards on 2/11/18. -// - -public enum SourceBalanceType: String, Codable { - case card - case bankAccount = "bank_account" - case alipayAccount = "alipay_account" -} diff --git a/Sources/Stripe/Models/Charges/Charge.swift b/Sources/Stripe/Models/Charges/Charge.swift deleted file mode 100644 index fdbaeb2..0000000 --- a/Sources/Stripe/Models/Charges/Charge.swift +++ /dev/null @@ -1,103 +0,0 @@ -// -// Charge.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -import Foundation - -/** - Charge object - https://stripe.com/docs/api/curl#charge_object - */ - -public struct StripeCharge: StripeModel { - public var id: String - public var object: String - public var amount: Int - public var amountRefunded: Int? - public var application: String? - public var applicationFee: String? - public var applicationFeeAmount: Int? - public var balanceTransaction: String? - public var captured: Bool - public var created: Date? - public var currency: StripeCurrency - public var customer: String? - public var description: String? - public var destination: String? - public var dispute: String? - public var failureCode: String? - public var failureMessage: String? - public var fraudDetails: StripeFraudDetails? - public var invoice: String? - public var livemode: Bool? - public var metadata: [String: String] - public var onBehalfOf: String? - public var order: String? - public var outcome: StripeOutcome? - public var paid: Bool? - public var paymentIntent: String? - public var receiptEmail: String? - public var receiptNumber: String? - public var refunded: Bool? - public var refunds: RefundsList - public var review: String? - public var shipping: ShippingLabel? - public var source: StripeSource? - public var sourceTransfer: String? - public var statementDescriptor: String? - public var status: StripeStatus? - public var transfer: String? - public var transferData: StripeChargeTransferData? - public var transferGroup: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case amountRefunded = "amount_refunded" - case application - case applicationFee = "application_fee" - case applicationFeeAmount = "application_fee_amount" - case balanceTransaction = "balance_transaction" - case captured - case created - case currency - case customer - case description - case destination - case dispute - case failureCode = "failure_code" - case failureMessage = "failure_message" - case fraudDetails = "fraud_details" - case invoice - case livemode - case metadata - case onBehalfOf = "on_behalf_of" - case order - case outcome - case paid - case paymentIntent = "payment_intent" - case receiptEmail = "receipt_email" - case receiptNumber = "receipt_number" - case refunded - case refunds - case review - case shipping - case source - case sourceTransfer = "source_transfer" - case statementDescriptor = "statement_descriptor" - case status - case transfer - case transferData = "transfer_data" - case transferGroup = "transfer_group" - } -} - -public struct StripeChargeTransferData: StripeModel { - public var amount: Int? - public var destination: String? -} diff --git a/Sources/Stripe/Models/Charges/ChargeList.swift b/Sources/Stripe/Models/Charges/ChargeList.swift deleted file mode 100644 index 8a0dfc5..0000000 --- a/Sources/Stripe/Models/Charges/ChargeList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// ChargeList.swift -// Stripe -// -// Created by Anthony Castelli on 4/17/17. -// -// - -/** - Charges list - https://stripe.com/docs/api/curl#list_charges - */ - -public struct ChargesList: StripeModel { - public var object: String - public var hasMore: Bool? - public var totalCount: Int? - public var url: String? - public var data: [StripeCharge]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Charges/FruadDetails.swift b/Sources/Stripe/Models/Charges/FruadDetails.swift deleted file mode 100644 index 7efd599..0000000 --- a/Sources/Stripe/Models/Charges/FruadDetails.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// FruadDetails.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -/** - Fraud Details - https://stripe.com/docs/api/curl#charge_object-fraud_details - */ - -public enum FraudReport: String, Codable { - case safe - case fraudulent -} - -public protocol FraudDetails { - var userReport: FraudReport? { get } - var stripeReport: FraudReport? { get } -} - -public struct StripeFraudDetails: FraudDetails, StripeModel { - public var userReport: FraudReport? - public var stripeReport: FraudReport? - - public enum CodingKeys: String, CodingKey { - case userReport = "user_report" - case stripeReport = "stripe_report" - } -} diff --git a/Sources/Stripe/Models/Charges/Outcome.swift b/Sources/Stripe/Models/Charges/Outcome.swift deleted file mode 100644 index a2e9429..0000000 --- a/Sources/Stripe/Models/Charges/Outcome.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// Outcome.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -/** - Outcome - https://stripe.com/docs/api/curl#charge_object-outcome - */ - -public enum NetworkStatus: String, Codable { - case approvedByNetwork = "approved_by_network" - case declinedByNetwork = "declined_by_network" - case notSentToNetwork = "not_sent_to_network" - case reversedAfterApproval = "reversed_after_approval" -} - -public enum RiskLevel: String, Codable { - case normal - case elevated - case highest - case notAssessed = "not_assessed" - case unknown -} - -public enum OutcomeType: String, Codable { - case authorized - case manualReview = "manual_review" - case issuerDeclined = "issuer_declined" - case blocked - case invalid -} - -public struct StripeOutcome: StripeModel { - public var networkStatus: NetworkStatus? - public var reason: String? - public var riskLevel: RiskLevel? - public var rule: String? - public var sellerMessage: String? - public var type: OutcomeType? - - public enum CodingKeys: String, CodingKey { - case networkStatus = "network_status" - case reason - case riskLevel = "risk_level" - case rule - case sellerMessage = "seller_message" - case type - } -} diff --git a/Sources/Stripe/Models/Charges/Review.swift b/Sources/Stripe/Models/Charges/Review.swift deleted file mode 100644 index 7d8eddc..0000000 --- a/Sources/Stripe/Models/Charges/Review.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// Review.swift -// Stripe -// -// Created by Andrew Edwards on 2/11/18. -// - -import Foundation - -/** - Review object - https://stripe.com/docs/api/curl#review_object - */ - -public struct StripeReview: StripeModel { - public var id: String - public var object: String - public var charge: String - public var created: Date? - public var livemode: Bool? - public var open: Bool? - public var reason: ReviewReason? -} diff --git a/Sources/Stripe/Models/Charges/ReviewReason.swift b/Sources/Stripe/Models/Charges/ReviewReason.swift deleted file mode 100644 index 1c69548..0000000 --- a/Sources/Stripe/Models/Charges/ReviewReason.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// ReviewReason.swift -// Stripe -// -// Created by Andrew Edwards on 2/11/18. -// - -/** - ReviewReason - https://stripe.com/docs/api/curl#review_object-reason - */ - -public enum ReviewReason: String, Codable { - case rule - case manual - case approved - case refunded - case refundedAsFraud = "refunded_as_fraud" - case disputed -} diff --git a/Sources/Stripe/Models/Connect/Account.swift b/Sources/Stripe/Models/Connect/Account.swift deleted file mode 100644 index 1da4610..0000000 --- a/Sources/Stripe/Models/Connect/Account.swift +++ /dev/null @@ -1,224 +0,0 @@ -// -// Account.swift -// Stripe -// -// Created by Andrew Edwards on 7/8/17. -// -// - -import Foundation - -/** - Account object - https://stripe.com/docs/api#account_object - */ - -public struct StripeConnectAccount: StripeModel { - public var id: String - public var object: String - public var businessProfile: StripeConnectAccountBusinessProfile? - public var businessType: StripeConnectAccountBusinessType? - public var capabilities: StripeConnectAccountCapablities? - public var chargesEnabled: Bool? - public var company: StripeConnectAccountCompany? - public var country: String? - public var created: Date? - public var defaultCurrency: StripeCurrency? - public var detailsSubmitted: Bool? - public var email: String? - public var externalAccounts: StripeExternalAccountsList? - public var individual: StripePerson? - public var metadata: [String: String] - public var payoutsEnabled: Bool? - public var requirements: StripeConnectAccountRequirmenets? - public var settings: StripeConnectAccountSettings? - public var tosAcceptance: StripeTOSAcceptance? - public var type: StripeConnectAccountType? - - private enum CodingKeys: String, CodingKey { - case id - case object - case businessProfile = "business_profile" - case businessType = "business_type" - case capabilities - case chargesEnabled = "charges_enabled" - case company - case country - case created - case defaultCurrency = "default_currency" - case detailsSubmitted = "details_submitted" - case email - case externalAccounts = "external_accounts" - case individual - case metadata - case payoutsEnabled = "payouts_enabled" - case requirements - case settings - case tosAcceptance = "tos_acceptance" - case type - } -} - -public struct StripeConnectAccountList: StripeModel { - public var object: String - public var hasMore: Bool - public var url: String? - public var data: [StripeConnectAccount]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case url - case data - } -} - -public struct StripeConnectAccountBusinessProfile: StripeModel { - public var mcc: String? - public var name: String? - public var productDescription: String? - public var supportAddress: StripeAddress? - public var supportEmail: String? - public var supportPhone: String? - public var supportUrl: String? - public var url: String? - - private enum CodingKeys: String, CodingKey { - case mcc - case name - case productDescription = "product_description" - case supportAddress = "support_address" - case supportEmail = "support_email" - case supportPhone = "support_phone" - case supportUrl = "support_url" - case url - } -} - -public struct StripeConnectAccountCapablities: StripeModel { - public var cardPayments: StripeConnectAccountCapabilitiesStatus? - public var legacyPayments: StripeConnectAccountCapabilitiesStatus? - public var platformPayments: StripeConnectAccountCapabilitiesStatus? - - private enum CodingKeys: String, CodingKey { - case cardPayments = "card_payments" - case legacyPayments = "legacy_payments" - case platformPayments = "platform_payments" - } -} - -public struct StripeConnectAccountCompany: StripeModel { - public var address: StripeAddress? - public var directorsProvided: Bool? - public var name: String? - public var ownersProvided: Bool? - public var phone: String? - public var taxIdProvided: Bool? - public var taxIdRegistrar: String? - public var vatIdProvided: Bool? - - private enum CodingKeys: String, CodingKey { - case address - case directorsProvided = "directors_provided" - case name - case ownersProvided = "owners_provided" - case phone - case taxIdProvided = "tax_id_provided" - case taxIdRegistrar = "tax_id_registrar" - case vatIdProvided = "vat_id_provided" - } -} - -public struct StripeConnectAccountRequirmenets: StripeModel { - public var currentDeadline: Date? - public var currentlyDue: [String]? - public var disabledReason: String? - public var eventuallyDue: [String]? - public var pastDue: [String]? - - private enum CodingKeys: String, CodingKey { - case currentDeadline = "current_deadline" - case currentlyDue = "currently_due" - case disabledReason = "disabled_reason" - case eventuallyDue = "eventually_due" - case pastDue = "past_due" - } -} - -public struct StripeConnectAccountSettings: StripeModel { - public var branding: StripeConnectAccountSettingsBranding? - public var cardPayments: StripeConnectAccountSettingsCardPayments? - public var dashboard: StripeConnectAccountSettingsDashboard? - public var payments: StripeConnectAccountSettingsPayments? - public var payouts: StripeConnectAccountSettingsPayouts? - - private enum CodingKeys: String, CodingKey { - case branding - case cardPayments = "card_payments" - case dashboard - case payments - case payouts - } -} - -public struct StripeConnectAccountSettingsBranding: StripeModel { - public var icon: String? - public var logo: String? - public var primaryColor: String? - - private enum CodingKeys: String, CodingKey { - case icon - case logo - case primaryColor = "primary_color" - } -} - -public struct StripeConnectAccountSettingsCardPayments: StripeModel { - public var declineOn: StripeConnectAccountSettingsCardPaymentsDeclineOn? - public var statementDescriptorPrefix: String? - - private enum CodingKeys: String, CodingKey { - case declineOn = "decline_on" - case statementDescriptorPrefix = "statement_descriptor_prefix" - } -} - -public struct StripeConnectAccountSettingsCardPaymentsDeclineOn: StripeModel { - public var avsFailure: Bool? - public var cvcFailure: Bool? - - private enum CodingKeys: String, CodingKey { - case avsFailure = "avs_failure" - case cvcFailure = "cvc_failure" - } -} - -public struct StripeConnectAccountSettingsDashboard: StripeModel { - public var displayName: String? - public var timezone: String? - - private enum CodingKeys: String, CodingKey { - case displayName = "display_name" - case timezone - } -} - -public struct StripeConnectAccountSettingsPayments: StripeModel { - public var statementDescriptor: String? - - private enum CodingKeys: String, CodingKey { - case statementDescriptor = "statement_descriptor" - } -} - -public struct StripeConnectAccountSettingsPayouts: StripeModel { - public var debitNegativeBalances: Bool? - public var schedule: StripePayoutSchedule? - public var statementDescriptor: String? - - private enum CodingKeys: String, CodingKey { - case debitNegativeBalances = "debit_negative_balances" - case schedule - case statementDescriptor = "statement_descriptor" - } -} diff --git a/Sources/Stripe/Models/Connect/ApplicationFee.swift b/Sources/Stripe/Models/Connect/ApplicationFee.swift deleted file mode 100644 index b60cd65..0000000 --- a/Sources/Stripe/Models/Connect/ApplicationFee.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// ApplicationFee.swift -// Stripe -// -// Created by Andrew Edwards on 3/16/19. -// - -import Vapor -/// When you collect a transaction fee on top of a charge made for your user (using [Connect](https://stripe.com/docs/connect) ), an `Application Fee` object is created in your account. You can list, retrieve, and refund application fees. For details, see [Collecting application fees](https://stripe.com/docs/connect/direct-charges#collecting-fees). [Learn More →](https://stripe.com/docs/api/application_fees) -public struct StripeApplicationFee: StripeModel { - /// Unique identifier for the object. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// ID of the Stripe account this fee was taken from. - public var account: String? - /// Amount earned, in cents. - public var amount: Int? - /// Amount in cents refunded (can be less than the amount attribute on the fee if a partial refund was issued) - public var amountRefunded: Int? - /// ID of the Connect application that earned the fee. - public var application: String? - /// Balance transaction that describes the impact of this collected application fee on your account balance (not including refunds). - public var balanceTransaction: String? - /// ID of the charge that the application fee was taken from. - public var charge: String? - /// Time at which the object was created. Measured in seconds since the Unix epoch. - public var created: Date? - /// Three-letter ISO currency code, in lowercase. Must be a supported currency. - public var currency: StripeCurrency? - /// Has the value true if the object exists in live mode or the value false if the object exists in test mode. - public var livemode: Bool? - /// ID of the corresponding charge on the platform account, if this fee was the result of a charge using the destination parameter. - public var originatingTransaction: String? - /// Whether the fee has been fully refunded. If the fee is only partially refunded, this attribute will still be false. - public var refunded: Bool? - /// A list of refunds that have been applied to the fee. - public var refunds: StripeApplicationFeeRefundList? - - private enum CodingKeys: String, CodingKey { - case id - case object - case account - case amount - case amountRefunded = "amount_refunded" - case application - case balanceTransaction = "balance_transaction" - case charge - case created - case currency - case livemode - case originatingTransaction = "originating_transaction" - case refunded - case refunds - } -} - -public struct StripeApplicationFeeList: StripeModel { - public var object: String - public var hasMore: Bool - public var url: String? - public var data: [StripeApplicationFee]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift b/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift deleted file mode 100644 index f6a52d6..0000000 --- a/Sources/Stripe/Models/Connect/ApplicationFeeRefund.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// ApplicationFeeRefund.swift -// Stripe -// -// Created by Andrew Edwards on 3/17/19. -// - -import Vapor -/// `Application Fee Refund` objects allow you to refund an application fee that has previously been created but not yet refunded. Funds will be refunded to the Stripe account from which the fee was originally collected. -public struct StripeApplicationFeeRefund: StripeModel { - /// Unique identifier for the object. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// Amount, in cents. - public var amount: Int? - /// Balance transaction that describes the impact on your account balance. - public var balanceTransaction: String? - /// Time at which the object was created. Measured in seconds since the Unix epoch. - public var created: Date? - /// Three-letter ISO currency code, in lowercase. Must be a supported currency. - public var currency: StripeCurrency? - /// ID of the application fee that was refunded. - public var fee: String? - /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. - public var metadata: [String: String]? - - private enum CodingKeys: String, CodingKey { - case id - case object - case amount - case balanceTransaction = "balance_transaction" - case created - case currency - case fee - case metadata - } -} - -public struct StripeApplicationFeeRefundList: StripeModel { - public var object: String - public var hasMore: Bool - public var url: String? - public var data: [StripeApplicationFeeRefund]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Connect/ConnectLoginLink.swift b/Sources/Stripe/Models/Connect/ConnectLoginLink.swift deleted file mode 100644 index 13bac99..0000000 --- a/Sources/Stripe/Models/Connect/ConnectLoginLink.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// ConnectLoginLink.swift -// Stripe -// -// Created by Andrew Edwards on 7/9/17. -// -// - -import Foundation - -/** - Login link object - https://stripe.com/docs/api/curl#login_link_object - */ - -public struct StripeConnectLoginLink: StripeModel { - public var object: String - public var created: Date? - public var url: String? -} diff --git a/Sources/Stripe/Models/Connect/CountrySpec.swift b/Sources/Stripe/Models/Connect/CountrySpec.swift deleted file mode 100644 index 375b350..0000000 --- a/Sources/Stripe/Models/Connect/CountrySpec.swift +++ /dev/null @@ -1,66 +0,0 @@ -// -// CountrySpec.swift -// Stripe -// -// Created by Andrew Edwards on 3/23/19. -// - -import Vapor -/// Stripe needs to collect certain pieces of information about each account created. These requirements can differ depending on the account's country. The Country Specs API makes these rules available to your integration. -public struct StripeCountrySpec: StripeModel { - /// Unique identifier for the object. Represented as the ISO country code for this country. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// The default currency for this country. This applies to both payment methods and bank accounts. - public var defaultCurrency: StripeCurrency? - /// Currencies that can be accepted in the specific country (for transfers). - public var supportedBankAccountCurrencies: [String: [String]]? - /// Currencies that can be accepted in the specified country (for payments). - public var supportedPaymentCurrencies: [StripeCurrency]? - /// Payment methods available in the specified country. You may need to enable some payment methods (e.g., [ACH](https://stripe.com/docs/ach)) on your account before they appear in this list. The `stripe` payment method refers to [charging through your platform](https://stripe.com/docs/connect/destination-charges). - public var supportedPaymentMethods: [String]? - /// Countries that can accept transfers from the specified country. - public var supportedTransferCountries: [String]? - /// Lists the types of verification data needed to keep an account open. - public var verificationFields: StripeCountrySpecVerificationFields? - - private enum CodingKeys: String, CodingKey { - case id - case object - case defaultCurrency = "default_currency" - case supportedBankAccountCurrencies = "supported_bank_account_currencies" - case supportedPaymentCurrencies = "supported_payment_currencies" - case supportedPaymentMethods = "supported_payment_methods" - case supportedTransferCountries = "supported_transfer_countries" - case verificationFields = "verification_fields" - } -} - -public struct StripeCountrySpecList: StripeModel { - public var object: String - public var hasMore: Bool - public var url: String? - public var data: [StripeCountrySpec]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case url - case data - } -} - -public struct StripeCountrySpecVerificationFields: StripeModel { - /// Verification types for company account. - public var company: StripeCountrySpecVerificationFieldsAttributes? - /// Verification types for individual account. - public var individual: StripeCountrySpecVerificationFieldsAttributes? -} - -public struct StripeCountrySpecVerificationFieldsAttributes: StripeModel { - /// Additional fields which are only required for some users. - public var additional: [String]? - /// Fields which every account must eventually provide. - public var minimum: [String]? -} diff --git a/Sources/Stripe/Models/Connect/ExternalAccounts.swift b/Sources/Stripe/Models/Connect/ExternalAccounts.swift deleted file mode 100644 index 254c20e..0000000 --- a/Sources/Stripe/Models/Connect/ExternalAccounts.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// ExternalAccounts.swift -// Stripe -// -// Created by Andrew Edwards on 7/8/17. -// -// - -/// External accounts list. [See here](https://stripe.com/docs/api/accounts/object#account_object-external_accounts) -public struct StripeExternalAccountsList: StripeModel { - /// String representing the object’s type. Objects of the same type share the same value. Always has the value list. - public var object: String - /** - Needs to be a string because the result can be an array of 2 possible types `StripeCard` and/or `StripeBankAccount`. - We'll actually decode the array of accounts seperately based on type and filtered based on object. See the initializer. - The `data` key is still needed in the `CodingKeys` and for decoding that property from the Stripe API, so we still have to declare it even though the type is unused. - */ - private var data: String? - /// True if this list has another page of items after this one that can be fetched. - public var hasMore: Bool? - /// The URL where this list can be accessed. - public var url: String? - /// An array of `StripeCard`s associated with the account. - public var cardAccounts: [StripeCard]? - /// /// An array of `StripeBankAccount`s associated with the account. - public var bankAccounts: [StripeBankAccount]? - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - object = try container.decode(String.self, forKey: .object) - hasMore = try container.decode(Bool.self, forKey: .hasMore) - url = try container.decodeIfPresent(String.self, forKey: .url) - - cardAccounts = try container.decodeIfPresent([StripeCard].self, forKey: .data)?.filter{ $0.object == "card" } - bankAccounts = try container.decodeIfPresent([StripeBankAccount].self, forKey: .data)?.filter{ $0.object == "bank_account" } - } - - private enum CodingKeys: String, CodingKey { - case object - case data - case hasMore = "has_more" - case url - case cardAccounts - case bankAccounts - } -} diff --git a/Sources/Stripe/Models/Connect/PayoutSchedule.swift b/Sources/Stripe/Models/Connect/PayoutSchedule.swift deleted file mode 100644 index 8a54042..0000000 --- a/Sources/Stripe/Models/Connect/PayoutSchedule.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// PayoutSchedule.swift -// Stripe -// -// Created by Andrew Edwards on 7/8/17. -// -// - -/** - Payout Schedule object - https://stripe.com/docs/api/curl#account_object-payout_schedule - */ - -public struct StripePayoutSchedule: StripeModel { - public var delayDays: Int? - public var interval: StripePayoutInterval? - public var monthlyAnchor: Int? - public var weeklyAnchor: StripeWeeklyAnchor? - - public enum CodingKeys: String, CodingKey { - case delayDays = "delay_days" - case interval - case monthlyAnchor = "monthly_anchor" - case weeklyAnchor = "weekly_anchor" - } -} diff --git a/Sources/Stripe/Models/Connect/Person.swift b/Sources/Stripe/Models/Connect/Person.swift deleted file mode 100644 index 682af2d..0000000 --- a/Sources/Stripe/Models/Connect/Person.swift +++ /dev/null @@ -1,166 +0,0 @@ -// -// Person.swift -// Stripe -// -// Created by Andrew Edwards on 2/24/19. -// - -import Foundation - -// https://stripe.com/docs/api/persons/object?&lang=curl -public struct StripePerson: StripeModel { - public var id: String - public var object: String - public var account: String? - public var address: StripeAddress? - public var created: Date? - public var dob: StripePersonDOB? - public var email: String? - public var firstName: String? - public var gender: StripePersonGender? - public var idNumberProvided: Bool? - public var lastName: String? - public var maidenName: String? - public var metadata: [String: String] - public var phone: String? - public var relationship: StripePersonRelationship? - public var requirements: StripePersonRequirements? - public var ssnLast4Provided: Bool? - public var verification: StripePersonVerification? - - private enum CodingKeys: String, CodingKey { - case id - case object - case account - case address - case created - case dob - case email - case firstName = "first_name" - case gender - case idNumberProvided = "id_number_provided" - case lastName = "last_name" - case maidenName = "maiden_name" - case metadata - case phone - case relationship - case requirements - case ssnLast4Provided = "ssn_last_4_provided" - case verification - } -} - -public struct StripePersonDOB: StripeModel { - public var day: Int? - public var month: Int? - public var year: Int? -} - -public enum StripePersonGender: String, StripeModel { - case male - case female -} - -public struct StripePersonRelationship: StripeModel { - public var accountOpener: Bool? - public var director: Bool? - public var owner: Bool? - public var percentOwnership: Decimal? - public var title: String? - - private enum CodingKeys: String, CodingKey { - case accountOpener = "account_opener" - case director - case owner - case percentOwnership = "percent_ownership" - case title - } -} - -public struct StripePersonRequirements: StripeModel { - public var currentlyDue: [String]? - public var eventuallyDue: [String]? - public var pastDue: [String]? - - private enum CodingKeys: String, CodingKey { - case currentlyDue = "currently_due" - case eventuallyDue = "eventually_due" - case pastDue = "past_due" - } -} - -public struct StripePersonVerification: StripeModel { - public var details: String? - public var detailsCode: StripePersonVerificationDetailsCode? - public var document: StripePersonVerificationDocument? - public var status: StripePersonVerificationStatus? - - private enum CodingKeys: String, CodingKey { - case details - case detailsCode = "details_code" - case document - case status - } -} - -public enum StripePersonVerificationDetailsCode: String, StripeModel { - case scanNameMismatch = "scan_name_mismatch" - case failedKeyedIdentity = "failed_keyed_identity" - case failedOther = "failed_other" -} - - -public struct StripePersonVerificationDocument: StripeModel { - public var back: String? - public var details: String? - public var detailsCode: StripePersonVerificationDocumentDetailsCode? - public var front: String? - - private enum CodingKeys: String, CodingKey { - case back - case details - case detailsCode = "details_code" - case front - } -} - -public enum StripePersonVerificationDocumentDetailsCode: String, StripeModel { - case documentCorrupt = "document_corrupt" - case documentFailedCopy = "document_failed_copy" - case documentNotReadable = "document_not_readable" - case documentFailedGreyscale = "document_failed_greyscale" - case documentNotUploaded = "document_not_uploaded" - case documentIdTypeNotSupported = "document_id_type_not_supported" - case documentIdCountryNotSupported = "document_id_country_not_supported" - case documentFailedOther = "document_failed_other" - case documentFraudulent = "document_fraudulent" - case documentInvalid = "document_invalid" - case documentManipulated = "document_manipulated" - case documentMissingBack = "document_missing_back" - case documentMissingFront = "document_missing_front" - case documentPhotoMismatch = "document_photo_mismatch" - case documentTooLarge = "document_too_large" - case documentFailedTestMode = "document_failed_test_mode" -} - -public enum StripePersonVerificationStatus: String, StripeModel { - case unverified - case pending - case verified -} - -public struct PersonsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripePerson]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Connect/StripeConnectedAccountType.swift b/Sources/Stripe/Models/Connect/StripeConnectedAccountType.swift deleted file mode 100644 index 994a185..0000000 --- a/Sources/Stripe/Models/Connect/StripeConnectedAccountType.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// ConnectedAccountType.swift -// Stripe -// -// Created by Andrew Edwards on 7/9/17. -// -// - -// https://stripe.com/docs/api/curl#account_object-type -public enum StripeConnectAccountType: String, Codable { - case custom - case standard -} - -public enum StripeConnectAccountBusinessType: String, Codable { - case individual - case company -} diff --git a/Sources/Stripe/Models/Connect/TOSAcceptance.swift b/Sources/Stripe/Models/Connect/TOSAcceptance.swift deleted file mode 100644 index b11a490..0000000 --- a/Sources/Stripe/Models/Connect/TOSAcceptance.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// TOSAcceptance.swift -// Stripe -// -// Created by Andrew Edwards on 7/8/17. -// -// - -import Foundation - -/** - Terms of acceptance object - https://stripe.com/docs/api/curl#account_object-tos_acceptance - */ - -public struct StripeTOSAcceptance: StripeModel { - public var date: Date? - public var ip: String? - public var userAgent: String? - - public enum CodingKeys: String, CodingKey { - case date - case ip - case userAgent = "user_agent" - } -} diff --git a/Sources/Stripe/Models/Connect/TopUp.swift b/Sources/Stripe/Models/Connect/TopUp.swift deleted file mode 100644 index 1a07e27..0000000 --- a/Sources/Stripe/Models/Connect/TopUp.swift +++ /dev/null @@ -1,84 +0,0 @@ -// -// TopUp.swift -// Stripe -// -// Created by Andrew Edwards on 3/24/19. -// - -import Vapor -/// The top-up object [see here](https://stripe.com/docs/api/topups/object) -public struct StripeTopUp: StripeModel { - /// Unique identifier for the object. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// Amount transferred. - public var amount: Int? - /// ID of the balance transaction that describes the impact of this top-up on your account balance. May not be specified depending on status of top-up. - public var balanceTransaction: String? - /// Time at which the object was created. Measured in seconds since the Unix epoch. - public var created: Date? - /// Three-letter ISO currency code, in lowercase. Must be a supported currency. - public var currency: StripeCurrency? - /// An arbitrary string attached to the object. Often useful for displaying to users. - public var description: String? - /// Date the funds are expected to arrive in your Stripe account for payouts. This factors in delays like weekends or bank holidays. May not be specified depending on status of top-up. - public var expectedAvailabilityDate: Date? - /// Error code explaining reason for top-up failure if available (see [the errors section](https://stripe.com/docs/api#errors) for a list of codes). - public var failureCode: String? - /// Message to user further explaining reason for top-up failure if available. - public var failureMessage: String? - /// Has the value true if the object exists in live mode or the value false if the object exists in test mode. - public var livemode: Bool? - /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. - public var metadata: [String: String]? - /// For most Stripe users, the source of every top-up is a bank account. This hash is then the [source object](https://stripe.com/docs/api/topups/object#source_object) describing that bank account. - public var source: StripeSource? - /// Extra information about a top-up. This will appear on your source’s bank statement. It must contain at least one letter. - public var statementDescriptor: String? - /// The status of the top-up is either `canceled`, `failed`, `pending`, `reversed`, or `succeeded`. - public var status: StripeTopUpStatus? - /// A string that identifies this top-up as part of a group. - public var transferGroup: String? - - private enum CodingKeys: String, CodingKey { - case id - case object - case amount - case balanceTransaction = "balance_transaction" - case created - case currency - case description - case expectedAvailabilityDate = "expected_availability_date" - case failureCode = "failure_code" - case failureMessage = "failure_message" - case livemode - case metadata - case source - case statementDescriptor = "statement_descriptor" - case status - case transferGroup = "transfer_group" - } -} - -public enum StripeTopUpStatus: String, StripeModel { - case canceled - case failed - case pending - case reversed - case succeeded -} - -public struct StripeTopUpList: StripeModel { - public var object: String - public var hasMore: Bool - public var url: String? - public var data: [StripeTopUp]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Connect/Transfer.swift b/Sources/Stripe/Models/Connect/Transfer.swift deleted file mode 100644 index 84a7691..0000000 --- a/Sources/Stripe/Models/Connect/Transfer.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// Transfer.swift -// Stripe -// -// Created by Andrew Edwards on 4/2/18. -// - -import Foundation - -/** - Transfer object - https://stripe.com/docs/api/curl#transfer_object - */ - -public struct StripeTransfer: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var amountReversed: Int? - public var balanceTransaction: String? - public var created: Date? - public var currency: StripeCurrency? - public var description: String? - public var destination: String? - public var destinationPayment: String? - public var livemode: Bool? - public var metadata: [String: String] - public var reversals: TransferReversalList? - public var reversed: Bool? - public var sourceTransaction: String? - public var sourceType: String? - public var transferGroup: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case amountReversed = "amount_reversed" - case balanceTransaction = "balance_transaction" - case created - case currency - case description - case destination - case destinationPayment = "destination_payment" - case livemode - case metadata - case reversals - case reversed - case sourceTransaction = "source_transaction" - case sourceType = "source_type" - case transferGroup = "transfer_group" - } -} diff --git a/Sources/Stripe/Models/Connect/TransferList.swift b/Sources/Stripe/Models/Connect/TransferList.swift deleted file mode 100644 index a6b84a9..0000000 --- a/Sources/Stripe/Models/Connect/TransferList.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// TransferList.swift -// Stripe -// -// Created by Andrew Edwards on 4/3/18. -// - -import Foundation - -/** - Transfers list - https://stripe.com/docs/api/curl#list_transfers - */ - -public struct TransferList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeTransfer]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Connect/TransferReversal.swift b/Sources/Stripe/Models/Connect/TransferReversal.swift deleted file mode 100644 index 05b615e..0000000 --- a/Sources/Stripe/Models/Connect/TransferReversal.swift +++ /dev/null @@ -1,35 +0,0 @@ -// -// TransferReversal.swift -// Stripe -// -// Created by Andrew Edwards on 4/2/18. -// - -import Foundation - -/** - Transfer object - https://stripe.com/docs/api/curl#transfer_reversal_object - */ - -public struct StripeTransferReversal: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var balanceTransaction: String? - public var created: Date? - public var currency: StripeCurrency? - public var metadata: [String: String] - public var transfer: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case balanceTransaction = "balance_transaction" - case created - case currency - case metadata - case transfer - } -} diff --git a/Sources/Stripe/Models/Connect/TransferReversalList.swift b/Sources/Stripe/Models/Connect/TransferReversalList.swift deleted file mode 100644 index 21a23a4..0000000 --- a/Sources/Stripe/Models/Connect/TransferReversalList.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// TransferReversalList.swift -// Stripe -// -// Created by Andrew Edwards on 4/3/18. -// - -/** - Connected Account list - https://stripe.com/docs/api/curl#transfer_object-reversals - */ - -public struct TransferReversalList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeTransferReversal]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Coupons/Coupon.swift b/Sources/Stripe/Models/Coupons/Coupon.swift deleted file mode 100644 index 6c3469b..0000000 --- a/Sources/Stripe/Models/Coupons/Coupon.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// Coupon.swift -// Stripe -// -// Created by Andrew Edwards on 5/28/17. -// -// - -import Foundation - -/** - Coupon Model - https://stripe.com/docs/api/curl#coupon_object - */ - -public struct StripeCoupon: StripeModel { - public var id: String - public var object: String - public var amountOff: Int? - public var created: Date? - public var currency: StripeCurrency? - public var duration: StripeDuration? - public var durationInMonths: Int? - public var livemode: Bool? - public var maxRedemptions: Int? - public var metadata: [String: String] - public var percentOff: Int? - public var redeemBy: Date? - public var timesRedeemed: Int? - public var valid: Bool? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amountOff = "amount_off" - case created - case currency - case duration - case durationInMonths = "duration_in_months" - case livemode - case maxRedemptions = "max_redemptions" - case metadata - case percentOff = "percent_off" - case redeemBy = "redeem_by" - case timesRedeemed = "times_redeemed" - case valid - } -} diff --git a/Sources/Stripe/Models/Coupons/CouponList.swift b/Sources/Stripe/Models/Coupons/CouponList.swift deleted file mode 100644 index 1ea3bba..0000000 --- a/Sources/Stripe/Models/Coupons/CouponList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// CouponList.swift -// Stripe -// -// Created by Andrew Edwards on 5/28/17. -// -// - -/** - Coupons List - https://stripe.com/docs/api#list_coupons - */ - -public struct CouponsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeCoupon]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Coupons/Discount.swift b/Sources/Stripe/Models/Coupons/Discount.swift deleted file mode 100644 index c64bee3..0000000 --- a/Sources/Stripe/Models/Coupons/Discount.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// Discount.swift -// Stripe -// -// Created by Andrew Edwards on 6/7/17. -// -// - -import Foundation -import Vapor - -/** - Discount Model - https://stripe.com/docs/api/curl#discount_object - */ - -public struct StripeDiscount: StripeModel { - public var object: String - public var coupon: StripeCoupon? - public var customer: String? - public var end: Date? - public var start: Date - public var subscription: String? -} diff --git a/Sources/Stripe/Models/Customer/Customer.swift b/Sources/Stripe/Models/Customer/Customer.swift deleted file mode 100644 index b5ab90b..0000000 --- a/Sources/Stripe/Models/Customer/Customer.swift +++ /dev/null @@ -1,93 +0,0 @@ -// -// Customer.swift -// Stripe -// -// Created by Anthony Castelli on 4/19/17. -// -// - -import Foundation - -/** - Customer Model - https://stripe.com/docs/api/curl#customer_object - */ - -public struct StripeCustomer: StripeModel { - public var id: String - public var object: String - public var accountBalance: Int? - public var created: Date? - public var currency: StripeCurrency? - public var defaultSource: String? - public var delinquent: Bool? - public var description: String? - public var discount: StripeDiscount? - public var email: String? - public var invoicePrefix: String? - public var invoiceSettings: StripeInvoiceSettings? - public var livemode: Bool? - public var metadata: [String: String] - public var shipping: ShippingLabel? - public var sources: StripeSourcesList? - public var subscriptions: StripeSubscriptionsList? - public var taxInfo: StripeCustomerTaxInfo? - public var taxInfoVerification: StripeCustomerTaxInfo? - - public enum CodingKeys: String, CodingKey { - case id - case object - case accountBalance = "account_balance" - case created - case currency - case defaultSource = "default_source" - case delinquent - case description - case discount - case email - case invoicePrefix = "invoice_prefix" - case invoiceSettings = "invoice_settings" - case livemode - case metadata - case shipping - case sources - case subscriptions - case taxInfo = "tax_info" - case taxInfoVerification = "tax_info_verification" - } -} - -public struct StripeCustomerTaxInfo: StripeModel { - public var taxId: String? - public var type: String? - - private enum CodingKeys: String, CodingKey { - case taxId = "tax_id" - case type - } -} - -public struct StripeCustomerTaxInfoVerification: StripeModel { - public var status: String? - public var verifiedName: String? - - private enum CodingKeys: String, CodingKey { - case status - case verifiedName = "verified_name" - } -} - -public struct StripeInvoiceSettings: StripeModel { - public var footer: String? - public var customFields: [StripeInvoiceCustomFields]? - - private enum CodingKeys: String, CodingKey { - case footer - case customFields = "custom_fields" - } -} - -public struct StripeInvoiceCustomFields: StripeModel { - public var name: String? - public var value: String? -} diff --git a/Sources/Stripe/Models/Customer/CustomerList.swift b/Sources/Stripe/Models/Customer/CustomerList.swift deleted file mode 100644 index 54fe8c2..0000000 --- a/Sources/Stripe/Models/Customer/CustomerList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// CustomerList.swift -// Stripe -// -// Created by Anthony Castelli on 4/20/17. -// -// - -/** - Customers List - https://stripe.com/docs/api/curl#list_customers - */ - -public struct StripeCustomersList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeCustomer]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Dispute/Dispute.swift b/Sources/Stripe/Models/Dispute/Dispute.swift deleted file mode 100644 index 903d748..0000000 --- a/Sources/Stripe/Models/Dispute/Dispute.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// Dispute.swift -// Stripe -// -// Created by Andrew Edwards on 7/11/17. -// -// - -import Foundation - -/** - Dispute object - https://stripe.com/docs/api#dispute_object - */ -public struct StripeDispute: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var balanceTransactions: [StripeBalanceTransactionItem]? - public var charge: String? - public var created: Date? - public var currency: StripeCurrency? - public var evidence: StripeDisputeEvidence? - public var evidenceDetails: StripeDisputeEvidenceDetails? - public var isChargeRefundable: Bool? - public var livemode: Bool? - public var metadata: [String: String] - public var reason: DisputeReason? - public var status: DisputeStatus? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case balanceTransactions = "balance_transactions" - case charge - case created - case currency - case evidence - case evidenceDetails = "evidence_details" - case isChargeRefundable = "is_charge_refundable" - case livemode - case metadata - case reason - case status - } -} diff --git a/Sources/Stripe/Models/Dispute/DisputeEvidence.swift b/Sources/Stripe/Models/Dispute/DisputeEvidence.swift deleted file mode 100644 index 283b3e8..0000000 --- a/Sources/Stripe/Models/Dispute/DisputeEvidence.swift +++ /dev/null @@ -1,71 +0,0 @@ -// -// DisputeEvidence.swift -// Stripe -// -// Created by Andrew Edwards on 12/7/17. -// - -/** - DisputeEvidence object - https://stripe.com/docs/api#dispute_evidence_object - */ - -public struct StripeDisputeEvidence: StripeModel { - public var accessActivityLog: String? - public var billingAddress: String? - public var cancellationPolicy: String? - public var cancellationPolicyDisclosure: String? - public var cancellationRebuttal: String? - public var customerCommunication: String? - public var customerEmailAddress: String? - public var customerName: String? - public var customerPurchaseIp: String? - public var customerSignature: String? - public var duplicateChargeDocumentation: String? - public var duplicateChargeExplanation: String? - public var duplicateChargeId: String? - public var productDescription: String? - public var receipt: String? - public var refundPolicy: String? - public var refundPolicyDisclosure: String? - public var refundRefusalExplanation: String? - public var serviceDate: String? - public var serviceDocumentation: String? - public var shippingAddress: String? - public var shippingCarrier: String? - public var shippingDate: String? - public var shippingDocumentation: String? - public var shippingTrackingNumber: String? - public var uncategorizedFile: String? - public var uncategorizedText: String? - - public enum CodingKeys: String, CodingKey { - case accessActivityLog = "access_activity_log" - case billingAddress = "billing_address" - case cancellationPolicy = "cancellation_policy" - case cancellationPolicyDisclosure = "cancellation_policy_disclosure" - case cancellationRebuttal = "cancellation_rebuttal" - case customerCommunication = "customer_communication" - case customerEmailAddress = "customer_email_address" - case customerName = "customer_name" - case customerPurchaseIp = "customer_purchase_ip" - case customerSignature = "customer_signature" - case duplicateChargeDocumentation = "duplicate_charge_documentation" - case duplicateChargeExplanation = "duplicate_charge_explanation" - case duplicateChargeId = "duplicate_charge_id" - case productDescription = "product_description" - case receipt - case refundPolicy = "refund_policy" - case refundPolicyDisclosure = "refund_policy_disclosure" - case refundRefusalExplanation = "refund_refusal_explanation" - case serviceDate = "service_date" - case serviceDocumentation = "service_documentation" - case shippingAddress = "shipping_address" - case shippingCarrier = "shipping_carrier" - case shippingDate = "shipping_date" - case shippingDocumentation = "shipping_documentation" - case shippingTrackingNumber = "shipping_tracking_number" - case uncategorizedFile = "uncategorized_file" - case uncategorizedText = "uncategorized_text" - } -} diff --git a/Sources/Stripe/Models/Dispute/DisputeEvidenceDetails.swift b/Sources/Stripe/Models/Dispute/DisputeEvidenceDetails.swift deleted file mode 100644 index f121edb..0000000 --- a/Sources/Stripe/Models/Dispute/DisputeEvidenceDetails.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// DisputeEvidenceDetails.swift -// Stripe -// -// Created by Andrew Edwards on 12/7/17. -// - -import Foundation - -/** - DisputeEvidenceDetails object - https://stripe.com/docs/api#dispute_object-evidence_details - */ - -public struct StripeDisputeEvidenceDetails: StripeModel { - public var dueBy: Date? - public var hasEvidence: Bool? - public var pastDue: Bool? - public var submissionCount: Int? - - public enum CodingKeys: String, CodingKey { - case dueBy = "due_by" - case hasEvidence = "has_evidence" - case pastDue = "past_due" - case submissionCount = "submission_count" - } -} diff --git a/Sources/Stripe/Models/Dispute/DisputeList.swift b/Sources/Stripe/Models/Dispute/DisputeList.swift deleted file mode 100644 index 1f88f50..0000000 --- a/Sources/Stripe/Models/Dispute/DisputeList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// DisputeList.swift -// Stripe -// -// Created by Andrew Edwards on 7/12/17. -// -// - -/** - Disputes List - https://stripe.com/docs/api#list_disputes - */ - -public struct DisputesList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeDispute]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Dispute/DisputeReason.swift b/Sources/Stripe/Models/Dispute/DisputeReason.swift deleted file mode 100644 index f07f4e3..0000000 --- a/Sources/Stripe/Models/Dispute/DisputeReason.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// DisputeReason.swift -// Stripe -// -// Created by Andrew Edwards on 7/11/17. -// -// - -// https://stripe.com/docs/api#dispute_object-reason -public enum DisputeReason: String, Codable { - case duplicate - case fraudulent - case subscriptionCanceled = "subscription_canceled" - case productUnacceptable = "product_unacceptable" - case productNotReceived = "product_not_received" - case unrecognized - case creditNotProcessed = "credit_not_processed" - case general - case incorrectAccountDetails = "incorrect_account_details" - case insufficientFunds = "insufficient_funds" - case bankCannotProcess = "bank_cannot_process" - case debitNotAuthorized = "debit_not_authorized" - case customerInitiated = "customer_initiated" -} - -// https://stripe.com/docs/api#dispute_object-status -public enum DisputeStatus: String, Codable { - case warningNeedsResponse = "warning_needs_response" - case warningUnderReview = "warning_under_review" - case warningClosed = "warning_closed" - case needsResponse = "needs_response" - case underReview = "under_review" - case chargeRefunded = "charge_refunded" - case won - case lost -} diff --git a/Sources/Stripe/Models/EphemeralKey/EphemeralKey.swift b/Sources/Stripe/Models/EphemeralKey/EphemeralKey.swift deleted file mode 100644 index 9bb3e18..0000000 --- a/Sources/Stripe/Models/EphemeralKey/EphemeralKey.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// EphemeralKey.swift -// Stripe -// -// Created by Andrew Edwards on 10/17/17. -// - -import Foundation - -public struct StripeEphemeralKey: StripeModel { - public var id: String - public var object: String - public var associatedObjects: [[String : String]]? - public var created: Date? - public var expires: Date? - public var livemode: Bool? - public var secret: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case associatedObjects = "associated_objects" - case created - case expires - case livemode - case secret - } -} diff --git a/Sources/Stripe/Models/Files/FileLink.swift b/Sources/Stripe/Models/Files/FileLink.swift deleted file mode 100644 index 5b92ba9..0000000 --- a/Sources/Stripe/Models/Files/FileLink.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// FileLink.swift -// Stripe -// -// Created by Andrew Edwards on 9/14/18. -// - -import Vapor - -/// To share the contents of a File object with non-Stripe users, you can create a FileLink. FileLinks contain a URL that can be used to retrieve the contents of the file without authentication. -public struct StripeFileLink: StripeModel { - /// Unique identifier for the object. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// Time at which the object was created. Measured in seconds since the Unix epoch. - public var created: Date? - /// Whether this link is already expired. - public var expired: Bool? - /// Time at which the link expires. - public var expiresAt: Date? - /// The file object this link points to. - public var file: String? - /// Has the value true if the object exists in live mode or the value false if the object exists in test mode. - public var livemode: Bool? - /// Set of key-value pairs that you can attach to an object. - public var metadata: [String: String] - /// The publicly accessible URL to download the file. - public var url: String? - - private enum CodingKeys: String, CodingKey { - case id - case object - case created - case expired - case expiresAt = "expires_at" - case file - case livemode - case metadata - case url - } -} diff --git a/Sources/Stripe/Models/Files/FileLinkList.swift b/Sources/Stripe/Models/Files/FileLinkList.swift deleted file mode 100644 index 4a0886a..0000000 --- a/Sources/Stripe/Models/Files/FileLinkList.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// FileLinkList.swift -// Stripe -// -// Created by Andrew Edwards on 9/15/18. -// - -public struct FileLinkList: StripeModel { - public var object: String - public var hasMore: Bool? - public var totalCount: Int? - public var url: String? - public var data: [StripeFileLink]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Files/FileUpload.swift b/Sources/Stripe/Models/Files/FileUpload.swift deleted file mode 100644 index 0c37598..0000000 --- a/Sources/Stripe/Models/Files/FileUpload.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// FileUpload.swift -// Stripe -// -// Created by Andrew Edwards on 9/15/18. -// - -import Vapor - -/// There are various times when you’ll want to upload files to Stripe (for example, when uploading dispute evidence). This can be done by creating a File Upload object. When you upload a file, the API responds with a file upload token and other information about the upload. The token can then be used to retrieve a File Upload object. -public struct StripeFileUpload: StripeModel { - /// Unique identifier for the object. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// Time at which the object was created. Measured in seconds since the Unix epoch. - public var created: Date? - /// A filename for the file, suitable for saving to a filesystem. - public var filename: String? - /// A list of file links. - public var links: FileLinkList? - /// The purpose of the uploaded file. - public var purpose: FilePurpose? - /// The size in bytes of the file upload object. - public var size: Int? - /// The type of the file returned. - public var type: FileType? - /// A read-only URL where the uploaded file can be accessed. Will be nil if the purpose of the uploaded file is identity_document. Also nil if retrieved with the publishable API key. - public var url: String? -} - -public enum FilePurpose: String, Content { - case businessLogo = "business_logo" - case customerSignature = "customer_signature" - case disputeEvidence = "dispute_evidence" - case identityDocument = "identity_document" - case pciDocument = "pci_document" - case taxDocumentUserUpload = "tax_document_user_upload" -} - -public enum FileType: String, Content { - case csv - case docx - case gif - case jpg - case pdf - case png - case xls - case xlsx -} diff --git a/Sources/Stripe/Models/Files/FileUploadList.swift b/Sources/Stripe/Models/Files/FileUploadList.swift deleted file mode 100644 index 7f2782d..0000000 --- a/Sources/Stripe/Models/Files/FileUploadList.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// FileUploadList.swift -// Stripe -// -// Created by Andrew Edwards on 9/15/18. -// - -public struct FileUploadList: StripeModel { - public var object: String - public var hasMore: Bool? - public var totalCount: Int? - public var url: String? - public var data: [StripeFileUpload]? - - private enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Invoices/BillingReason.swift b/Sources/Stripe/Models/Invoices/BillingReason.swift deleted file mode 100644 index 5568470..0000000 --- a/Sources/Stripe/Models/Invoices/BillingReason.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// BillingReason.swift -// Stripe -// -// Created by Nicolas Bachschmidt on 2018-11-23. -// - -import Foundation - -// https://stripe.com/docs/api/invoices/object?lang=curl#invoice_object-billing_reason -public enum StripeBillingReason: String, Codable { - case subscriptionCreate = "subscription_create" - case subscriptionUpdate = "subscription_update" - case subscriptionCycle = "subscription_cycle" - case subscription = "subscription" - case manual - case upcoming -} diff --git a/Sources/Stripe/Models/Invoices/Invoice.swift b/Sources/Stripe/Models/Invoices/Invoice.swift deleted file mode 100644 index 4d634aa..0000000 --- a/Sources/Stripe/Models/Invoices/Invoice.swift +++ /dev/null @@ -1,108 +0,0 @@ -// -// Invoice.swift -// Stripe -// -// Created by Anthony Castelli on 9/4/17. -// -// - -import Foundation - -/** - Invoice object - https://stripe.com/docs/api#invoice_object - */ - -public struct StripeInvoice: StripeModel { - public var id: String? - public var object: String - public var amountDue: Int? - public var amountPaid: Int? - public var amountRemanining: Int? - public var applicationFee: Int? - public var attemptCount: Int? - public var attempted: Bool? - public var autoAdvance: Bool? - public var billing: String? - public var billingReason: StripeBillingReason? - public var charge: String? - public var closed: Bool? - public var currency: StripeCurrency? - public var customer: String? - public var date: Date? - public var defaultSource: String? - public var description: String? - public var discount: StripeDiscount? - public var dueDate: Date? - public var endingBalance: Int? - public var finalizedAt: Date? - public var forgiven: Bool? - public var hostedInvoiceUrl: String? - public var invoicePdf: String? - public var lines: InvoiceLineGroup? - public var livemode: Bool? - public var metadata: [String: String] - public var nextPaymentAttempt: Date? - public var number: String? - public var paid: Bool? - public var periodEnd: Date? - public var periodStart: Date? - public var receiptNumber: String? - public var startingBalance: Int? - public var statementDescriptor: String? - public var status: StripeInvoiceStatus? - public var subscription: String? - public var subscriptionProrationDate: Int? - public var subtotal: Int? - public var total: Int? - public var tax: Int? - public var taxPercent: Decimal? - public var webhooksDeliveredAt: Date? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amountDue = "amount_due" - case amountPaid = "amount_paid" - case amountRemanining = "amount_remaining" - case applicationFee = "application_fee" - case attemptCount = "attempt_count" - case attempted - case autoAdvance = "auto_advance" - case billing - case billingReason = "billing_reason" - case charge - case closed - case currency - case customer - case date - case defaultSource = "default_source" - case description - case discount - case dueDate = "due_date" - case endingBalance = "ending_balance" - case finalizedAt = "finalized_at" - case forgiven - case hostedInvoiceUrl = "hosted_invoice_url" - case invoicePdf = "invoice_pdf" - case lines - case livemode - case metadata - case nextPaymentAttempt = "next_payment_attempt" - case number - case paid - case periodEnd = "period_end" - case periodStart = "period_start" - case receiptNumber = "receipt_number" - case startingBalance = "starting_balance" - case statementDescriptor = "statement_descriptor" - case status - case subscription - case subscriptionProrationDate = "subscription_proration_date" - case subtotal - case total - case tax - case taxPercent = "tax_percent" - case webhooksDeliveredAt = "webhooks_delivered_at" - } -} diff --git a/Sources/Stripe/Models/Invoices/InvoiceItem.swift b/Sources/Stripe/Models/Invoices/InvoiceItem.swift deleted file mode 100644 index 2e3b428..0000000 --- a/Sources/Stripe/Models/Invoices/InvoiceItem.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// InvoiceItem.swift -// Stripe -// -// Created by Anthony Castelli on 9/5/17. -// -// - -import Foundation - -/** - Invoice Items - https://stripe.com/docs/api#invoiceitems - */ - -public struct StripeInvoiceItem: StripeModel { - public var id: String? - public var object: String - public var amount: Int? - public var currency: StripeCurrency? - public var customer: String? - public var date: Date? - public var description: String? - public var discountable: Bool? - public var invoice: String? - public var livemode: Bool? - public var metadata: [String: String] - public var period: Period? - public var plan: StripePlan? - public var proration: Bool? - public var quantity: Int? - public var subscription: String? - public var subscriptionItem: String? - public var unitAmount: Int? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case currency - case customer - case date - case description - case discountable - case invoice - case livemode - case metadata - case period - case plan - case proration - case quantity - case subscription - case subscriptionItem = "subscription_item" - case unitAmount = "unit_amount" - } -} diff --git a/Sources/Stripe/Models/Invoices/InvoiceItemList.swift b/Sources/Stripe/Models/Invoices/InvoiceItemList.swift deleted file mode 100644 index 0d3b1c7..0000000 --- a/Sources/Stripe/Models/Invoices/InvoiceItemList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// InvoiceItemList.swift -// Stripe -// -// Created by Andrew Edwards on 12/7/17. -// - -/** - InvoiceItems List - https://stripe.com/docs/api#list_invoiceitems - */ - -public struct InvoiceItemsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeInvoiceItem]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} - diff --git a/Sources/Stripe/Models/Invoices/InvoiceLineGroup.swift b/Sources/Stripe/Models/Invoices/InvoiceLineGroup.swift deleted file mode 100644 index 6042ec8..0000000 --- a/Sources/Stripe/Models/Invoices/InvoiceLineGroup.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// InvoiceLineGroup.swift -// Stripe -// -// Created by Anthony Castelli on 9/5/17. -// -// - -/** - InvoiceLines list - https://stripe.com/docs/api#invoice_lines - */ - -public struct InvoiceLineGroup: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeInvoiceLineItem]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Invoices/InvoiceLineItem.swift b/Sources/Stripe/Models/Invoices/InvoiceLineItem.swift deleted file mode 100644 index fed56b8..0000000 --- a/Sources/Stripe/Models/Invoices/InvoiceLineItem.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// InvoiceLineItem.swift -// Stripe -// -// Created by Anthony Castelli on 9/5/17. -// -// - -import Foundation - -/** - InvoiceItem object - https://stripe.com/docs/api#invoice_line_item_object - */ - -public struct StripeInvoiceLineItem: StripeModel { - public var id: String? - public var object: String - public var amount: Int? - public var currency: StripeCurrency? - public var description: String? - public var discountable: Bool? - public var livemode: Bool? - public var metadata: [String: String] - public var period: Period? - public var plan: StripePlan? - public var proration: Bool? - public var quantity: Int? - public var subscription: String? - public var subscriptionItem: String? - public var type: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case currency - case description - case discountable - case livemode - case metadata - case period - case plan - case proration - case quantity - case subscription - case subscriptionItem = "subscription_item" - case type - } -} diff --git a/Sources/Stripe/Models/Invoices/InvoiceList.swift b/Sources/Stripe/Models/Invoices/InvoiceList.swift deleted file mode 100644 index ce33a57..0000000 --- a/Sources/Stripe/Models/Invoices/InvoiceList.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// InvoiceList.swift -// Stripe -// -// Created by Andrew Edwards on 12/7/17. -// - -/** - Invoices list - https://stripe.com/docs/api#list_invoices - */ - -public struct InvoicesList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeInvoice]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Invoices/Period.swift b/Sources/Stripe/Models/Invoices/Period.swift deleted file mode 100644 index 31b942b..0000000 --- a/Sources/Stripe/Models/Invoices/Period.swift +++ /dev/null @@ -1,13 +0,0 @@ -// -// Period.swift -// Stripe -// -// Created by Andrew Edwards on 12/7/17. -// - -import Foundation - -public struct Period: StripeModel { - public var start: Date? - public var end: Date? -} diff --git a/Sources/Stripe/Models/Orders/DeliveryEstimateType.swift b/Sources/Stripe/Models/Orders/DeliveryEstimateType.swift deleted file mode 100644 index 671b370..0000000 --- a/Sources/Stripe/Models/Orders/DeliveryEstimateType.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// DeliveryEstimateType.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -import Foundation - -// https://stripe.com/docs/api/curl#order_object-shipping_methods-delivery_estimate-type -public enum DeliveryEstimateType: String, Codable { - case range - case exact -} diff --git a/Sources/Stripe/Models/Orders/Order.swift b/Sources/Stripe/Models/Orders/Order.swift deleted file mode 100644 index be253fc..0000000 --- a/Sources/Stripe/Models/Orders/Order.swift +++ /dev/null @@ -1,66 +0,0 @@ -// -// Order.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -import Foundation - -/** - Order object - https://stripe.com/docs/api#order_object - */ - -public struct StripeOrder: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var amountReturned: Int? - public var application: String? - public var applicationFee: Int? - public var charge: String? - public var created: Date? - public var currency: StripeCurrency? - public var customer: String? - public var email: String? - public var externalCouponCode: String? - public var items: [StripeOrderItem]? - public var livemode: Bool? - public var metadata: [String: String] - public var returns: OrderReturnList? - public var selectedShippingMethod: String? - public var shipping: ShippingLabel? - public var shippingMethods: [StripeShippingMethod]? - public var status: OrderStatus? - public var statusTransitions: StripeOrderStatusTransitions? - public var updated: Date? - public var upstreamId: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case amountReturned = "amount_returned" - case application - case applicationFee = "application_fee" - case charge - case created - case currency - case customer - case email - case externalCouponCode = "external_coupon_code" - case items - case livemode - case metadata - case returns - case selectedShippingMethod = "selected_shipping_method" - case shipping - case shippingMethods = "shipping_methods" - case status - case statusTransitions = "status_transitions" - case updated - case upstreamId = "upstream_id" - } -} diff --git a/Sources/Stripe/Models/Orders/OrderItem.swift b/Sources/Stripe/Models/Orders/OrderItem.swift deleted file mode 100644 index a105b3d..0000000 --- a/Sources/Stripe/Models/Orders/OrderItem.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// OrderItem.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -/** - OrderItem object - https://stripe.com/docs/api#order_item_object-object - */ - -public struct StripeOrderItem: StripeModel { - public var object: String - public var amount: Int - public var currency: StripeCurrency? - public var description: String? - public var parent: String? - public var quantity: Int? - public var type: OrderItemType? -} diff --git a/Sources/Stripe/Models/Orders/OrderItemType.swift b/Sources/Stripe/Models/Orders/OrderItemType.swift deleted file mode 100644 index 7df60e4..0000000 --- a/Sources/Stripe/Models/Orders/OrderItemType.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// OrderItemType.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -public enum OrderItemType: String, Codable { - case sku - case tax - case shipping - case discount -} diff --git a/Sources/Stripe/Models/Orders/OrderList.swift b/Sources/Stripe/Models/Orders/OrderList.swift deleted file mode 100644 index 39e3f09..0000000 --- a/Sources/Stripe/Models/Orders/OrderList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// OrderList.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -/** - Orders List - https://stripe.com/docs/api/curl#list_orders - */ - -public struct OrdersList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeOrder]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Orders/OrderReturn.swift b/Sources/Stripe/Models/Orders/OrderReturn.swift deleted file mode 100644 index a62356a..0000000 --- a/Sources/Stripe/Models/Orders/OrderReturn.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// OrderReturn.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -import Foundation - -/** - OrderReturn object - https://stripe.com/docs/api#order_return_object - */ - -public struct StripeOrderReturn: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var created: Date? - public var currency: StripeCurrency? - public var items: [StripeOrderItem]? - public var livemode: Bool? - public var order: String? - public var refund: String? -} diff --git a/Sources/Stripe/Models/Orders/OrderReturnList.swift b/Sources/Stripe/Models/Orders/OrderReturnList.swift deleted file mode 100644 index 3e740cd..0000000 --- a/Sources/Stripe/Models/Orders/OrderReturnList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// OrderReturnList.swift -// Stripe -// -// Created by Andrew Edwards on 8/25/17. -// -// - -/** - Order return List - https://stripe.com/docs/api#list_order_returns - */ - -public struct OrderReturnList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeOrderReturn]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Orders/OrderStatus.swift b/Sources/Stripe/Models/Orders/OrderStatus.swift deleted file mode 100644 index fed68d0..0000000 --- a/Sources/Stripe/Models/Orders/OrderStatus.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// OrderStatus.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -public enum OrderStatus: String, Codable { - case created - case paid - case canceled - case fulfilled - case returned -} diff --git a/Sources/Stripe/Models/Other/DeletedObject.swift b/Sources/Stripe/Models/Other/DeletedObject.swift deleted file mode 100644 index 2c2fe28..0000000 --- a/Sources/Stripe/Models/Other/DeletedObject.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// DeletedObject.swift -// Stripe -// -// Created by Anthony Castelli on 4/20/17. -// -// - -import Vapor - -/** - Deleted object - https://stripe.com/docs/api/curl#delete_customer - */ - -public struct StripeDeletedObject: StripeModel { - public var id: String - public var object: String - public var deleted: Bool -} diff --git a/Sources/Stripe/Models/Payouts/Payout.swift b/Sources/Stripe/Models/Payouts/Payout.swift deleted file mode 100644 index 96f0e59..0000000 --- a/Sources/Stripe/Models/Payouts/Payout.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// Payout.swift -// Async -// -// Created by Andrew Edwards on 8/20/18. -// - -import Foundation - -/** - Payout object - https://stripe.com/docs/api/curl#payout_object - */ - -public struct StripePayout: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var arrivalDate: Date? - public var automatic: Bool? - public var balanceTransaction: String? - public var created: Date? - public var currency: StripeCurrency? - public var description: String? - public var destination: String? - public var failureBalanceTransaction: String? - public var failureCode: StripePayoutFailureCode? - public var failureMessage: String? - public var livemode: Bool? - public var metadata: [String: String] - public var method: StripePayoutMethod? - public var sourceType: StripePayoutSourceType? - public var statementDescriptor: String? - public var status: StripePayoutStatus? - public var type: StripePayoutType? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case arrivalDate = "arrival_date" - case automatic - case balanceTransaction = "balance_transaction" - case created - case currency - case description - case destination - case failureBalanceTransaction = "failure_balance_transaction" - case failureCode = "failure_code" - case failureMessage = "failure_message" - case livemode - case metadata - case method - case sourceType = "source_type" - case statementDescriptor = "statement_descriptor" - case status - case type - } -} diff --git a/Sources/Stripe/Models/Payouts/PayoutEnums.swift b/Sources/Stripe/Models/Payouts/PayoutEnums.swift deleted file mode 100644 index aa2b281..0000000 --- a/Sources/Stripe/Models/Payouts/PayoutEnums.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// PayoutMethod.swift -// Stripe -// -// Created by Andrew Edwards on 8/20/18. -// - -import Vapor - -public enum StripePayoutFailureCode: String, Content { - case accountClosed = "account_closed" - case accountFrozen = "account_frozen" - case bankAccountRestricted = "bank_account_restricted" - case bankOwnershipChanged = "bank_ownership_changed" - case couldNotProcess = "could_not_process" - case debitNotAuthorized = "debit_not_authorized" - case declined - case insufficientFunds = "insufficient_funds" - case invalidAccountNumber = "invalid_account_number" - case invalidAccountHolderName = "invalid_account_holder_name" - case invalidCurrency = "invalid_currency" - case noAccount = "no_account" - case unsupportedCard = "unsupported_card" -} - -public enum StripePayoutMethod: String, Content { - case standard - case instant -} - -public enum StripePayoutStatus: String, Content { - case paid - case pending - case inTransit = "in_transit" - case canceled - case failed -} - -public enum StripePayoutSourceType: String, Content { - case alipayAccount = "alipay_account" - case bankAccount = "bank_account" - case card -} - -public enum StripePayoutType: String, Content { - case bankAccount = "bank_account" - case card -} diff --git a/Sources/Stripe/Models/Payouts/PayoutsList.swift b/Sources/Stripe/Models/Payouts/PayoutsList.swift deleted file mode 100644 index d266e9e..0000000 --- a/Sources/Stripe/Models/Payouts/PayoutsList.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// PayoutsList.swift -// Stripe -// -// Created by Andrew Edwards on 8/21/18. -// - -/** - Payouts List - https://stripe.com/docs/api/curl#list_payouts - */ - -public struct StripePayoutsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripePayout]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Plans/BillingScheme.swift b/Sources/Stripe/Models/Plans/BillingScheme.swift deleted file mode 100644 index 61f8790..0000000 --- a/Sources/Stripe/Models/Plans/BillingScheme.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// BillingScheme.swift -// Stripe -// -// Created by Andrew Edwards on 6/17/18. -// - -import Foundation - -extension StripePlan { - - public enum BillingScheme: String, Codable { - case perUnit = "per_unit" - case tiered - } - - public enum RoundMode: String, Codable { - case up - case down - } - - public struct Tier: Codable { - public var amount: Int? - public var upTo: Int? - - public enum CodingKeys: String, CodingKey { - case amount - case upTo = "up_to" - } - } - - public enum TiersMode: String, Codable { - case graduated - case volume - } - - public struct UsageTransformation: Codable { - public var divideBy: Int? - public var round: RoundMode? - - public enum CodingKeys: String, CodingKey { - case divideBy = "divide_by" - case round - } - } - - public enum UsageType: String, Codable { - case metered - case licensed - } -} diff --git a/Sources/Stripe/Models/Plans/Plans.swift b/Sources/Stripe/Models/Plans/Plans.swift deleted file mode 100644 index 5338195..0000000 --- a/Sources/Stripe/Models/Plans/Plans.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// Plans.swift -// Stripe -// -// Created by Andrew Edwards on 5/29/17. -// -// - -import Foundation - -/** - Plan object - https://stripe.com/docs/api/curl#plan_object - */ - -public struct StripePlan: StripeModel { - public var id: String - public var object: String - public var active: Bool? - public var aggregateUsage: String? - public var amount: Int? - public var billingScheme: BillingScheme? - public var created: Date? - public var currency: StripeCurrency? - public var interval: StripePlanInterval? - public var intervalCount: Int? - public var livemode: Bool? - public var metadata: [String: String] - public var nickname: String? - public var product: String? - public var tiers: [Tier]? - public var tiersMode: TiersMode? - public var transformUsage: UsageTransformation? - public var trialPeriodDays: Int? - public var usageType: UsageType? - - public enum CodingKeys: String, CodingKey { - case id - case object - case active - case aggregateUsage = "aggregate_usage" - case amount - case billingScheme = "billing_scheme" - case created - case currency - case interval - case intervalCount = "interval_count" - case livemode - case metadata - case nickname - case product - case tiers - case tiersMode = "tiers_mode" - case transformUsage = "transform_usage" - case trialPeriodDays = "trial_period_days" - case usageType = "usage_type" - } -} diff --git a/Sources/Stripe/Models/Plans/PlansList.swift b/Sources/Stripe/Models/Plans/PlansList.swift deleted file mode 100644 index 7b0f53d..0000000 --- a/Sources/Stripe/Models/Plans/PlansList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// PlansList.swift -// Stripe -// -// Created by Andrew Edwards on 5/29/17. -// -// - -/** - Plans List - https://stripe.com/docs/api/curl#list_plans - */ - -public struct PlansList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripePlan]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Products/PackageDimensions.swift b/Sources/Stripe/Models/Products/PackageDimensions.swift deleted file mode 100644 index 135caa7..0000000 --- a/Sources/Stripe/Models/Products/PackageDimensions.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// PackageDimensions.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -import Foundation - -/** - Package Dimensions - https://stripe.com/docs/api/curl#product_object-package_dimensions - */ - -public struct StripePackageDimensions: StripeModel { - public var height: Decimal? - public var length: Decimal? - public var weight: Decimal? - public var width: Decimal? -} diff --git a/Sources/Stripe/Models/Products/Product.swift b/Sources/Stripe/Models/Products/Product.swift deleted file mode 100644 index 4a44e73..0000000 --- a/Sources/Stripe/Models/Products/Product.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// Product.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -import Foundation - -/** - Product object - https://stripe.com/docs/api#products - */ - -public struct StripeProduct: StripeModel { - public var id: String - public var object: String - public var active: Bool? - public var attributes: [String]? - public var caption: String? - public var created: Date? - public var deactivateOn: [String]? - public var description: String? - public var images: [String]? - public var livemode: Bool? - public var metadata: [String: String] - public var name: String? - public var packageDimensions: StripePackageDimensions? - public var shippable: Bool? - public var statementDescriptor: String? - public var type: ProductType? - public var updated: Date? - public var url: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case active - case attributes - case caption - case created - case deactivateOn = "deactivate_on" - case description - case images - case livemode - case metadata - case name - case packageDimensions = "package_dimensions" - case shippable - case statementDescriptor = "statement_descriptor" - case type - case updated - case url - } -} diff --git a/Sources/Stripe/Models/Products/ProductType.swift b/Sources/Stripe/Models/Products/ProductType.swift deleted file mode 100644 index 52eef0e..0000000 --- a/Sources/Stripe/Models/Products/ProductType.swift +++ /dev/null @@ -1,13 +0,0 @@ -// -// ProductType.swift -// Stripe -// -// Created by Andrew Edwards on 6/17/18. -// - -import Foundation - -public enum ProductType: String, Codable { - case service - case good -} diff --git a/Sources/Stripe/Models/Products/ProductsList.swift b/Sources/Stripe/Models/Products/ProductsList.swift deleted file mode 100644 index 7ee0165..0000000 --- a/Sources/Stripe/Models/Products/ProductsList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// ProductsList.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -/** - Products List - https://stripe.com/docs/api/curl#list_products - */ - -public struct ProductsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeProduct]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Refunds/Refund.swift b/Sources/Stripe/Models/Refunds/Refund.swift deleted file mode 100644 index c8ebf79..0000000 --- a/Sources/Stripe/Models/Refunds/Refund.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// RefundItem.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -import Foundation - -/** - Refund object - https://stripe.com/docs/api/curl#refunds - */ - -public struct StripeRefund: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var balanceTransaction: String? - public var charge: String? - public var created: Date? - public var currency: StripeCurrency? - public var failureBalanceTransaction: String? - public var failureReason: String? - public var metadata: [String: String] - public var reason: RefundReason? - public var receiptNumber: String? - public var status: StripeStatus? - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case balanceTransaction = "balance_transaction" - case charge - case created - case currency - case failureBalanceTransaction = "failure_balance_transaction" - case failureReason = "failure_reason" - case metadata - case reason - case receiptNumber = "receipt_number" - case status - } -} diff --git a/Sources/Stripe/Models/Refunds/RefundList.swift b/Sources/Stripe/Models/Refunds/RefundList.swift deleted file mode 100644 index 474f068..0000000 --- a/Sources/Stripe/Models/Refunds/RefundList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// RefundList.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -/** - Refunds list - https://stripe.com/docs/api/curl#charge_object-refunds - */ - -public struct RefundsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeRefund]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Refunds/RefundReason.swift b/Sources/Stripe/Models/Refunds/RefundReason.swift deleted file mode 100644 index 1cc3698..0000000 --- a/Sources/Stripe/Models/Refunds/RefundReason.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// RefundReason.swift -// Stripe -// -// Created by Anthony Castelli on 5/13/17. -// -// - -/** - Refund reason - https://stripe.com/docs/api/curl#refund_object-reason - */ - -public enum RefundReason: String, Codable { - case duplicate - case fraudulent - case requestedByCustomer = "requested_by_customer" -} diff --git a/Sources/Stripe/Models/SKU/Inventory.swift b/Sources/Stripe/Models/SKU/Inventory.swift deleted file mode 100644 index 210fc31..0000000 --- a/Sources/Stripe/Models/SKU/Inventory.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// Inventory.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -/** - Inventory object - https://stripe.com/docs/api/curl#sku_object-inventory - */ - -public struct StripeInventory: StripeModel { - public var quantity: Int? - public var type: InventoryType? - public var value: InventoryTypeValue? -} diff --git a/Sources/Stripe/Models/SKU/SKU.swift b/Sources/Stripe/Models/SKU/SKU.swift deleted file mode 100644 index 390ee24..0000000 --- a/Sources/Stripe/Models/SKU/SKU.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// SKU.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -import Foundation - -/** - SKU object - https://stripe.com/docs/api#skus - */ - -public struct StripeSKU: StripeModel { - public var id: String - public var object: String - public var active: Bool? - public var attributes: [String: String]? - public var created: Date? - public var currency: StripeCurrency? - public var image: String? - public var inventory: StripeInventory? - public var livemode: Bool? - public var metadata: [String: String] - public var packageDimensions: StripePackageDimensions? - public var price: Int? - public var product: String? - public var updated: Date? - - public enum CodingKeys: String, CodingKey { - case id - case object - case active - case attributes - case created - case currency - case image - case inventory - case livemode - case metadata - case packageDimensions = "package_dimensions" - case price - case product - case updated - } -} diff --git a/Sources/Stripe/Models/SKU/SKUList.swift b/Sources/Stripe/Models/SKU/SKUList.swift deleted file mode 100644 index 30b692c..0000000 --- a/Sources/Stripe/Models/SKU/SKUList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// SKUList.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -/** - SKU List - https://stripe.com/docs/api/curl#list_skus - */ - -public struct SKUList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeSKU]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Shipping/DeliveryEstimate.swift b/Sources/Stripe/Models/Shipping/DeliveryEstimate.swift deleted file mode 100644 index 678ba21..0000000 --- a/Sources/Stripe/Models/Shipping/DeliveryEstimate.swift +++ /dev/null @@ -1,19 +0,0 @@ -// -// DeliveryEstimate.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -/** - Delivery Estimate - https://stripe.com/docs/api/curl#order_object-shipping_methods-delivery_estimate - */ - -public struct StripeDeliveryEstimate: StripeModel { - public var date: String? - public var earliest: String? - public var latest: String? - public var type: DeliveryEstimateType? -} diff --git a/Sources/Stripe/Models/Shipping/OrderStatusTransitions.swift b/Sources/Stripe/Models/Shipping/OrderStatusTransitions.swift deleted file mode 100644 index 88503d7..0000000 --- a/Sources/Stripe/Models/Shipping/OrderStatusTransitions.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// StatusTransitions.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -import Foundation - -/** - StatusTransitions - https://stripe.com/docs/api/curl#order_object-status_transitions - */ - -public struct StripeOrderStatusTransitions: StripeModel { - public var canceled: Date? - public var fulfiled: Date? - public var paid: Date? - public var returned: Date? -} diff --git a/Sources/Stripe/Models/Shipping/ShippingLabel.swift b/Sources/Stripe/Models/Shipping/ShippingLabel.swift deleted file mode 100644 index 7c8c0e6..0000000 --- a/Sources/Stripe/Models/Shipping/ShippingLabel.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// ShippingLabel.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -/** - Shipping - https://stripe.com/docs/api/curl#order_object-shipping - */ - -public struct ShippingLabel: StripeModel { - public var address: StripeAddress? - public var carrier: String? - public var name: String? - public var phone: String? - public var trackingNumber: String? - - public enum CodingKeys: String, CodingKey { - case address - case carrier - case name - case phone - case trackingNumber = "tracking_number" - } -} diff --git a/Sources/Stripe/Models/Shipping/ShippingMethod.swift b/Sources/Stripe/Models/Shipping/ShippingMethod.swift deleted file mode 100644 index 103f55e..0000000 --- a/Sources/Stripe/Models/Shipping/ShippingMethod.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// ShippingMethod.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -/** - Shipping Method - https://stripe.com/docs/api/curl#order_object-shipping_methods - */ - -public struct StripeShippingMethod: StripeModel { - public var id: String - public var amount: Int? - public var currency: StripeCurrency? - public var deliveryEstimate: StripeDeliveryEstimate? - public var description: String? - - public enum CodingKeys: String, CodingKey { - case id - case amount - case currency - case deliveryEstimate = "delivery_estimate" - case description - } -} diff --git a/Sources/Stripe/Models/Shipping/StripeAddress.swift b/Sources/Stripe/Models/Shipping/StripeAddress.swift deleted file mode 100644 index cfd006a..0000000 --- a/Sources/Stripe/Models/Shipping/StripeAddress.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// StripeAddress.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -/** - Shipping Address - https://stripe.com/docs/api/curl#order_object-shipping-address - */ - -public struct StripeAddress: StripeModel { - public var city: String? - public var country: String? - public var line1: String? - public var line2: String? - public var postalCode: String? - public var state: String? - - public enum CodingKeys: String, CodingKey { - case city - case country - case line1 - case line2 - case postalCode = "postal_code" - case state - } -} diff --git a/Sources/Stripe/Models/Sources/BankAccount.swift b/Sources/Stripe/Models/Sources/BankAccount.swift deleted file mode 100644 index 7f735ee..0000000 --- a/Sources/Stripe/Models/Sources/BankAccount.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// BankAccount.swift -// Stripe -// -// Created by Anthony Castelli on 5/12/17. -// -// - -/// The bank account object. [See here](https://stripe.com/docs/api/customer_bank_accounts/object). -public struct StripeBankAccount: StripeModel { - /// Unique identifier for the object. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// The account this bank account belongs to. - public var account: String? - /// The name of the person or business that owns the bank account. - public var accountHolderName: String? - /// The type of entity that holds the account. This can be either `individual` or `company`. - public var accountHolderType: StripeBankAccountHolderType? - /// Name of the bank associated with the routing number (e.g., WELLS FARGO). - public var bankName: String? - /// Two-letter ISO code representing the country the bank account is located in. - public var country: String? - /// Three-letter ISO code for the currency paid out to the bank account. - public var currency: StripeCurrency? - /// The customer that this bank account belongs to. - public var customer: String? - /// Whether this bank account is the default external account for its currency. - public var defaultForCurrency: Bool? - /// Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. - public var fingerprint: String? - /// /// The last four digits of the bank account. - public var last4: String? - /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. - public var metadata: [String: String]? - /// The routing transit number for the bank account. - public var routingNumber: String? - /// For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. A bank account that hasn’t had any activity or validation performed is `new`. If Stripe can determine that the bank account exists, its status will be `validated`. Note that there often isn’t enough information to know (e.g., for smaller credit unions), and the validation is not always run. If customer bank account verification has succeeded, the bank account status will be `verified`. If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. If a transfer sent to this bank account fails, we’ll set the status to `errored` and will not continue to send transfers until the bank details are updated. \n For external accounts, possible values are `new` and `errored`. Validations aren’t run against external accounts because they’re only used for payouts. This means the other statuses don’t apply. If a transfer fails, the status is set to `errored` and transfers are stopped until account details are updated. - public var status: StripeBankAccountStatus? - - public enum CodingKeys: String, CodingKey { - case id - case object - case account - case accountHolderName = "account_holder_name" - case accountHolderType = "account_holder_type" - case bankName = "bank_name" - case country - case currency - case customer - case defaultForCurrency = "default_for_currency" - case fingerprint - case last4 - case metadata - case routingNumber = "routing_number" - case status - } -} - -public struct StripeBankAccountList: StripeModel { - /// String representing the object’s type. Objects of the same type share the same value. Always has the value list. - public var object: String - /// An array of `StripeCard`s associated with the account. - public var data: [StripeBankAccount]? - /// True if this list has another page of items after this one that can be fetched. - public var hasMore: Bool? - /// The URL where this list can be accessed. - public var url: String? - - private enum CodingKeys: String, CodingKey { - case object - case data - case hasMore = "has_more" - case url - } -} - -public enum StripeBankAccountStatus: String, Codable { - case new - case validated - case verified - case verificationFailed = "verification_failed" - case errored -} - -public enum StripeBankAccountHolderType: String, StripeModel { - case individual - case company -} diff --git a/Sources/Stripe/Models/Sources/Card.swift b/Sources/Stripe/Models/Sources/Card.swift deleted file mode 100644 index 72e5a3f..0000000 --- a/Sources/Stripe/Models/Sources/Card.swift +++ /dev/null @@ -1,145 +0,0 @@ -// -// Card.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -/// The card object. [See here](https://stripe.com/docs/api/external_account_cards/object). -public struct StripeCard: StripeModel { - /// Unique identifier for the object. - public var id: String - /// String representing the object’s type. Objects of the same type share the same value. - public var object: String - /// The account this card belongs to. This attribute will not be in the card object if the card belongs to a customer or recipient instead. - public var account: String? - /// City/District/Suburb/Town/Village. - public var addressCity: String? - /// Billing address country, if provided when creating card. - public var addressCountry: String? - /// Address line 1 (Street address/PO Box/Company name). - public var addressLine1: String? - /// If `address_line1` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. - public var addressLine1Check: StripeCardValidationCheck? - /// Address line 2 (Apartment/Suite/Unit/Building). - public var addressLine2: String? - /// State/County/Province/Region. - public var addressState: String? - /// ZIP or postal code. - public var addressZip: String? - /// If `address_zip` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. - public var addressZipCheck: StripeCardValidationCheck? - /// A set of available payout methods for this card. Will be either `["standard"]` or `["standard", "instant"]`. Only values from this set should be passed as the `method` when creating a transfer. - public var availablePayoutMethods: [String]? - /// Card brand. Can be `American Express`, `Diners Club`, `Discover`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. - public var brand: StripeCardBrand? - /// Two-letter ISO code representing the country of the card. You could use this attribute to get a sense of the international breakdown of cards you’ve collected. - public var country: String? - /// Three-letter ISO code for currency. Only applicable on accounts (not customers or recipients). The card can be used as a transfer destination for funds in this currency. - public var currency: StripeCurrency? - /// The customer that this card belongs to. This attribute will not be in the card object if the card belongs to an account or recipient instead. - public var customer: String? - /// If a CVC was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. - public var cvcCheck: StripeCardValidationCheck? - /// Whether this card is the default external account for its currency. - public var defaultForCurrency: Bool? - /// (For tokenized numbers only.) The last four digits of the device account number. - public var dynamicLast4: String? - /// Two-digit number representing the card’s expiration month. - public var expMonth: Int? - /// Four-digit number representing the card’s expiration year. - public var expYear: Int? - /// Uniquely identifies this particular card number. You can use this attribute to check whether two customers who’ve signed up with you are using the same card number, for example. - public var fingerprint: String? - /// Card funding type. Can be `credit`, `debit`, `prepaid`, or `unknown`. - public var funding: StripeCardFundingType? - /// The last four digits of the card. - public var last4: String? - /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. - public var metadata: [String: String]? - /// Cardholder name. - public var name: String? - /// The recipient that this card belongs to. This attribute will not be in the card object if the card belongs to a customer or account instead. - public var recipient: String? - /// If the card number is tokenized, this is the method that was used. Can be `apple_pay` or `google_pay`. - public var tokenizationMethod: StripeCardTokenizedMethod? - - public enum CodingKeys: String, CodingKey { - case id - case object - case account - case addressCity = "address_city" - case addressCountry = "address_country" - case addressLine1 = "address_line1" - case addressLine1Check = "address_line1_check" - case addressLine2 = "address_line2" - case addressState = "address_state" - case addressZip = "address_zip" - case addressZipCheck = "address_zip_check" - case availablePayoutMethods = "available_payout_methods" - case brand - case country - case customer - case cvcCheck = "cvc_check" - case defaultForCurrency = "default_for_currency" - case dynamicLast4 = "dynamic_last4" - case expMonth = "exp_month" - case expYear = "exp_year" - case fingerprint - case funding - case last4 - case metadata - case name - case recipient - case tokenizationMethod = "tokenization_method" - } -} - -public struct StripeCardList: StripeModel { - /// String representing the object’s type. Objects of the same type share the same value. Always has the value list. - public var object: String - /// An array of `StripeCard`s associated with the account. - public var data: [StripeCard]? - /// True if this list has another page of items after this one that can be fetched. - public var hasMore: Bool? - /// The URL where this list can be accessed. - public var url: String? - - private enum CodingKeys: String, CodingKey { - case object - case data - case hasMore = "has_more" - case url - } -} - -public enum StripeCardValidationCheck: String, Codable { - case pass - case failed - case unavailable - case unchecked -} - -public enum StripeCardBrand: String, Codable { - case americanExpress = "American Express" - case dinersClub = "Diners Club" - case discover = "Discover" - case jcb = "JCB" - case masterCard = "MasterCard" - case unionPay = "UnionPay" - case visa = "Visa" - case unknown = "Unknown" -} - -public enum StripeCardFundingType: String, Codable { - case credit - case debit - case prepaid - case unknown -} - -public enum StripeCardTokenizedMethod: String, Codable { - case applePay = "apple_pay" - case androidPay = "android_pay" -} diff --git a/Sources/Stripe/Models/Sources/Flow.swift b/Sources/Stripe/Models/Sources/Flow.swift deleted file mode 100644 index 2d1a74c..0000000 --- a/Sources/Stripe/Models/Sources/Flow.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// Flow.swift -// Stripe -// -// Created by Andrew Edwards on 1/26/18. -// - -/** - Flow - https://stripe.com/docs/api/curl#source_object-flow - */ - -public enum Flow: String, Codable { - case redirect - case receiver - case codeVerification = "code_verification" - case none -} diff --git a/Sources/Stripe/Models/Sources/Mandate.swift b/Sources/Stripe/Models/Sources/Mandate.swift deleted file mode 100644 index 17603fb..0000000 --- a/Sources/Stripe/Models/Sources/Mandate.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// Mandate.swift -// Stripe -// -// Created by Andrew Edwards on 1/26/18. -// - -/** - Mandate - https://stripe.com/docs/api/curl#create_source-mandate - */ - -public struct StripeMandate: StripeModel { - public var acceptance: StripeTOSAcceptance? - public var notificationMethod: String? - - public enum CodingKeys: String, CodingKey { - case acceptance - case notificationMethod = "notification_method" - } -} diff --git a/Sources/Stripe/Models/Sources/OtherSources.swift b/Sources/Stripe/Models/Sources/OtherSources.swift deleted file mode 100644 index 11759ac..0000000 --- a/Sources/Stripe/Models/Sources/OtherSources.swift +++ /dev/null @@ -1,161 +0,0 @@ -// -// OtherSources.swift -// Stripe -// -// Created by Andrew Edwards on 12/6/17. -// - -/** - Payment Sources - https://stripe.com/docs/sources - */ - -// MARK: - ThreeDSecure -public struct ThreeDSecure: StripeModel { - public var card: String? - public var customer: String? - public var authenticated: Bool? -} - -// MARK: - Giropay -public struct Giropay: StripeModel { - public var bankCode: String? - public var bic: String? - public var bankName: String? - public var statementDescriptor: String? - - public enum CodingKeys: String, CodingKey { - case bankCode = "bank_code" - case bic - case bankName = "bank_name" - case statementDescriptor = "statement_descriptor" - } -} - -// MARK: - SepaDebit -public struct SepaDebit: StripeModel { - public var bankCode: String? - public var country: String? - public var fingerprint: String? - public var last4: String? - public var mandateReference: String? - public var mandateUrl: String? - - public enum CodingKeys: String, CodingKey { - case bankCode = "bank_code" - case country - case fingerprint - case last4 - case mandateReference = "mandate_reference" - case mandateUrl = "mandate_url" - } -} - -// MARK: - iDEAL -public struct iDEAL: StripeModel { - public var bank: String? - public var bic: String? - public var ibanLast4: String? - public var statementDescriptor: String? - - public enum CodingKeys: String, CodingKey { - case bank - case bic - case ibanLast4 = "iban_last4" - case statementDescriptor = "statement_descriptor" - } -} - -// MARK: - SOFORT -public struct SOFORT: StripeModel { - public var country: String? - public var bankCode: String? - public var bic: String? - public var bankName: String? - public var ibanLast4: String? - public var preferredLanguage: String? - public var statementDescriptor: String? - - public enum CodingKeys: String, CodingKey { - case country - case bankCode = "bank_code" - case bic - case bankName = "bank_name" - case ibanLast4 = "iban_last4" - case preferredLanguage = "preferred_language" - case statementDescriptor = "statement_descriptor" - } -} - -// MARK: - Bancontact -public struct Bancontact: StripeModel { - public var bankCode: String? - public var bic: String? - public var bankName: String? - public var statementDescriptor: String? - public var preferredLanguage: String? - - public enum CodingKeys: String, CodingKey { - case bankCode = "bank_code" - case bic - case bankName = "bank_name" - case statementDescriptor = "statement_descriptor" - case preferredLanguage = "preferred_language" - } -} - -// MARK: - Alipay -public struct Alipay: StripeModel { - public var nativeUrl: String? - public var statementDescriptor: String? - - public enum CodingKeys: String, CodingKey { - case nativeUrl = "native_url" - case statementDescriptor = "statement_descriptor" - } -} - -// MARK: - P24 -public struct P24: StripeModel { - public var reference: String? -} - -// MARK: - ACH Credit Transfer -public struct ACHCreditTransfer: StripeModel { - public var accountNumber: String? - public var routingNumber: String? - public var fingerprint: String? - public var bankName: String? - public var swiftCode: String? - - public enum CodingKeys: String, CodingKey { - case accountNumber = "account_number" - case routingNumber = "routing_number" - case fingerprint - case bankName = "bank_name" - case swiftCode = "swift_code" - } -} - -// MARK: - Basic Card -public struct StripeBasicCard: StripeModel { - public var funding: StripeCardFundingType - public var expMonth: Int - public var country: String - public var threeDSecure: String - public var fingerprint: String - public var last4: String - public var brand: String - public var expYear: Int - - public enum CodingKeys: String, CodingKey { - case funding - case expMonth = "exp_month" - case country - case threeDSecure = "three_d_secure" - case fingerprint - case last4 - case brand - case expYear = "exp_year" - } -} diff --git a/Sources/Stripe/Models/Sources/Owner.swift b/Sources/Stripe/Models/Sources/Owner.swift deleted file mode 100644 index bf08281..0000000 --- a/Sources/Stripe/Models/Sources/Owner.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// Owner.swift -// Stripe -// -// Created by Anthony Castelli on 4/16/17. -// -// - -/** - Owner object - https://stripe.com/docs/api/curl#source_object-owner - */ - -public struct StripeOwner: StripeModel { - public var address: StripeAddress? - public var email: String? - public var name: String? - public var phone: String? - public var verifiedAddress: StripeAddress? - public var verifiedEmail: String? - public var verifiedName: String? - public var verifiedPhone: String? - - public enum CodingKeys: String, CodingKey { - case address - case email - case name - case phone - case verifiedAddress = "verified_address" - case verifiedEmail = "verified_email" - case verifiedName = "verified_name" - case verifiedPhone = "verified_phone" - } -} diff --git a/Sources/Stripe/Models/Sources/PaymentSource.swift b/Sources/Stripe/Models/Sources/PaymentSource.swift deleted file mode 100644 index 3c3d97e..0000000 --- a/Sources/Stripe/Models/Sources/PaymentSource.swift +++ /dev/null @@ -1,98 +0,0 @@ -// -// PaymentSource.swift -// Stripe -// -// Created by Nicolas Bachschmidt on 2018-08-09. -// - -/** - Payment Source objects - https://stripe.com/docs/api#customer_bank_account_object - https://stripe.com/docs/api#card_object - https://stripe.com/docs/api#source_object - */ - -public enum StripePaymentSource: StripeModel { - case bankAccount(StripeBankAccount) - case card(StripeCard) - case source(StripeSource) - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let object = try container.decode(String.self, forKey: .object) - switch object { - case "bank_account": - self = try .bankAccount(StripeBankAccount(from: decoder)) - case "card": - self = try .card(StripeCard(from: decoder)) - case "source": - self = try .source(StripeSource(from: decoder)) - default: - throw DecodingError.dataCorruptedError( - forKey: CodingKeys.object, - in: container, - debugDescription: "Unknown payment source \"\(object)\"" - ) - } - } - - public func encode(to encoder: Encoder) throws { - switch self { - case let .bankAccount(bankAccount): - try bankAccount.encode(to: encoder) - case let .card(card): - try card.encode(to: encoder) - case let .source(source): - try source.encode(to: encoder) - } - } - - public enum CodingKeys: String, CodingKey { - case object - } -} - -extension StripePaymentSource { - public var bankAccount: StripeBankAccount? { - guard case let .bankAccount(bankAccount) = self else { - return nil - } - return bankAccount - } - - public var card: StripeCard? { - guard case let .card(card) = self else { - return nil - } - return card - } - - public var source: StripeSource? { - guard case let .source(source) = self else { - return nil - } - return source - } - - public var id: String { - switch self { - case let .bankAccount(bankAccount): - return bankAccount.id - case let .card(card): - return card.id - case let .source(source): - return source.id - } - } - - public var object: String { - switch self { - case let .bankAccount(bankAccount): - return bankAccount.object - case let .card(card): - return card.object - case let .source(source): - return source.object - } - } -} diff --git a/Sources/Stripe/Models/Sources/Receiver.swift b/Sources/Stripe/Models/Sources/Receiver.swift deleted file mode 100644 index 08bffa3..0000000 --- a/Sources/Stripe/Models/Sources/Receiver.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// Receiver.swift -// Stripe -// -// Created by Anthony Castelli on 4/16/17. -// -// - -/** - Receiver object - https://stripe.com/docs/api/curl#source_object-receiver - */ - -public struct StripeReceiver: StripeModel { - public var address: String - public var amountCharged: Int? - public var amountReceived: Int? - public var amountReturned: Int? - public var refundAttributesMethod: String? - public var refundAttributesStatus: String? - - public enum CodingKeys: String, CodingKey { - case address - case amountCharged = "amount_charged" - case amountReceived = "amount_received" - case amountReturned = "amount_returned" - case refundAttributesMethod = "refund_attributes_method" - case refundAttributesStatus = "refund_attributes_status" - } -} diff --git a/Sources/Stripe/Models/Sources/Source.swift b/Sources/Stripe/Models/Sources/Source.swift deleted file mode 100644 index cef36ff..0000000 --- a/Sources/Stripe/Models/Sources/Source.swift +++ /dev/null @@ -1,131 +0,0 @@ -// -// Source.swift -// Stripe -// -// Created by Anthony Castelli on 4/15/17. -// -// - -import Foundation - -/** - Source object - https://stripe.com/docs/api/curl#source_object - */ - -// TODO: - Add multibanco, EPS -// https://stripe.com/docs/sources - -public struct StripeSource: StripeModel { - public var id: String - public var object: String - public var amount: Int? - public var clientSecret: String? - public var codeVerification: CodeVerification? - public var created: Date? - public var currency: StripeCurrency? - public var flow: Flow? - public var livemode: Bool? - public var metadata: [String: String] - public var owner: StripeOwner? - public var receiver: StripeReceiver? - public var redirect: SourceRedirect? - public var statementDescriptor: String? - public var status: StripeStatus? - public var type: SourceType? - public var usage: String? - public var card: StripeBasicCard? - public var threeDSecure: ThreeDSecure? - public var giropay: Giropay? - public var sepaDebit: SepaDebit? - public var ideal: iDEAL? - public var sofort: SOFORT? - public var bancontact: Bancontact? - public var alipay: Alipay? - public var p24: P24? - public var achCreditTransfer: ACHCreditTransfer? - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - id = try container.decode(String.self, forKey: .id) - object = try container.decode(String.self, forKey: .object) - amount = try container.decodeIfPresent(Int.self, forKey: .amount) - clientSecret = try container.decodeIfPresent(String.self, forKey: .clientSecret) - codeVerification = try container.decodeIfPresent(CodeVerification.self, forKey: .codeVerification) - created = try container.decodeIfPresent(Date.self, forKey: .created) - currency = try container.decodeIfPresent(StripeCurrency.self, forKey: .currency) - flow = try container.decodeIfPresent(Flow.self, forKey: .flow) - livemode = try container.decodeIfPresent(Bool.self, forKey: .livemode) - metadata = try container.decode([String: String].self, forKey: .metadata) - owner = try container.decodeIfPresent(StripeOwner.self, forKey: .owner) - receiver = try container.decodeIfPresent(StripeReceiver.self, forKey: .receiver) - redirect = try container.decodeIfPresent(SourceRedirect.self, forKey: .redirect) - statementDescriptor = try container.decodeIfPresent(String.self, forKey: .statementDescriptor) - status = try container.decodeIfPresent(StripeStatus.self, forKey: .status) - usage = try container.decodeIfPresent(String.self, forKey: .usage) - type = try container.decodeIfPresent(SourceType.self, forKey: .type) - if let sourceType = type { - switch sourceType { - case .card: - card = try container.decodeIfPresent(StripeBasicCard.self, forKey: .card) - - case .threeDSecure: - threeDSecure = try container.decodeIfPresent(ThreeDSecure.self, forKey: .threeDSecure) - - case .giropay: - giropay = try container.decodeIfPresent(Giropay.self, forKey: .giropay) - - case .sepaDebit: - sepaDebit = try container.decodeIfPresent(SepaDebit.self, forKey: .sepaDebit) - - case .ideal: - ideal = try container.decodeIfPresent(iDEAL.self, forKey: .ideal) - - case .sofort: - sofort = try container.decodeIfPresent(SOFORT.self, forKey: .sofort) - - case .bancontact: - bancontact = try container.decodeIfPresent(Bancontact.self, forKey: .bancontact) - - case .alipay: - alipay = try container.decodeIfPresent(Alipay.self, forKey: .alipay) - - case .p24: - p24 = try container.decodeIfPresent(P24.self, forKey: .p24) - - case .achCreditTransfer: - achCreditTransfer = try container.decodeIfPresent(ACHCreditTransfer.self, forKey: .achCreditTransfer) - } - } - } - - public enum CodingKeys: String, CodingKey { - case id - case object - case amount - case clientSecret = "client_secret" - case codeVerification = "code_verification" - case created - case currency - case flow - case livemode - case metadata - case owner - case receiver - case redirect - case statementDescriptor = "statement_descriptor" - case status - case usage - case type - case card - case threeDSecure = "three_d_secure" - case giropay - case sepaDebit = "sepa_debit" - case ideal - case sofort - case bancontact - case alipay - case p24 - case achCreditTransfer = "ach_credit_transfer" - } -} diff --git a/Sources/Stripe/Models/Sources/SourceList.swift b/Sources/Stripe/Models/Sources/SourceList.swift deleted file mode 100644 index fb7affd..0000000 --- a/Sources/Stripe/Models/Sources/SourceList.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// SourceList.swift -// Stripe -// -// Created by Anthony Castelli on 4/20/17. -// -// - -/** - Sources list - https://stripe.com/docs/api#customer_object-sources - */ - -public struct StripeSourcesList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripePaymentSource]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} - -extension StripeSourcesList { - - public var bankAccounts: [StripeBankAccount]? { - return data?.compactMap { $0.bankAccount } - } - - public var cards: [StripeCard]? { - return data?.compactMap { $0.card } - } - - public var sources: [StripeSource]? { - return data?.compactMap { $0.source } - } -} diff --git a/Sources/Stripe/Models/Sources/SourceRedirect.swift b/Sources/Stripe/Models/Sources/SourceRedirect.swift deleted file mode 100644 index f205534..0000000 --- a/Sources/Stripe/Models/Sources/SourceRedirect.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// SourceRedirect.swift -// Stripe -// -// Created by Andrew Edwards on 12/4/17. -// - -public struct SourceRedirect: StripeModel { - public var failureReason: String? - public var returnUrl: String? - public var status: String? - public var url: String? - - public enum CodingKeys: String, CodingKey { - case failureReason = "failure_reason" - case returnUrl = "return_url" - case status - case url - } -} diff --git a/Sources/Stripe/Models/Sources/SourceType.swift b/Sources/Stripe/Models/Sources/SourceType.swift deleted file mode 100644 index f4dd175..0000000 --- a/Sources/Stripe/Models/Sources/SourceType.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// SourceType.swift -// Stripe -// -// Created by Anthony Castelli on 4/14/17. -// -// - -/** - Source type - https://stripe.com/docs/api/curl#source_object-type - */ - -public enum SourceType: String, Codable { - case card - case achCreditTransfer = "ach_credit_transfer" - case threeDSecure = "three_d_secure" - case giropay - case sepaDebit = "sepa_debit" - case ideal - case sofort - case bancontact - case alipay - case p24 -} diff --git a/Sources/Stripe/Models/StripeModel.swift b/Sources/Stripe/Models/StripeModel.swift deleted file mode 100644 index a32cfe5..0000000 --- a/Sources/Stripe/Models/StripeModel.swift +++ /dev/null @@ -1,123 +0,0 @@ -// -// StripeModel.swift -// Stripe -// -// Created by Anthony Castelli on 4/14/17. -// -// - -import Vapor -import Foundation - -public protocol StripeModel: Content { - func toEncodedBody() throws -> String - func toEncodedDictionary() throws -> [String: Any] -} - -extension StripeModel { - public func toEncodedBody() throws -> String { - return try self.toEncodedDictionary().queryParameters - } - - public func toEncodedDictionary() throws -> [String: Any] { - let encoded = try JSONEncoder().encode(self) - - let jsonString = String(data: encoded, encoding: .utf8) ?? "" - - let final = try JSONDecoder().decode(AnyDecodable.self, from: jsonString.data(using: .utf8) ?? Data()).value as? [String: Any] ?? [:] - - return final - } -} - -public struct AnyDecodable: Decodable { - public var value: Any - - private struct CodingKeys: CodingKey { - var stringValue: String - var intValue: Int? - init?(intValue: Int) { - self.stringValue = "\(intValue)" - self.intValue = intValue - } - init?(stringValue: String) { self.stringValue = stringValue } - } - - public init(from decoder: Decoder) throws { - if let container = try? decoder.container(keyedBy: CodingKeys.self) { - var result = [String: Any]() - try container.allKeys.forEach { (key) throws in - result[key.stringValue] = try container.decode(AnyDecodable.self, forKey: key).value - } - value = result - } else if var container = try? decoder.unkeyedContainer() { - var result = [Any]() - while !container.isAtEnd { - result.append(try container.decode(AnyDecodable.self).value) - } - value = result - } else if let container = try? decoder.singleValueContainer() { - if let intVal = try? container.decode(Int.self) { - value = intVal - } else if let doubleVal = try? container.decode(Double.self) { - value = doubleVal - } else if let boolVal = try? container.decode(Bool.self) { - value = boolVal - } else if let stringVal = try? container.decode(String.self) { - value = stringVal - } else { - throw DecodingError.dataCorruptedError(in: container, debugDescription: "the container contains nothing serialisable") - } - } else { - throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not serialise")) - } - } -} - -extension Dictionary where Key == String { - var queryParameters: String { - // A quick implementation of URLEncodedFormSerializer that includes indices in array key-paths - // -> `items[0][plan]=...` instead of `items[][plan]=...` - return Dictionary.queryComponents(keyPath: [], self).map { keyPath, value in - "\(keyPath.queryKeyPercentEncoded)=\(value.queryValuePercentEncoded)" - }.joined(separator: "&") - } - - private static func queryComponents(keyPath: [String], _ value: Any) -> [([String], String)] { - if let dictionary = value as? [String: Any] { - return dictionary.flatMap { key, value in - queryComponents(keyPath: keyPath + [key], value) - } - } else if let array = value as? [Any] { - return array.enumerated().flatMap { idx, value in - queryComponents(keyPath: keyPath + ["\(idx)"], value) - } - } else { - return [(keyPath, "\(value)")] - } - } -} - -private extension CharacterSet { - static var queryComponentAllowed: CharacterSet = { - var characterSet = CharacterSet.urlQueryAllowed - characterSet.remove("&") - characterSet.remove("+") - return characterSet - }() -} - -private extension Sequence where Element == String { - var queryKeyPercentEncoded: String { - return enumerated().map { idx, key in - let encodedKey = key.queryValuePercentEncoded - return idx == 0 ? encodedKey : "[\(encodedKey)]" - }.joined() - } -} - -private extension String { - var queryValuePercentEncoded: String { - return addingPercentEncoding(withAllowedCharacters: .queryComponentAllowed) ?? "" - } -} diff --git a/Sources/Stripe/Models/Subscriptions/StripeSubscriptionsList.swift b/Sources/Stripe/Models/Subscriptions/StripeSubscriptionsList.swift deleted file mode 100644 index d31ab15..0000000 --- a/Sources/Stripe/Models/Subscriptions/StripeSubscriptionsList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// StripeSubscriptionsList.swift -// Stripe -// -// Created by Anthony Castelli on 4/20/17. -// -// - -/** - Subscriptions List - https://stripe.com/docs/api/curl#list_subscriptions - */ - -public struct StripeSubscriptionsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeSubscription]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Subscriptions/Subscription.swift b/Sources/Stripe/Models/Subscriptions/Subscription.swift deleted file mode 100644 index b14b967..0000000 --- a/Sources/Stripe/Models/Subscriptions/Subscription.swift +++ /dev/null @@ -1,68 +0,0 @@ -// -// Subscription.swift -// Stripe -// -// Created by Andrew Edwards on 6/6/17. -// -// - -import Foundation - -/** - Subscription object - https://stripe.com/docs/api/curl#subscription_object - */ - -public struct StripeSubscription: StripeModel { - public var id: String - public var object: String - public var applicationFeePercent: Decimal? - public var billing: String? - public var billingCycleAnchor: Date? - public var cancelAtPeriodEnd: Bool? - public var canceledAt: Date? - public var created: Date? - public var currentPeriodEnd: Date? - public var currentPeriodStart: Date? - public var customer: String? - public var daysUntilDue: Int? - public var discount: StripeDiscount? - public var endedAt: Date? - public var items: SubscriptionItemsList? - public var livemode: Bool? - public var metadata: [String: String] - public var plan: StripePlan? - public var quantity: Int? - public var start: Date? - public var status: StripeSubscriptionStatus? - public var taxPercent: Decimal? - public var trialEnd: Date? - public var trialStart: Date? - - public enum CodingKeys: String, CodingKey { - case id - case object - case applicationFeePercent = "application_fee_percent" - case billing - case billingCycleAnchor = "billing_cycle_anchor" - case cancelAtPeriodEnd = "cancel_at_period_end" - case canceledAt = "canceled_at" - case created - case currentPeriodEnd = "current_period_end" - case currentPeriodStart = "current_period_start" - case customer - case daysUntilDue = "days_until_due" - case discount - case endedAt = "ended_at" - case items - case livemode - case metadata - case plan - case quantity - case start - case status - case taxPercent = "tax_percent" - case trialEnd = "trial_end" - case trialStart = "trial_start" - } -} diff --git a/Sources/Stripe/Models/Subscriptions/SubscriptionItem.swift b/Sources/Stripe/Models/Subscriptions/SubscriptionItem.swift deleted file mode 100644 index 93cdc06..0000000 --- a/Sources/Stripe/Models/Subscriptions/SubscriptionItem.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// SubscriptionItem.swift -// Stripe -// -// Created by Andrew Edwards on 6/6/17. -// -// - -import Foundation - -/** - SubscriptionItem object - https://stripe.com/docs/api/curl#subscription_items - */ - -public struct StripeSubscriptionItem: StripeModel { - public var id: String - public var object: String - public var created: Date? - public var metadata: [String: String] - public var plan: StripePlan? - public var quantity: Int? - public var subscription: String? - - public enum CodingKeys: String, CodingKey { - case id - case object - case created - case metadata - case plan - case quantity - case subscription - } -} diff --git a/Sources/Stripe/Models/Subscriptions/SubscriptionItemsList.swift b/Sources/Stripe/Models/Subscriptions/SubscriptionItemsList.swift deleted file mode 100644 index 951c2a0..0000000 --- a/Sources/Stripe/Models/Subscriptions/SubscriptionItemsList.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// SubscriptionItemsList.swift -// Stripe -// -// Created by Andrew Edwards on 6/8/17. -// -// - -/** - SubscriptionItem List - https://stripe.com/docs/api/curl#list_subscription_items - */ - -public struct SubscriptionItemsList: StripeModel { - public var object: String - public var hasMore: Bool - public var totalCount: Int? - public var url: String? - public var data: [StripeSubscriptionItem]? - - public enum CodingKeys: String, CodingKey { - case object - case hasMore = "has_more" - case totalCount = "total_count" - case url - case data - } -} diff --git a/Sources/Stripe/Models/Tokens/Token.swift b/Sources/Stripe/Models/Tokens/Token.swift deleted file mode 100644 index cfbe9fd..0000000 --- a/Sources/Stripe/Models/Tokens/Token.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// Token.swift -// Stripe -// -// Created by Anthony Castelli on 4/23/17. -// -// - -import Foundation - -/** - Token object - https://stripe.com/docs/api/curl#token_object - */ - -public struct StripeToken: StripeModel { - public var id: String - public var object: String - public var type: TokenType? - public var clientIp: String? - public var created: Date? - public var livemode: Bool? - public var used: Bool? - public var card: StripeCard? - public var bankAccount: StripeBankAccount? - - public enum CodingKeys: String, CodingKey { - case id - case object - case type - case clientIp = "client_ip" - case created - case livemode - case used - case card - case bankAccount = "bank_account" - } -} diff --git a/Sources/Stripe/Models/Tokens/TokenType.swift b/Sources/Stripe/Models/Tokens/TokenType.swift deleted file mode 100644 index a1aceaf..0000000 --- a/Sources/Stripe/Models/Tokens/TokenType.swift +++ /dev/null @@ -1,16 +0,0 @@ -// -// TokenType.swift -// Stripe -// -// Created by Andrew Edwards on 6/17/18. -// - -import Foundation - -public enum TokenType: String, Codable { - case account - case bankAccount = "bank_account" - case card - case pii -} - diff --git a/Sources/Stripe/Provider/Provider.swift b/Sources/Stripe/Provider/Provider.swift deleted file mode 100644 index b676978..0000000 --- a/Sources/Stripe/Provider/Provider.swift +++ /dev/null @@ -1,112 +0,0 @@ -// -// Stripe.swift -// Stripe -// -// Created by Anthony Castelli on 4/13/17. -// -// - -import Vapor - -public struct StripeConfig: Service { - public let apiKey: String - public let testApiKey: String? - - public init(apiKey: String) { - self.apiKey = apiKey - self.testApiKey = nil - } - - public init(productionKey: String, testKey: String) { - self.apiKey = productionKey - self.testApiKey = testKey - } -} - -public final class StripeProvider: Provider { - public static let repositoryName = "stripe-provider" - - public init() { } - - public func boot(_ worker: Container) throws { } - - public func didBoot(_ worker: Container) throws -> EventLoopFuture { - return .done(on: worker) - } - - public func register(_ services: inout Services) throws { - services.register { (container) -> StripeClient in - let httpClient = try container.make(Client.self) - let config = try container.make(StripeConfig.self) - return StripeClient(apiKey: config.apiKey, testKey: config.testApiKey, client: httpClient) - } - } -} - -public final class StripeClient: Service { - public var balance: BalanceRoutes - public var charge: ChargeRoutes - public var connectAccount: AccountRoutes - public var coupon: CouponRoutes - public var customer: CustomerRoutes - public var dispute: DisputeRoutes - public var ephemeralKey: EphemeralKeyRoutes - public var invoiceItem: InvoiceItemRoutes - public var invoice: InvoiceRoutes - public var orderReturn: OrderReturnRoutes - public var order: OrderRoutes - public var plan: PlanRoutes - public var product: ProductRoutes - public var refund: RefundRoutes - public var sku: SKURoutes - public var source: SourceRoutes - public var subscriptionItem: SubscriptionItemRoutes - public var subscription: SubscriptionRoutes - public var token: TokenRoutes - public var transfer: TransferRoutes - public var transferReversals: TransferReversalRoutes - public var payouts: PayoutRoutes - public var fileLinks: FileLinkRoutes - public var files: FileRoutes - public var person: PersonRoutes - public var applicationFee: ApplicationFeesRoutes - public var applicationFeeRefunds: ApplicationFeeRefundRoutes - public var externalAccounts: ExternalAccountsRoutes - public var countrySpecs: CountrySpecRoutes - public var topup: TopUpRoutes - - internal init(apiKey: String, testKey: String?, client: Client) { - let apiRequest = StripeAPIRequest(httpClient: client, apiKey: apiKey, testApiKey: testKey) - - balance = StripeBalanceRoutes(request: apiRequest) - charge = StripeChargeRoutes(request: apiRequest) - connectAccount = StripeConnectAccountRoutes(request: apiRequest) - coupon = StripeCouponRoutes(request: apiRequest) - customer = StripeCustomerRoutes(request: apiRequest) - dispute = StripeDisputeRoutes(request: apiRequest) - ephemeralKey = StripeEphemeralKeyRoutes(request: apiRequest) - invoiceItem = StripeInvoiceItemRoutes(request: apiRequest) - invoice = StripeInvoiceRoutes(request: apiRequest) - orderReturn = StripeOrderReturnRoutes(request: apiRequest) - order = StripeOrderRoutes(request: apiRequest) - plan = StripePlanRoutes(request: apiRequest) - product = StripeProductRoutes(request: apiRequest) - refund = StripeRefundRoutes(request: apiRequest) - sku = StripeSKURoutes(request: apiRequest) - source = StripeSourceRoutes(request: apiRequest) - subscriptionItem = StripeSubscriptionItemRoutes(request: apiRequest) - subscription = StripeSubscriptionRoutes(request: apiRequest) - token = StripeTokenRoutes(request: apiRequest) - transfer = StripeTransferRoutes(request: apiRequest) - transferReversals = StripeTransferReversalRoutes(request: apiRequest) - payouts = StripePayoutRoutes(request: apiRequest) - fileLinks = StripeFileLinkRoutes(request: apiRequest) - files = StripeFileRoutes(request: apiRequest) - person = StripePersonRoutes(request: apiRequest) - applicationFee = StripeApplicationFeeRoutes(request: apiRequest) - applicationFeeRefunds = StripeApplicationFeeRefundRoutes(request: apiRequest) - externalAccounts = StripeExternalAccountsRoutes(request: apiRequest) - countrySpecs = StripeCountrySpecRoutes(request: apiRequest) - topup = StripeTopUpRoutes(request: apiRequest) - } -} diff --git a/Sources/Stripe/StripeProvider.swift b/Sources/Stripe/StripeProvider.swift new file mode 100644 index 0000000..240d0f2 --- /dev/null +++ b/Sources/Stripe/StripeProvider.swift @@ -0,0 +1,27 @@ +// +// StripeProvider.swift +// +// +// Created by Andrew Edwards on 6/14/19. +// + +import Vapor +import StripeKit + +public struct StripeConfiguration { + public var apiKey: String + + public init(apiKey: String) { + self.apiKey = apiKey + } +} + +public final class StripeProvider: Provider { + public init() { } + public func register(_ s: inout Services) { + s.register(StripeClient.self) { container -> StripeClient in + let providerConfiguration = try container.make(StripeConfiguration.self) + return StripeClient(eventLoop: container.eventLoop, apiKey: providerConfiguration.apiKey) + } + } +} diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index e826dfa..3c6f89c 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -1,8 +1,6 @@ import XCTest -import StripeTests var tests = [XCTestCaseEntry]() -tests += StripeTests.__allTests() XCTMain(tests) diff --git a/Tests/StripeTests/AccountTests.swift b/Tests/StripeTests/AccountTests.swift deleted file mode 100644 index 81d620b..0000000 --- a/Tests/StripeTests/AccountTests.swift +++ /dev/null @@ -1,332 +0,0 @@ -// -// AccountTests.swift -// Stripe -// -// Created by Andrew Edwards on 7/9/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class AccountTests: XCTestCase { - let accountString = """ -{ - "id": "acct_1032D82eZvKYlo2C", - "object": "account", - "business_profile": { - "mcc": "hello", - "name": "Vapor", - "product_description": "Something", - "support_address" : { - "city": null, - "country": "US", - "line1": null, - "line2": null, - "postal_code": "12345", - "state": null - }, - "support_email": "a@b.com", - "support_phone": "1", - "support_url": "http", - "url": "https://www.stripe.com" - }, - "business_type": "individual", - "capabilities": { - "card_payments": "active", - "platform_payments": "inactive" - }, - "charges_enabled": false, - "company": { - "address": { - "city": null, - "country": "US", - "line1": null, - "line2": null, - "postal_code": null, - "state": null - }, - "directors_provided": false, - "name": "Vapor", - "owners_provided": true, - "phone": "1", - "tax_id_provided": false, - "tax_id_registrar": "bob", - "vat_id_provided": true - }, - "country": "US", - "created": 1385798567, - "default_currency": "usd", - "details_submitted": false, - "email": "site@stripe.com", - "external_accounts": { - "object": "list", - "data": [ - { - "id": "ba_1BnxhQ2eZvKYlo2C5cM6hYK1", - "object": "bank_account", - "account_holder_name": "Jane Austen", - "account_holder_type": "individual", - "bank_name": "STRIPE TEST BANK", - "country": "US", - "currency": "usd", - "fingerprint": "1JWtPxqbdX5Gamtc", - "last4": "6789", - "metadata": { - "hello": "world" - }, - "routing_number": "110000000", - "status": "new" - }, - { - "brand": "Visa", - "exp_month": 8, - "exp_year": 2019, - "country": "US", - "fingerprint": "H5flqusa75kgwmml", - "funding": "unknown", - "id": "card_1BoJ2IKrZ43eBVAbSXsWRMXT", - "last4": "4242", - "metadata": {}, - "object": "card" - } - ], - "has_more": false, - "url": "/v1/accounts/acct_1032D82eZvKYlo2C/external_accounts" - }, - "individual": { - "id": "person_8VPUvxRDdnt3Q8", - "object": "person", - "account": "acct_16Ds3sAU9AiAmxbB", - "address": { - "city": null, - "country": "US", - "line1": null, - "line2": null, - "postal_code": null, - "state": null - }, - "created": 1434353476, - "dob": { - "day": 1, - "month": 1, - "year": 2019 - }, - "first_name": null, - "id_number_provided": false, - "last_name": "carl", - "metadata": {}, - "relationship": { - "account_opener": true, - "director": false, - "owner": true, - "percent_ownership": 100.0, - "title": "CEO" - }, - "requirements": { - "currently_due": [ - "dob.day", - "dob.month", - "dob.year", - "first_name", - "last_name", - "ssn_last_4" - ], - "eventually_due": [], - "past_due": [] - }, - "ssn_last_4_provided": false, - "verification": { - "details": null, - "details_code": "scan_name_mismatch", - "document": { - "back": null, - "details": null, - "details_code": "document_id_country_not_supported", - "front": null - }, - "status": "unverified" - } - }, - "metadata": { - }, - "payouts_enabled": false, - "requirements": { - "current_deadline": null, - "currently_due": [ - "external_account", - "individual.address.city", - "individual.address.line1", - "individual.address.postal_code", - "individual.address.state", - "individual.dob.day", - "individual.dob.month", - "individual.dob.year", - "individual.first_name", - "individual.last_name", - "individual.ssn_last_4", - "product_description", - "tos_acceptance.date", - "tos_acceptance.ip" - ], - "disabled_reason": "requirements.past_due", - "eventually_due": [ - "external_account", - "product_description", - "tos_acceptance.date", - "tos_acceptance.ip" - ], - "past_due": [] - }, - "settings": { - "branding": { - "icon": "wow", - "logo": null, - "primary_color": "FFFFFF" - }, - "card_payments": { - "decline_on": { - "avs_failure": false, - "cvc_failure": true - } - }, - "dashboard": { - "display_name": "StripeVapor", - "timezone": "America/Indianapolis" - }, - "payments": { - "statement_descriptor": "BLAH" - }, - "payouts": { - "debit_negative_balances": true, - "schedule": { - "delay_days": 2, - "interval": "daily" - }, - "statement_descriptor": "MORE" - } - }, - "tos_acceptance": { - "date": 1385798567, - "ip": "0.0.0.0", - "user_agent": "ios-safari" - }, - "type": "standard" -} -""" - - func testAccountParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: accountString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let account = try decoder.decode(StripeConnectAccount.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() - - XCTAssertEqual(account.id, "acct_1032D82eZvKYlo2C") - XCTAssertEqual(account.object, "account") - XCTAssertEqual(account.businessProfile?.url, "https://www.stripe.com") - XCTAssertEqual(account.businessProfile?.name, "Vapor") - XCTAssertEqual(account.businessProfile?.mcc, "hello") - XCTAssertEqual(account.businessProfile?.supportUrl, "http") - XCTAssertEqual(account.businessProfile?.productDescription, "Something") - XCTAssertEqual(account.businessProfile?.supportAddress?.postalCode, "12345") - XCTAssertEqual(account.businessProfile?.supportPhone, "1") - XCTAssertEqual(account.businessProfile?.supportEmail, "a@b.com") - XCTAssertEqual(account.businessType, .individual) - XCTAssertEqual(account.capabilities?.cardPayments, .active) - XCTAssertEqual(account.capabilities?.platformPayments, .inactive) - XCTAssertEqual(account.chargesEnabled, false) - XCTAssertEqual(account.company?.address?.country, "US") - XCTAssertEqual(account.company?.directorsProvided, false) - XCTAssertEqual(account.company?.name, "Vapor") - XCTAssertEqual(account.company?.ownersProvided, true) - XCTAssertEqual(account.company?.phone, "1") - XCTAssertEqual(account.company?.taxIdProvided, false) - XCTAssertEqual(account.company?.taxIdRegistrar, "bob") - XCTAssertEqual(account.company?.vatIdProvided, true) - XCTAssertEqual(account.country, "US") - XCTAssertEqual(account.created, Date(timeIntervalSince1970: 1385798567)) - XCTAssertEqual(account.defaultCurrency, .usd) - XCTAssertEqual(account.detailsSubmitted, false) - XCTAssertEqual(account.email, "site@stripe.com") - - // ExternalAccounts - XCTAssertEqual(account.externalAccounts?.object, "list") - XCTAssertEqual(account.externalAccounts?.hasMore, false) - XCTAssertEqual(account.externalAccounts?.url, "/v1/accounts/acct_1032D82eZvKYlo2C/external_accounts") - XCTAssertEqual(account.externalAccounts?.cardAccounts?.count, 1) - XCTAssertEqual(account.externalAccounts?.bankAccounts?.count, 1) - XCTAssertEqual(account.externalAccounts?.cardAccounts?[0].id, "card_1BoJ2IKrZ43eBVAbSXsWRMXT") - XCTAssertEqual(account.externalAccounts?.bankAccounts?[0].id, "ba_1BnxhQ2eZvKYlo2C5cM6hYK1") - - // Individual/Person - XCTAssertEqual(account.individual?.id, "person_8VPUvxRDdnt3Q8") - XCTAssertEqual(account.individual?.object, "person") - XCTAssertEqual(account.individual?.account, "acct_16Ds3sAU9AiAmxbB") - XCTAssertEqual(account.individual?.address?.country, "US") - XCTAssertEqual(account.individual?.created, Date(timeIntervalSince1970: 1434353476)) - XCTAssertEqual(account.individual?.dob?.day, 1) - XCTAssertEqual(account.individual?.dob?.month, 1) - XCTAssertEqual(account.individual?.dob?.year, 2019) - XCTAssertEqual(account.individual?.firstName, nil) - XCTAssertEqual(account.individual?.idNumberProvided, false) - XCTAssertEqual(account.individual?.lastName, "carl") - XCTAssertEqual(account.individual?.metadata, [:]) - XCTAssertEqual(account.individual?.relationship?.accountOpener, true) - XCTAssertEqual(account.individual?.relationship?.director, false) - XCTAssertEqual(account.individual?.relationship?.owner, true) - XCTAssertEqual(account.individual?.relationship?.percentOwnership, 100.0) - XCTAssertEqual(account.individual?.relationship?.title, "CEO") - XCTAssertEqual(account.individual?.requirements?.currentlyDue?.count, 6) - XCTAssertEqual(account.individual?.requirements?.eventuallyDue?.count, 0) - XCTAssertEqual(account.individual?.requirements?.pastDue?.count, 0) - XCTAssertEqual(account.individual?.ssnLast4Provided, false) - XCTAssertEqual(account.individual?.verification?.details, nil) - XCTAssertEqual(account.individual?.verification?.detailsCode, .scanNameMismatch) - XCTAssertEqual(account.individual?.verification?.document?.detailsCode, .documentIdCountryNotSupported) - XCTAssertEqual(account.individual?.verification?.status, .unverified) - - XCTAssertEqual(account.metadata, [:]) - XCTAssertEqual(account.payoutsEnabled, false) - - // Requirements - XCTAssertEqual(account.requirements?.currentDeadline, nil) - XCTAssertEqual(account.requirements?.currentlyDue?.count, 14) - XCTAssertEqual(account.requirements?.disabledReason, "requirements.past_due") - XCTAssertEqual(account.requirements?.eventuallyDue?.count, 4) - XCTAssertEqual(account.requirements?.pastDue?.count, 0) - - // Settings - XCTAssertEqual(account.settings?.branding?.icon, "wow") - XCTAssertEqual(account.settings?.branding?.logo, nil) - XCTAssertEqual(account.settings?.branding?.primaryColor, "FFFFFF") - - XCTAssertEqual(account.settings?.cardPayments?.declineOn?.avsFailure, false) - XCTAssertEqual(account.settings?.cardPayments?.declineOn?.cvcFailure, true) - - XCTAssertEqual(account.settings?.dashboard?.displayName, "StripeVapor") - XCTAssertEqual(account.settings?.dashboard?.timezone, "America/Indianapolis") - - XCTAssertEqual(account.settings?.payments?.statementDescriptor, "BLAH") - XCTAssertEqual(account.settings?.payouts?.debitNegativeBalances, true) - XCTAssertEqual(account.settings?.payouts?.schedule?.delayDays, 2) - XCTAssertEqual(account.settings?.payouts?.schedule?.interval, .daily) - XCTAssertEqual(account.settings?.payouts?.statementDescriptor, "MORE") - - // TOS acceptance - XCTAssertEqual(account.tosAcceptance?.date, Date(timeIntervalSince1970: 1385798567)) - XCTAssertEqual(account.tosAcceptance?.ip, "0.0.0.0") - XCTAssertEqual(account.tosAcceptance?.userAgent, "ios-safari") - - XCTAssertEqual(account.type, .standard) - } - catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/ApplicationFeeTests.swift b/Tests/StripeTests/ApplicationFeeTests.swift deleted file mode 100644 index 10fbcee..0000000 --- a/Tests/StripeTests/ApplicationFeeTests.swift +++ /dev/null @@ -1,111 +0,0 @@ -// -// ApplicationFeeTests.swift -// StripeTests -// -// Created by Andrew Edwards on 3/17/19. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class ApplicationFeeTests: XCTestCase { - let applicationFeeRefundString = """ -{ - "id": "fr_1EEtTKKbnvuxQXGuFmk1SX9S", - "object": "fee_refund", - "amount": 100, - "balance_transaction": "bt_1234", - "created": 1552807914, - "currency": "usd", - "fee": "fee_1B73DOKbnvuxQXGuhY8Aw0TN", - "metadata": {} -} -""" - - let applicationfeeString = """ -{ - "id": "fee_1B73DOKbnvuxQXGuhY8Aw0TN", - "object": "application_fee", - "account": "acct_164wxjKbnvuxQXGu", - "amount": 105, - "amount_refunded": 105, - "application": "ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7", - "balance_transaction": "txn_19XJJ02eZvKYlo2ClwuJ1rbA", - "charge": "ch_1B73DOKbnvuxQXGurbwPqzsu", - "created": 1506609734, - "currency": "gbp", - "livemode": false, - "originating_transaction": null, - "refunded": true, - "refunds": { - "object": "list", - "data": [ - { - "id": "fr_D0s7fGBKB40Twy", - "object": "fee_refund", - "amount": 138, - "balance_transaction": "txn_1CaqNg2eZvKYlo2C75cA3Euk", - "created": 1528486576, - "currency": "usd", - "fee": "fee_1B73DOKbnvuxQXGuhY8Aw0TN", - "metadata": {} - } - ], - "has_more": false, - "total_count": 1, - "url": "/v1/application_fees/fee_1B73DOKbnvuxQXGuhY8Aw0TN/refunds" - } -} -""" - - - func testApplicationFeeRefundParsesProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: applicationFeeRefundString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let refund = try decoder.decode(StripeApplicationFeeRefund.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() - - XCTAssertEqual(refund.id, "fr_1EEtTKKbnvuxQXGuFmk1SX9S") - XCTAssertEqual(refund.object, "fee_refund") - XCTAssertEqual(refund.amount, 100) - XCTAssertEqual(refund.balanceTransaction, "bt_1234") - XCTAssertEqual(refund.created, Date(timeIntervalSince1970: 1552807914)) - XCTAssertEqual(refund.currency, .usd) - XCTAssertEqual(refund.fee, "fee_1B73DOKbnvuxQXGuhY8Aw0TN") - XCTAssertEqual(refund.metadata, [:]) - } catch { - XCTFail("\(error)") - } - } - - func testApplicationFeeParsesProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: applicationfeeString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let fee = try decoder.decode(StripeApplicationFee.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() - - XCTAssertEqual(fee.id, "fee_1B73DOKbnvuxQXGuhY8Aw0TN") - XCTAssertEqual(fee.object, "application_fee") - XCTAssertEqual(fee.balanceTransaction, "txn_19XJJ02eZvKYlo2ClwuJ1rbA") - XCTAssertEqual(fee.amount, 105) - XCTAssertEqual(fee.amountRefunded, 105) - XCTAssertEqual(fee.created, Date(timeIntervalSince1970: 1506609734)) - XCTAssertEqual(fee.currency, .gbp) - XCTAssertEqual(fee.refunded, true) - XCTAssertNotNil(fee.refunds?.data) - } catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/BalanceTests.swift b/Tests/StripeTests/BalanceTests.swift deleted file mode 100644 index e9c2441..0000000 --- a/Tests/StripeTests/BalanceTests.swift +++ /dev/null @@ -1,180 +0,0 @@ -// -// BalanceTests.swift -// Stripe -// -// Created by Anthony Castelli on 4/14/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class BalanceTests: XCTestCase { - let balanceString = """ -{ - "object": "balance", - "available": [ - { - "currency": "usd", - "amount": 32147287853, - "source_types": { - "card": 32026441972, - "bank_account": 119300699 - } - }, - ], - "connect_reserved": [ - { - "currency": "eur", - "amount": 0 - }, - { - "currency": "nzd", - "amount": 0 - }, - ], - "livemode": false, - "pending": [ - { - "currency": "cad", - "amount": -21092, - "source_types": { - "card": -21092 - } - }, - { - "currency": "jpy", - "amount": 0, - "source_types": { - } - }, - { - "currency": "aud", - "amount": -33, - "source_types": { - } - }, - { - "currency": "gbp", - "amount": -81045, - "source_types": { - } - } - ] -} -""" - - func testBalanceParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: balanceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureBalance = try decoder.decode(StripeBalance.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureBalance.do { (balance) in - XCTAssertEqual(balance.object, "balance") - XCTAssertEqual(balance.livemode, false) - - // BalanceTransfer - XCTAssertEqual(balance.available?[0].currency, .usd) - XCTAssertEqual(balance.available?[0].amount, 32147287853) - XCTAssertEqual(balance.available?[0].sourceTypes?["card"], 32026441972) - // TODO: - Seeif this camel case is resolved in future versions of swift 4.1 snapshot - XCTAssertEqual(balance.available?[0].sourceTypes?["bank_account"], 119300699) - - XCTAssertEqual(balance.connectReserved?[0].currency, .eur) - XCTAssertEqual(balance.connectReserved?[0].amount, 0) - XCTAssertEqual(balance.connectReserved?[1].currency, .nzd) - XCTAssertEqual(balance.connectReserved?[1].amount, 0) - - XCTAssertEqual(balance.pending?[0].currency, .cad) - XCTAssertEqual(balance.pending?[0].amount, -21092) - XCTAssertEqual(balance.pending?[0].sourceTypes?["card"], -21092) - XCTAssertEqual(balance.pending?[1].currency, .jpy) - XCTAssertEqual(balance.pending?[1].amount, 0) - XCTAssertEqual(balance.pending?[2].currency, .aud) - XCTAssertEqual(balance.pending?[2].amount, -33) - XCTAssertEqual(balance.pending?[3].currency, .gbp) - XCTAssertEqual(balance.pending?[3].amount, -81045) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } - - let balanceTransactionString = """ -{ - "id": "txn_19XJJ02eZvKYlo2ClwuJ1rbA", - "object": "balance_transaction", - "amount": 999, - "available_on": 1483920000, - "created": 1483315442, - "currency": "usd", - "description": null, - "exchange_rate": 12.5, - "fee": 59, - "fee_details": [ - { - "amount": 59, - "application": null, - "currency": "usd", - "description": "Stripe processing fees", - "type": "stripe_fee" - } - ], - "net": 940, - "source": "ch_19XJJ02eZvKYlo2CHfSUsSpl", - "status": "pending", - "type": "charge" -} -""" - - func testBalanceTransactionParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: balanceTransactionString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureBalanceTransaction = try decoder.decode(StripeBalanceTransactionItem.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureBalanceTransaction.do { (balancetransaction) in - XCTAssertEqual(balancetransaction.id, "txn_19XJJ02eZvKYlo2ClwuJ1rbA") - XCTAssertEqual(balancetransaction.object, "balance_transaction") - XCTAssertEqual(balancetransaction.amount, 999) - XCTAssertEqual(balancetransaction.availableOn, Date(timeIntervalSince1970: 1483920000)) - XCTAssertEqual(balancetransaction.created, Date(timeIntervalSince1970: 1483315442)) - XCTAssertEqual(balancetransaction.currency, .usd) - XCTAssertEqual(balancetransaction.exchangeRate, 12.5) - XCTAssertEqual(balancetransaction.fee, 59) - XCTAssertEqual(balancetransaction.net, 940) - XCTAssertEqual(balancetransaction.source, "ch_19XJJ02eZvKYlo2CHfSUsSpl") - XCTAssertEqual(balancetransaction.status, .pending) - XCTAssertEqual(balancetransaction.type, .charge) - - // Fee - XCTAssertEqual(balancetransaction.feeDetails?[0].amount, 59) - XCTAssertEqual(balancetransaction.feeDetails?[0].currency, .usd) - XCTAssertEqual(balancetransaction.feeDetails?[0].description, "Stripe processing fees") - XCTAssertEqual(balancetransaction.feeDetails?[0].type, .stripeFee) - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/ChargeTests.swift b/Tests/StripeTests/ChargeTests.swift deleted file mode 100644 index 554b228..0000000 --- a/Tests/StripeTests/ChargeTests.swift +++ /dev/null @@ -1,133 +0,0 @@ -// -// ChargeTests.swift -// Stripe -// -// Created by Anthony Castelli on 4/16/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor -// TODO: - Implement Review tests -class ChargeTests: XCTestCase { - let chargeString = """ -{ - "id": "ch_1BrbM42eZvKYlo2CIu7qiNPF", - "object": "charge", - "amount": 999, - "amount_refunded": 0, - "application": "oops", - "application_fee": "fee_something", - "application_fee_amount": 300, - "balance_transaction": "txn_19XJJ02eZvKYlo2ClwuJ1rbA", - "captured": false, - "created": 1517704056, - "currency": "usd", - "customer": "cus_A2FVP45tySz01V", - "description": null, - "destination": null, - "dispute": null, - "failure_code": "expired_card", - "failure_message": "Your card has expired.", - "fraud_details": { - }, - "invoice": "in_1BqUzH2eZvKYlo2CV8BYZkYX", - "livemode": false, - "metadata": { - }, - "on_behalf_of": "some account", - "order": "order number", - "outcome": { - "network_status": "declined_by_network", - "reason": "expired_card", - "risk_level": "not_assessed", - "seller_message": "The bank returned the decline code `expired_card`.", - "type": "issuer_declined" - }, - "paid": false, - "payment_intent": "bop", - "receipt_email": "a@b.com", - "receipt_number": "some number", - "refunded": false, - "refunds": { - "data": [], - "total_count": 1, - "has_more": false, - "object": "list", - "url": "/v1/charges/ch_1CatgjJrybuur7n4xgpcPVuL/refunds" -}, - "review": "prv_123456", - "shipping": null, - "source": null, - "source_transfer": "sickness", - "statement_descriptor": "for a shirt", - "status": "failed", - "transfer_group": "group a", - "transfer_data": { - "amount": 45, - "destination": "acc_123" - } -} -""" - - func testChargeParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: chargeString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureCharge = try decoder.decode(StripeCharge.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureCharge.do { (charge) in - XCTAssertEqual(charge.id, "ch_1BrbM42eZvKYlo2CIu7qiNPF") - XCTAssertEqual(charge.object, "charge") - XCTAssertEqual(charge.amount, 999) - XCTAssertEqual(charge.amountRefunded, 0) - XCTAssertEqual(charge.application, "oops") - XCTAssertEqual(charge.applicationFee, "fee_something") - XCTAssertEqual(charge.applicationFeeAmount, 300) - XCTAssertEqual(charge.balanceTransaction, "txn_19XJJ02eZvKYlo2ClwuJ1rbA") - XCTAssertEqual(charge.captured, false) - XCTAssertEqual(charge.created, Date(timeIntervalSince1970: 1517704056)) - XCTAssertEqual(charge.currency, .usd) - XCTAssertEqual(charge.customer, "cus_A2FVP45tySz01V") - XCTAssertEqual(charge.failureCode, "expired_card") - XCTAssertEqual(charge.failureMessage, "Your card has expired.") - XCTAssertEqual(charge.invoice, "in_1BqUzH2eZvKYlo2CV8BYZkYX") - XCTAssertEqual(charge.livemode, false) - XCTAssertEqual(charge.onBehalfOf, "some account") - XCTAssertEqual(charge.order, "order number") - - // Outcome - XCTAssertEqual(charge.outcome?.networkStatus, .declinedByNetwork) - XCTAssertEqual(charge.outcome?.reason, "expired_card") - XCTAssertEqual(charge.outcome?.riskLevel, .notAssessed) - XCTAssertEqual(charge.outcome?.sellerMessage, "The bank returned the decline code `expired_card`.") - XCTAssertEqual(charge.outcome?.type, .issuerDeclined) - - XCTAssertEqual(charge.paid, false) - XCTAssertEqual(charge.paymentIntent, "bop") - XCTAssertEqual(charge.receiptEmail, "a@b.com") - XCTAssertEqual(charge.receiptNumber, "some number") - XCTAssertEqual(charge.refunded, false) - XCTAssertEqual(charge.review, "prv_123456") - XCTAssertEqual(charge.sourceTransfer, "sickness") - XCTAssertEqual(charge.statementDescriptor, "for a shirt") - XCTAssertEqual(charge.status, .failed) - XCTAssertEqual(charge.transferGroup, "group a") - XCTAssertEqual(charge.transferData?.amount, 45) - XCTAssertEqual(charge.transferData?.destination, "acc_123") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/CountrySpecTests.swift b/Tests/StripeTests/CountrySpecTests.swift deleted file mode 100644 index c6d9729..0000000 --- a/Tests/StripeTests/CountrySpecTests.swift +++ /dev/null @@ -1,102 +0,0 @@ -// -// CountrySpecTests.swift -// StripeTests -// -// Created by Andrew Edwards on 3/23/19. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class CountrySpecTests: XCTestCase { - let countrySpecString = """ -{ - "id": "US", - "object": "country_spec", - "default_currency": "usd", - "supported_bank_account_currencies": { - "usd": [ - "US" - ] - }, - "supported_payment_currencies": [ - "usd", - "aed", - "afn", - ], - "supported_payment_methods": [ - "card", - "stripe" - ], - "supported_transfer_countries": [ - "US" - ], - "verification_fields": { - "company": { - "additional": [ - "relationship.account_opener" - ], - "minimum": [ - "business_profile.mcc", - "business_profile.url", - "business_type", - "company.address.city", - "company.address.line1", - "company.address.postal_code", - "company.address.state", - "company.name", - "company.phone", - "company.tax_id", - "external_account", - "relationship.account_opener", - "relationship.owner", - "tos_acceptance.date", - "tos_acceptance.ip" - ] - }, - "individual": { - "additional": [ - "individual.id_number" - ], - "minimum": [ - "business_profile.mcc", - "business_profile.url", - "business_type", - "external_account", - "individual.address.city", - "individual.address.line1", - "individual.address.postal_code", - "individual.address.state", - "individual.dob.day", - "individual.dob.month", - "individual.dob.year", - "individual.email", - "individual.first_name", - "individual.last_name", - "individual.phone", - "individual.ssn_last_4", - "tos_acceptance.date", - "tos_acceptance.ip" - ] - } - } -} -""" - - func testCountrySpecParsesProperly() throws { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: countrySpecString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let spec = try decoder.decode(StripeCountrySpec.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() - - XCTAssertEqual(spec.supportedBankAccountCurrencies?["usd"], ["US"]) - XCTAssertEqual(spec.supportedPaymentCurrencies?.count, 3) - XCTAssertEqual(spec.verificationFields?.company?.additional?.count, 1) - XCTAssertEqual(spec.verificationFields?.individual?.minimum?.count, 18) - } -} diff --git a/Tests/StripeTests/CustomerTests.swift b/Tests/StripeTests/CustomerTests.swift deleted file mode 100644 index 5b720f4..0000000 --- a/Tests/StripeTests/CustomerTests.swift +++ /dev/null @@ -1,78 +0,0 @@ -// -// CustomerTests.swift -// Stripe -// -// Created by Anthony Castelli on 4/20/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class CustomerTests: XCTestCase { - let customerString = """ -{ - "id": "cus_CG7FIUH6U4JTkB", - "object": "customer", - "account_balance": 0, - "created": 1517702745, - "currency": "usd", - "default_source": "scr_123456", - "delinquent": false, - "description": "A customer", - "discount": null, - "email": "abc@xyz.com", - "livemode": false, - "metadata": { - }, - "shipping": null, - "sources": { - "has_more": false, - "object": "list", - "data": [], - "total_count": 0, - "url": "/v1/customers/cus_D3t6eeIn7f2nYi/sources" - }, - "subscriptions": { - "has_more": false, - "object": "list", - "data": [], - "total_count": 0, - "url": "/v1/customers/cus_D3t6eeIn7f2nYi/subscriptions" - } -} -""" - // TODO: Add tests for non optional values - func testCustomerParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: customerString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureCustomer = try decoder.decode(StripeCustomer.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureCustomer.do { (customer) in - XCTAssertEqual(customer.id, "cus_CG7FIUH6U4JTkB") - XCTAssertEqual(customer.object, "customer") - XCTAssertEqual(customer.accountBalance, 0) - XCTAssertEqual(customer.created, Date(timeIntervalSince1970: 1517702745)) - XCTAssertEqual(customer.currency, .usd) - XCTAssertEqual(customer.defaultSource, "scr_123456") - XCTAssertEqual(customer.delinquent, false) - XCTAssertEqual(customer.description, "A customer") - XCTAssertEqual(customer.email, "abc@xyz.com") - XCTAssertEqual(customer.livemode, false) - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/DisputeTests.swift b/Tests/StripeTests/DisputeTests.swift deleted file mode 100644 index a227c58..0000000 --- a/Tests/StripeTests/DisputeTests.swift +++ /dev/null @@ -1,132 +0,0 @@ -// -// DisputeTests.swift -// Stripe -// -// Created by Andrew Edwards on 7/12/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class DisputeTests: XCTestCase { - let disputeString = """ -{ - "amount": 1000, - "balance_transactions": [], - "charge": "ch_1BoJ2MKrZ43eBVAbDNoY8Anc", - "created": 1234567890, - "currency": "usd", - "evidence": { - "access_activity_log": "Rasengan", - "billing_address": "Rasengan", - "cancellation_policy": "Rasengan", - "cancellation_policy_disclosure": "Rasengan", - "cancellation_rebuttal": "Rasengan", - "customer_communication": "Rasengan", - "customer_email_address": "Rasengan", - "customer_name": "Rasengan", - "customer_purchase_ip": "Rasengan", - "customer_signature": "Rasengan", - "duplicate_charge_documentation": "Rasengan", - "duplicate_charge_explanation": "Rasengan", - "duplicate_charge_id": "Rasengan", - "product_description": "Rasengan", - "receipt": "Rasengan", - "refund_policy": "Rasengan", - "refund_policy_disclosure": "Rasengan", - "refund_refusal_explanation": "Rasengan", - "service_date": "Rasengan", - "service_documentation": "Rasengan", - "shipping_address": "Rasengan", - "shipping_carrier": "Rasengan", - "shipping_date": "Rasengan", - "shipping_documentation": "Rasengan", - "shipping_tracking_number": "Rasengan", - "uncategorized_file": "Rasengan", - "uncategorized_text": "Rasengan" - }, - "evidence_details": { - "due_by": 1518566399, - "has_evidence": false, - "past_due": false, - "submission_count": 0 - }, - "id": "dp_1BoJ2MKrZ43eBVAbjyK5qAWL", - "is_charge_refundable": false, - "livemode": false, - "metadata": {}, - "object": "dispute", - "reason": "general", - "status": "needs_response" -} -""" - - func testDisputeParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: disputeString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureDispute = try decoder.decode(StripeDispute.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureDispute.do { (dispute) in - XCTAssertEqual(dispute.amount, 1000) - XCTAssertEqual(dispute.charge, "ch_1BoJ2MKrZ43eBVAbDNoY8Anc") - XCTAssertEqual(dispute.created, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(dispute.currency, .usd) - XCTAssertEqual(dispute.id, "dp_1BoJ2MKrZ43eBVAbjyK5qAWL") - XCTAssertEqual(dispute.isChargeRefundable, false) - XCTAssertEqual(dispute.livemode, false) - XCTAssertEqual(dispute.object, "dispute") - XCTAssertEqual(dispute.reason, .general) - XCTAssertEqual(dispute.status, .needsResponse) - - // Evidence Datails - XCTAssertEqual(dispute.evidenceDetails?.dueBy, Date(timeIntervalSince1970: 1518566399)) - XCTAssertEqual(dispute.evidenceDetails?.hasEvidence, false) - XCTAssertEqual(dispute.evidenceDetails?.pastDue, false) - XCTAssertEqual(dispute.evidenceDetails?.submissionCount, 0) - - // Evidence - XCTAssertEqual(dispute.evidence?.accessActivityLog, "Rasengan") - XCTAssertEqual(dispute.evidence?.billingAddress, "Rasengan") - XCTAssertEqual(dispute.evidence?.cancellationPolicy, "Rasengan") - XCTAssertEqual(dispute.evidence?.cancellationPolicyDisclosure, "Rasengan") - XCTAssertEqual(dispute.evidence?.cancellationRebuttal, "Rasengan") - XCTAssertEqual(dispute.evidence?.customerCommunication, "Rasengan") - XCTAssertEqual(dispute.evidence?.customerEmailAddress, "Rasengan") - XCTAssertEqual(dispute.evidence?.customerName, "Rasengan") - XCTAssertEqual(dispute.evidence?.customerPurchaseIp, "Rasengan") - XCTAssertEqual(dispute.evidence?.customerSignature, "Rasengan") - XCTAssertEqual(dispute.evidence?.duplicateChargeDocumentation, "Rasengan") - XCTAssertEqual(dispute.evidence?.duplicateChargeExplanation, "Rasengan") - XCTAssertEqual(dispute.evidence?.duplicateChargeId, "Rasengan") - XCTAssertEqual(dispute.evidence?.productDescription, "Rasengan") - XCTAssertEqual(dispute.evidence?.receipt, "Rasengan") - XCTAssertEqual(dispute.evidence?.refundPolicy, "Rasengan") - XCTAssertEqual(dispute.evidence?.refundPolicyDisclosure, "Rasengan") - XCTAssertEqual(dispute.evidence?.refundRefusalExplanation, "Rasengan") - XCTAssertEqual(dispute.evidence?.serviceDate, "Rasengan") - XCTAssertEqual(dispute.evidence?.serviceDocumentation, "Rasengan") - XCTAssertEqual(dispute.evidence?.shippingAddress, "Rasengan") - XCTAssertEqual(dispute.evidence?.shippingCarrier, "Rasengan") - XCTAssertEqual(dispute.evidence?.shippingDate, "Rasengan") - XCTAssertEqual(dispute.evidence?.shippingDocumentation, "Rasengan") - XCTAssertEqual(dispute.evidence?.shippingTrackingNumber, "Rasengan") - XCTAssertEqual(dispute.evidence?.uncategorizedFile, "Rasengan") - XCTAssertEqual(dispute.evidence?.uncategorizedText, "Rasengan") - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/EphemeralKeyTests.swift b/Tests/StripeTests/EphemeralKeyTests.swift deleted file mode 100644 index 0cc971e..0000000 --- a/Tests/StripeTests/EphemeralKeyTests.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// EphemeralKeyTests.swift -// StripeTests -// -// Created by Andrew Edwards on 10/17/17. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class EphemeralKeyTests: XCTestCase { - let emphkeyString = """ - { - "id": "eph_123456", - "object": "ephemeral_key", - "associated_objects": [{ - "hello": "world" - }], - "created": 1234567890, - "expires": 1234567890, - "livemode": true, - "secret": "imasecret" - } -""" - - func testEphemeralKeyParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: emphkeyString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureKey = try decoder.decode(StripeEphemeralKey.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureKey.do { (key) in - XCTAssertEqual(key.id, "eph_123456") - XCTAssertEqual(key.object, "ephemeral_key") - XCTAssertEqual(key.associatedObjects?[0]["hello"], "world") - XCTAssertEqual(key.created, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(key.expires, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(key.livemode, true) - XCTAssertEqual(key.secret, "imasecret") - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/ErrorTests.swift b/Tests/StripeTests/ErrorTests.swift deleted file mode 100644 index 85173ec..0000000 --- a/Tests/StripeTests/ErrorTests.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// ErrorTests.swift -// StripeTests -// -// Created by Andrew Edwards on 2/27/18. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class ErrorTests: XCTestCase { - let errorString = """ -{ - "error": { - "type": "card_error", - "charge": "ch_12345", - "message": "Sorry kiddo", - "code": "token_already_used", - "decline_code": "stolen_card", - "param": "card_number" - } -} -""" - - func testErrorParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: errorString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureError = try decoder.decode(StripeError.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureError.do { (stripeError) in - XCTAssertEqual(stripeError.error.type, .cardError) - XCTAssertEqual(stripeError.error.charge, "ch_12345") - XCTAssertEqual(stripeError.error.message, "Sorry kiddo") - XCTAssertEqual(stripeError.error.code, .tokenAlreadyUsed) - XCTAssertEqual(stripeError.error.declineCode, .stolenCard) - XCTAssertEqual(stripeError.error.param, "card_number") - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/FileTests.swift b/Tests/StripeTests/FileTests.swift deleted file mode 100644 index 81ffa69..0000000 --- a/Tests/StripeTests/FileTests.swift +++ /dev/null @@ -1,124 +0,0 @@ -// -// FileTests.swift -// StripeTests -// -// Created by Andrew Edwards on 9/15/18. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class FileTests: XCTestCase { - let fileLinkString = """ -{ - "id": "link_1DAf602eZvKYlo2CwXzohqY4", - "object": "file_link", - "created": 1537023004, - "expired": false, - "expires_at": null, - "file": "file_1CcHwQ2eZvKYlo2CS8LDX4wK", - "livemode": false, - "metadata": { - }, - "url": "https://files.stripe.com/links/fl_test_iBHkHOhKU7YuwN7wXjKGOhcw" -} -""" - - func testFileLinkParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: fileLinkString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let fileLink = try decoder.decode(StripeFileLink.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - fileLink.do { (link) in - XCTAssertEqual(link.id, "link_1DAf602eZvKYlo2CwXzohqY4") - XCTAssertEqual(link.object, "file_link") - XCTAssertEqual(link.created, Date(timeIntervalSince1970: 1537023004)) - XCTAssertEqual(link.expired, false) - XCTAssertEqual(link.expiresAt, nil) - XCTAssertEqual(link.file, "file_1CcHwQ2eZvKYlo2CS8LDX4wK") - XCTAssertEqual(link.livemode, false) - XCTAssertEqual(link.metadata, [:]) - XCTAssertEqual(link.url, "https://files.stripe.com/links/fl_test_iBHkHOhKU7YuwN7wXjKGOhcw") - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } - - let fileUploadString = """ -{ - "id": "file_1CcHwQ2eZvKYlo2CS8LDX4wK", - "object": "file_upload", - "created": 1528830846, - "filename": "icon1.png", - "links": { - "object": "list", - "data": [ - { - "id": "link_1DAf5z2eZvKYlo2CScuVuZnv", - "object": "file_link", - "created": 1537023003, - "expired": false, - "expires_at": null, - "file": "file_1CcHwQ2eZvKYlo2CS8LDX4wK", - "livemode": false, - "metadata": { - }, - "url": "https://files.stripe.com/links/fl_test_980v1485SYKS1DVGCO5SFd7d" - } - ], - "has_more": true, - "url": "/v1/file_links?file=file_1CcHwQ2eZvKYlo2CS8LDX4wK" - }, - "purpose": "business_logo", - "size": 9676, - "type": "png", - "url": "https://files.stripe.com/files/f_test_F3TKCoF1vHGS0B5EmdyH1sUn" -} -""" - - func testFileUploadParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: fileUploadString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let fileUpload = try decoder.decode(StripeFileUpload.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - fileUpload.do { (upload) in - XCTAssertEqual(upload.id, "file_1CcHwQ2eZvKYlo2CS8LDX4wK") - XCTAssertEqual(upload.object, "file_upload") - XCTAssertEqual(upload.created, Date(timeIntervalSince1970: 1528830846)) - XCTAssertEqual(upload.filename, "icon1.png") - XCTAssertEqual(upload.purpose, .businessLogo) - XCTAssertEqual(upload.size, 9676) - XCTAssertEqual(upload.type, .png) - XCTAssertEqual(upload.url, "https://files.stripe.com/files/f_test_F3TKCoF1vHGS0B5EmdyH1sUn") - - XCTAssertEqual(upload.links?.object, "list") - XCTAssertEqual(upload.links?.hasMore, true) - XCTAssertEqual(upload.links?.url, "/v1/file_links?file=file_1CcHwQ2eZvKYlo2CS8LDX4wK") - XCTAssertEqual(upload.links?.data?.count, 1) - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/InvoiceTests.swift b/Tests/StripeTests/InvoiceTests.swift deleted file mode 100644 index 3e23b16..0000000 --- a/Tests/StripeTests/InvoiceTests.swift +++ /dev/null @@ -1,206 +0,0 @@ -// -// InvoiceTests.swift -// Stripe -// -// Created by Anthony Castelli on 9/5/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class InvoiceTests: XCTestCase { - let invoiceString = """ -{ - "amount_due": 0, - "amount_paid": 0, - "amount_remaining": 0, - "attempt_count": 0, - "attempted": false, - "auto_advance": true, - "billing": "charge_automatically", - "billing_reason": "manual", - "closed": false, - "currency": "usd", - "customer": "cus_CCiTI4Tpghl0nK", - "date": 1234567890, - "default_source": null, - "due_date": 1234567890, - "finalized_at": 1234567890, - "forgiven": false, - "hosted_invoice_url": "https://pay.stripe.com/invoice/invst_zw7Gf743ihdarScjrVuMTtctoT", - "invoice_pdf": "https://pay.stripe.com/invoice/invst_zw7Gf743ihdarScjrVuMTtctoT/pdf", - "id": "in_1BoJ2NKrZ43eBVAbQ8jb0Xfj", - "lines": { - "data": [ - { - "amount": 1000, - "currency": "usd", - "description": "My First Invoice Item (created for API docs)", - "discountable": true, - "id": "ii_1BoJ2NKrZ43eBVAby2HbDsY5", - "livemode": false, - "metadata": {}, - "object": "line_item", - "period": { - "end": 1516918659, - "start": 1516918659 - }, - "proration": false, - "type": "invoiceitem", - "quantity": 1, - "unit_amount": 2500 - } - ], - "has_more": false, - "object": "list", - "total_count": 1, - "url": "/v1/invoices/in_1BoJ2NKrZ43eBVAbQ8jb0Xfj/lines" - }, - "livemode": false, - "metadata": {}, - "next_payment_attempt": 1234567890, - "number": "fe61cc956c-0001", - "object": "invoice", - "paid": false, - "period_end": 1234567890, - "period_start": 1234567890, - "starting_balance": 0, - "status": "open", - "subtotal": 0, - "total": 0, - "webhooks_delivered_at": 1234567890 -} -""" - - func testInvoiceParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: invoiceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureInvoice = try decoder.decode(StripeInvoice.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureInvoice.do { (invoice) in - XCTAssertEqual(invoice.id, "in_1BoJ2NKrZ43eBVAbQ8jb0Xfj") - XCTAssertEqual(invoice.amountDue, 0) - XCTAssertEqual(invoice.amountPaid, 0) - XCTAssertEqual(invoice.amountRemanining, 0) - XCTAssertEqual(invoice.attemptCount, 0) - XCTAssertEqual(invoice.attempted, false) - XCTAssertEqual(invoice.autoAdvance, true) - XCTAssertEqual(invoice.billing, "charge_automatically") - XCTAssertEqual(invoice.billingReason, .manual) - XCTAssertEqual(invoice.closed, false) - XCTAssertEqual(invoice.currency, .usd) - XCTAssertEqual(invoice.customer, "cus_CCiTI4Tpghl0nK") - XCTAssertEqual(invoice.date, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(invoice.defaultSource, nil) - XCTAssertEqual(invoice.dueDate, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(invoice.finalizedAt, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(invoice.forgiven, false) - XCTAssertEqual(invoice.hostedInvoiceUrl, "https://pay.stripe.com/invoice/invst_zw7Gf743ihdarScjrVuMTtctoT") - XCTAssertEqual(invoice.invoicePdf, "https://pay.stripe.com/invoice/invst_zw7Gf743ihdarScjrVuMTtctoT/pdf") - XCTAssertEqual(invoice.livemode, false) - XCTAssertEqual(invoice.nextPaymentAttempt, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(invoice.number, "fe61cc956c-0001") - XCTAssertEqual(invoice.object, "invoice") - XCTAssertEqual(invoice.paid, false) - XCTAssertEqual(invoice.periodEnd, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(invoice.periodStart, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(invoice.startingBalance, 0) - XCTAssertEqual(invoice.status, .open) - XCTAssertEqual(invoice.subtotal, 0) - XCTAssertEqual(invoice.total, 0) - XCTAssertEqual(invoice.webhooksDeliveredAt, Date(timeIntervalSince1970: 1234567890)) - - // Test for invoice lineItem - XCTAssertEqual(invoice.lines?.hasMore, false) - XCTAssertEqual(invoice.lines?.object, "list") - XCTAssertEqual(invoice.lines?.url, "/v1/invoices/in_1BoJ2NKrZ43eBVAbQ8jb0Xfj/lines") - XCTAssertEqual(invoice.lines?.data?[0].amount, 1000) - XCTAssertEqual(invoice.lines?.data?[0].currency, .usd) - XCTAssertEqual(invoice.lines?.data?[0].description, "My First Invoice Item (created for API docs)") - XCTAssertEqual(invoice.lines?.data?[0].discountable, true) - XCTAssertEqual(invoice.lines?.data?[0].id, "ii_1BoJ2NKrZ43eBVAby2HbDsY5") - XCTAssertEqual(invoice.lines?.data?[0].livemode, false) - XCTAssertEqual(invoice.lines?.data?[0].object, "line_item") - XCTAssertEqual(invoice.lines?.data?[0].proration, false) - XCTAssertEqual(invoice.lines?.data?[0].type, "invoiceitem") - XCTAssertEqual(invoice.lines?.data?[0].period?.start, Date(timeIntervalSince1970: 1516918659)) - XCTAssertEqual(invoice.lines?.data?[0].period?.end, Date(timeIntervalSince1970: 1516918659)) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - let invoiceItemString = """ -{ - "id": "ii_1BtydB2eZvKYlo2CzeKs27EC", - "object": "invoiceitem", - "amount": 2500, - "currency": "usd", - "customer": "cus_CIaBoYfVixDHWf", - "date": 1518270185, - "description": "One-time setup fee", - "discountable": true, - "invoice": "in_1BtydF2eZvKYlo2COZpiUqSi", - "livemode": false, - "metadata": { - }, - "period": { - "start": 1518270185, - "end": 1518270185 - }, - "plan": null, - "proration": false, - "quantity": null, - "subscription": null, - "unit_amount": 2500 -} -""" - - func testInvoiceItemParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: invoiceItemString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureInvoiceItem = try decoder.decode(StripeInvoiceItem.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureInvoiceItem.do { (invoiceItem) in - XCTAssertEqual(invoiceItem.id, "ii_1BtydB2eZvKYlo2CzeKs27EC") - XCTAssertEqual(invoiceItem.object, "invoiceitem") - XCTAssertEqual(invoiceItem.amount, 2500) - XCTAssertEqual(invoiceItem.currency, .usd) - XCTAssertEqual(invoiceItem.customer, "cus_CIaBoYfVixDHWf") - XCTAssertEqual(invoiceItem.date, Date(timeIntervalSince1970: 1518270185)) - XCTAssertEqual(invoiceItem.description, "One-time setup fee") - XCTAssertEqual(invoiceItem.discountable, true) - XCTAssertEqual(invoiceItem.invoice, "in_1BtydF2eZvKYlo2COZpiUqSi") - XCTAssertEqual(invoiceItem.livemode, false) - XCTAssertEqual(invoiceItem.proration, false) - XCTAssertEqual(invoiceItem.quantity, nil) - XCTAssertEqual(invoiceItem.subscription, nil) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/OrderTests.swift b/Tests/StripeTests/OrderTests.swift deleted file mode 100644 index 1b1ef4f..0000000 --- a/Tests/StripeTests/OrderTests.swift +++ /dev/null @@ -1,160 +0,0 @@ -// -// OrderTests.swift -// Stripe -// -// Created by Andrew Edwards on 8/23/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class OrderTests: XCTestCase { - let orderString = """ -{ - "amount": 1500, - "created": 1234567890, - "currency": "usd", - "id": "or_1BoJ2NKrZ43eBVAbFf4SZyvD", - "items": [ - { - "amount": 1500, - "currency": "usd", - "description": "Gold Special", - "object": "order_item", - "parent": "sk_1BoJ2KKrZ43eBVAbu7ioKR0i", - "quantity": null, - "type": "sku" - } - ], - "livemode": false, - "metadata": { - "hello": "world" - }, - "object": "order", - "returns": { - "data": [ - { - "amount": 1500, - "created": 1234567890, - "currency": "usd", - "id": "orret_1BoJ2NKrZ43eBVAb8r8dx0GO", - "items": [ - { - "amount": 1500, - "currency": "usd", - "description": "Gold Special", - "object": "order_item", - "parent": "sk_1BoJ2NKrZ43eBVAb4RD4HHuH", - "quantity": null, - "type": "sku" - } - ], - "livemode": false, - "object": "order_return", - "order": "or_1BoJ2NKrZ43eBVAbSnN443id", - "refund": "re_1BoJ2NKrZ43eBVAbop3rb4h1" - } - ], - "has_more": false, - "object": "list", - "total_count": 1, - "url": "/v1/order_returns?order=or_1BoJ2NKrZ43eBVAbFf4SZyvD" - }, - "shipping": { - "address": { - "city": "Anytown", - "country": "US", - "line1": "1234 Main street", - "line2": "suite 123", - "postal_code": "123456", - "state": "AL" - }, - "carrier": "UPS", - "name": "Jenny Rosen", - "phone": null, - "tracking_number": null - }, - "shipping_methods": [], - "status": "created", - "status_transitions": { - "canceled": 1515290550, - "fulfiled": 1507690550, - "paid": 1517688550, - "returned": 1927690550 - }, - "updated": 1234567890 -} -""" - - func testOrderIsProperlyParsed() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: orderString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureOrder = try decoder.decode(StripeOrder.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureOrder.do { (order) in - XCTAssertEqual(order.id, "or_1BoJ2NKrZ43eBVAbFf4SZyvD") - XCTAssertEqual(order.amount, 1500) - XCTAssertEqual(order.created, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(order.currency, .usd) - XCTAssertEqual(order.livemode, false) - XCTAssertEqual(order.metadata["hello"], "world") - XCTAssertEqual(order.object, "order") - XCTAssertEqual(order.status, .created) - - // This test covers the Order Item object - XCTAssertEqual(order.statusTransitions?.canceled, Date(timeIntervalSince1970: 1515290550)) - XCTAssertEqual(order.statusTransitions?.fulfiled, Date(timeIntervalSince1970: 1507690550)) - XCTAssertEqual(order.statusTransitions?.paid, Date(timeIntervalSince1970: 1517688550)) - XCTAssertEqual(order.statusTransitions?.returned, Date(timeIntervalSince1970: 1927690550)) - XCTAssertEqual(order.updated, Date(timeIntervalSince1970: 1234567890)) - - XCTAssertEqual(order.items?[0].amount, 1500) - XCTAssertEqual(order.items?[0].currency, .usd) - XCTAssertEqual(order.items?[0].description, "Gold Special") - XCTAssertEqual(order.items?[0].object, "order_item") - XCTAssertEqual(order.items?[0].parent, "sk_1BoJ2KKrZ43eBVAbu7ioKR0i") - XCTAssertEqual(order.items?[0].quantity, nil) - XCTAssertEqual(order.items?[0].type, .sku) - - XCTAssertEqual(order.returns?.hasMore, false) - XCTAssertEqual(order.returns?.object, "list") - XCTAssertEqual(order.returns?.url, "/v1/order_returns?order=or_1BoJ2NKrZ43eBVAbFf4SZyvD") - - // This test covers the OrderItem Return object - XCTAssertEqual(order.returns?.data?[0].amount, 1500) - XCTAssertEqual(order.returns?.data?[0].created, Date(timeIntervalSince1970: 1234567890)) - XCTAssertEqual(order.returns?.data?[0].currency, .usd) - XCTAssertEqual(order.returns?.data?[0].id, "orret_1BoJ2NKrZ43eBVAb8r8dx0GO") - XCTAssertEqual(order.returns?.data?[0].livemode, false) - XCTAssertEqual(order.returns?.data?[0].object, "order_return") - XCTAssertEqual(order.returns?.data?[0].order, "or_1BoJ2NKrZ43eBVAbSnN443id") - XCTAssertEqual(order.returns?.data?[0].refund, "re_1BoJ2NKrZ43eBVAbop3rb4h1") - - XCTAssertEqual(order.shipping?.address?.city, "Anytown") - XCTAssertEqual(order.shipping?.address?.country, "US") - XCTAssertEqual(order.shipping?.address?.line1, "1234 Main street") - XCTAssertEqual(order.shipping?.address?.line2, "suite 123") - XCTAssertEqual(order.shipping?.address?.postalCode, "123456") - XCTAssertEqual(order.shipping?.address?.state, "AL") - XCTAssertEqual(order.shipping?.carrier, "UPS") - XCTAssertEqual(order.shipping?.name, "Jenny Rosen") - XCTAssertEqual(order.shipping?.phone, nil) - XCTAssertEqual(order.shipping?.trackingNumber, nil) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/PaymentSourceTests.swift b/Tests/StripeTests/PaymentSourceTests.swift deleted file mode 100644 index 09b4c25..0000000 --- a/Tests/StripeTests/PaymentSourceTests.swift +++ /dev/null @@ -1,145 +0,0 @@ -// -// PaymentSourceTests.swift -// Stripe -// -// Created by Nicolas Bachschmidt on 2018-08-09. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class PaymentSourceTests: XCTestCase { - let sourceListString = """ -{ - "object": "list", - "total_count": 3, - "data": [ - { - "id": "card_1Cs8z3GaLcnLeFWiU9SDCez8", - "object": "card", - "address_city": null, - "address_country": null, - "address_line1": null, - "address_line1_check": null, - "address_line2": null, - "address_state": null, - "address_zip": null, - "address_zip_check": null, - "brand": "Visa", - "country": "FR", - "customer": "cus_D3t6eeIn7f2nYi", - "cvc_check": "pass", - "dynamic_last4": null, - "exp_month": 12, - "exp_year": 2029, - "fingerprint": "GhnGuMVuycvktkHE", - "funding": "credit", - "last4": "0003", - "metadata": { - }, - "name": null, - "tokenization_method": null, - "type": "Visa" - }, - { - "id": "src_1CxF9xGaLcnLeFWif1vfiSkS", - "object": "source", - "ach_credit_transfer": { - "account_number": "test_49b8d100bde6", - "bank_name": "TEST BANK", - "fingerprint": "0W7zV79lnzu4L4Ie", - "routing_number": "110000000", - "swift_code": "TSTEZ122" - }, - "amount": null, - "client_secret": "src_client_secret_DO1CKYXtHAFzKMNPY4Fsi7d9", - "created": 1533825041, - "currency": "usd", - "flow": "receiver", - "livemode": false, - "metadata": { - }, - "owner": { - "address": null, - "email": "jenny.rosen@example.com", - "name": null, - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": null, - "verified_phone": null - }, - "receiver": { - "address": "110000000-test_49b8d100bde6", - "amount_charged": 0, - "amount_received": 1000, - "amount_returned": 0, - "refund_attributes_method": "email", - "refund_attributes_status": "missing" - }, - "statement_descriptor": null, - "status": "chargeable", - "type": "ach_credit_transfer", - "usage": "reusable" - }, - { - "id": "ba_1CxEzUGaLcnLeFWiz0fJrOVm", - "object": "bank_account", - "account_holder_name": "", - "account_holder_type": "individual", - "bank_name": "STRIPE TEST BANK", - "country": "US", - "currency": "usd", - "customer": "cus_D3t6eeIn7f2nYi", - "disabled": false, - "fingerprint": "xrXW6SzxS6Gjr4d7", - "last4": "6789", - "metadata": { - }, - "name": "", - "routing_number": "110000000", - "status": "new", - "validated": false, - "verified": false - } - ], - "has_more": false, - "url": "/v1/customers/cus_D3t6eeIn7f2nYi/sources" -} -""" - - func testSourceListIsProperlyParsed() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: sourceListString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureOrder = try decoder.decode(StripeSourcesList.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureOrder.do { list in - XCTAssertEqual(list.object, "list") - XCTAssertEqual(list.hasMore, false) - XCTAssertEqual(list.data?.count, 3) - XCTAssertEqual(list.bankAccounts?.count, 1) - XCTAssertEqual(list.cards?.count, 1) - XCTAssertEqual(list.sources?.count, 1) - XCTAssertEqual(list.data?.map { $0.id }, [ - "card_1Cs8z3GaLcnLeFWiU9SDCez8", - "src_1CxF9xGaLcnLeFWif1vfiSkS", - "ba_1CxEzUGaLcnLeFWiz0fJrOVm", - ]) - XCTAssertEqual(list.data?.map { $0.object }, ["card", "source", "bank_account"]) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/PayoutTests.swift b/Tests/StripeTests/PayoutTests.swift deleted file mode 100644 index e29221f..0000000 --- a/Tests/StripeTests/PayoutTests.swift +++ /dev/null @@ -1,73 +0,0 @@ -// -// PayoutTests.swift -// StripeTests -// -// Created by Andrew Edwards on 8/21/18. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class PayoutTests: XCTestCase { - let payoutString = """ -{ - "id": "po_1D1MTmAU9AiAmxbB7b7ip35l", - "object": "payout", - "amount": 1100, - "arrival_date": 1534806490, - "automatic": true, - "balance_transaction": "txn_1CSGjlAU9AiAmxbBWLHOEEsM", - "created": 1534806490, - "currency": "usd", - "description": "STRIPE PAYOUT", - "destination": "ba_1D1MTmAU9AiAmxbBTLh21RGt", - "failure_balance_transaction": null, - "failure_code": "invalid_account_number", - "failure_message": "sorry kiddo", - "livemode": false, - "metadata": { - }, - "method": "instant", - "source_type": "card", - "statement_descriptor": null, - "status": "in_transit", - "type": "bank_account" -} -""" - func testPayoutsParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: payoutString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let payout = try decoder.decode(StripePayout.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() - - XCTAssertEqual(payout.id, "po_1D1MTmAU9AiAmxbB7b7ip35l") - XCTAssertEqual(payout.object, "payout") - XCTAssertEqual(payout.amount, 1100) - XCTAssertEqual(payout.arrivalDate, Date(timeIntervalSince1970: 1534806490)) - XCTAssertEqual(payout.automatic, true) - XCTAssertEqual(payout.balanceTransaction, "txn_1CSGjlAU9AiAmxbBWLHOEEsM") - XCTAssertEqual(payout.created, Date(timeIntervalSince1970: 1534806490)) - XCTAssertEqual(payout.currency, .usd) - XCTAssertEqual(payout.description, "STRIPE PAYOUT") - XCTAssertEqual(payout.failureBalanceTransaction, nil) - XCTAssertEqual(payout.failureCode, .invalidAccountNumber) - XCTAssertEqual(payout.failureMessage, "sorry kiddo") - XCTAssertEqual(payout.livemode, false) - XCTAssertEqual(payout.metadata, [:]) - XCTAssertEqual(payout.method, .instant) - XCTAssertEqual(payout.sourceType, .card) - XCTAssertEqual(payout.statementDescriptor, nil) - XCTAssertEqual(payout.status, .inTransit) - XCTAssertEqual(payout.type, .bankAccount) - - } catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/ProductTests.swift b/Tests/StripeTests/ProductTests.swift deleted file mode 100644 index 2957f7c..0000000 --- a/Tests/StripeTests/ProductTests.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// ProductTests.swift -// Stripe -// -// Created by Andrew Edwards on 8/25/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class ProductTests: XCTestCase { - let productString = """ - { - "id": "prod_BosWT9EsdzgjPn", - "object": "product", - "active": false, - "attributes": [ - "size", - "gender" - ], - "caption": "test", - "created": 1511420673, - "deactivate_on": [ - - ], - "description": "Comfortable cotton t-shirt", - "images": [ - - ], - "livemode": false, - "metadata": { - }, - "name": "T-shirt", - "package_dimensions": { - "height": 1.25, - "length": 2.44, - "weight": 3.0, - "width": 4.0 - }, - "shippable": false, - "updated": 1511422435, - "type": "good", - "url": "https://api.stripe.com/" - } -""" - - func testProductParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: productString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureProduct = try decoder.decode(StripeProduct.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureProduct.do { (product) in - XCTAssertEqual(product.id, "prod_BosWT9EsdzgjPn") - XCTAssertEqual(product.object, "product") - XCTAssertEqual(product.active, false) - XCTAssertEqual(product.attributes, ["size", "gender"]) - XCTAssertEqual(product.caption, "test") - XCTAssertEqual(product.created, Date(timeIntervalSince1970: 1511420673)) - XCTAssertEqual(product.deactivateOn, []) - XCTAssertEqual(product.description, "Comfortable cotton t-shirt") - XCTAssertEqual(product.images, []) - XCTAssertEqual(product.livemode, false) - XCTAssertEqual(product.metadata, [:]) - XCTAssertEqual(product.name, "T-shirt") - XCTAssertEqual(product.packageDimensions?.height, 1.25) - XCTAssertEqual(product.packageDimensions?.length, 2.44) - XCTAssertEqual(product.packageDimensions?.weight, 3.0) - XCTAssertEqual(product.packageDimensions?.width, 4.0) - XCTAssertEqual(product.shippable, false) - XCTAssertEqual(product.updated, Date(timeIntervalSince1970: 1511422435)) - XCTAssertEqual(product.url, "https://api.stripe.com/") - XCTAssertEqual(product.type, .good) - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/ProviderTests.swift b/Tests/StripeTests/ProviderTests.swift deleted file mode 100644 index f5f7428..0000000 --- a/Tests/StripeTests/ProviderTests.swift +++ /dev/null @@ -1 +0,0 @@ -// TODO: - Implement diff --git a/Tests/StripeTests/QueryEncodingTests.swift b/Tests/StripeTests/QueryEncodingTests.swift deleted file mode 100644 index 7f5de46..0000000 --- a/Tests/StripeTests/QueryEncodingTests.swift +++ /dev/null @@ -1,26 +0,0 @@ -import XCTest -@testable import Stripe - -class QueryEncodingTests: XCTestCase { - - func testSimpleQueryEncodedProperly() throws { - let query = [ - "email": "accounting+furnitures@hmm.test" - ] - XCTAssertEqual(query.queryParameters, "email=accounting%2Bfurnitures@hmm.test") - } - - func testNestedDictionaryQueryEncodedProperly() throws { - let query: [String: Any] = [ - "shipping": ["name": "Hamlin, Hamlin & McGill"] - ] - XCTAssertEqual(query.queryParameters, "shipping[name]=Hamlin,%20Hamlin%20%26%20McGill") - } - - func testNestedArrayQueryEncodedProperly() throws { - let query: [String: Any] = [ - "items": [["plan": "plan_b"], ["plan": "plan_nine"]] - ] - XCTAssertEqual(query.queryParameters, "items[0][plan]=plan_b&items[1][plan]=plan_nine") - } -} diff --git a/Tests/StripeTests/RefundTests.swift b/Tests/StripeTests/RefundTests.swift deleted file mode 100644 index baf3572..0000000 --- a/Tests/StripeTests/RefundTests.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// RefundTests.swift -// Stripe -// -// Created by Anthony Castelli on 5/13/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class RefundTests: XCTestCase { - let refundString = """ -{ - "id": "re_1BrXqE2eZvKYlo2Cfa7NO6GF", - "object": "refund", - "amount": 1000, - "balance_transaction": "txn_1BrXqE2eZvKYlo2CyAuEMg17", - "charge": "ch_1BrXqD2eZvKYlo2Ce1sYPCDd", - "created": 1517690550, - "currency": "usd", - "metadata": { - "hello": "world" - }, - "reason": "requested_by_customer", - "receipt_number": "23760348", - "status": "succeeded" -} -""" - - func testRefundParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: refundString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureRefund = try decoder.decode(StripeRefund.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureRefund.do { (refund) in - XCTAssertEqual(refund.id, "re_1BrXqE2eZvKYlo2Cfa7NO6GF") - XCTAssertEqual(refund.object, "refund") - XCTAssertEqual(refund.amount, 1000) - XCTAssertEqual(refund.balanceTransaction, "txn_1BrXqE2eZvKYlo2CyAuEMg17") - XCTAssertEqual(refund.charge, "ch_1BrXqD2eZvKYlo2Ce1sYPCDd") - XCTAssertEqual(refund.created, Date(timeIntervalSince1970: 1517690550)) - XCTAssertEqual(refund.currency, .usd) - XCTAssertEqual(refund.metadata["hello"], "world") - XCTAssertEqual(refund.reason, .requestedByCustomer) - XCTAssertEqual(refund.receiptNumber, "23760348") - XCTAssertEqual(refund.status, .succeeded) - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/SKUTests.swift b/Tests/StripeTests/SKUTests.swift deleted file mode 100644 index db7eae7..0000000 --- a/Tests/StripeTests/SKUTests.swift +++ /dev/null @@ -1,89 +0,0 @@ -// -// SKUTests.swift -// Stripe -// -// Created by Andrew Edwards on 8/22/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class SKUTests: XCTestCase { - let skuString = """ -{ - "id": "sku_CG2zw7j7H8NEQq", - "object": "sku", - "active": true, - "attributes": { - "size": "Medium", - "gender": "Unisex" - }, - "created": 1517686889, - "currency": "usd", - "image": "https://www.example.com", - "inventory": { - "quantity": 499, - "type": "finite", - "value": "in_stock" }, - "metadata": { - "hello": "world" - }, - "package_dimensions": { - "height": 12.3, - "length": 13.3, - "weight": 14.3, - "width": 15.3 - }, - "price": 1500, - "livemode": false, - "product": "prod_BosWT9EsdzgjPn", - "updated": 1517686906 -} -""" - - func testSkuParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: skuString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let futureSku = try decoder.decode(StripeSKU.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - futureSku.do { (sku) in - XCTAssertEqual(sku.id, "sku_CG2zw7j7H8NEQq") - XCTAssertEqual(sku.object, "sku") - XCTAssertEqual(sku.active, true) - XCTAssertEqual(sku.attributes?["size"], "Medium") - XCTAssertEqual(sku.attributes?["gender"], "Unisex") - XCTAssertEqual(sku.created, Date(timeIntervalSince1970: 1517686889)) - XCTAssertEqual(sku.currency, .usd) - XCTAssertEqual(sku.image, "https://www.example.com") - XCTAssertEqual(sku.livemode, false) - XCTAssertEqual(sku.metadata["hello"], "world") - XCTAssertEqual(sku.price, 1500) - XCTAssertEqual(sku.product, "prod_BosWT9EsdzgjPn") - XCTAssertEqual(sku.updated, Date(timeIntervalSince1970: 1517686906)) - - XCTAssertEqual(sku.packageDimensions?.height, 12.3) - XCTAssertEqual(sku.packageDimensions?.length, 13.3) - XCTAssertEqual(sku.packageDimensions?.weight, 14.3) - XCTAssertEqual(sku.packageDimensions?.width, 15.3) - - XCTAssertEqual(sku.inventory?.quantity, 499) - XCTAssertEqual(sku.inventory?.type, .finite) - XCTAssertEqual(sku.inventory?.value, .inStock) - - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/SourceTests.swift b/Tests/StripeTests/SourceTests.swift deleted file mode 100644 index c4f7342..0000000 --- a/Tests/StripeTests/SourceTests.swift +++ /dev/null @@ -1,814 +0,0 @@ -// -// SourceTests.swift -// Stripe -// -// Created by Andrew Edwards on 6/2/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class SourceTests: XCTestCase { - let decoder = JSONDecoder() - - override func setUp() { - decoder.dateDecodingStrategy = .secondsSince1970 - } - - let cardSourceString = """ - { - "id": "src_1AhIN74iJb0CbkEwmbRYPsd4", - "object": "source", - "amount": 20, - "client_secret": null, - "created": 1500471469, - "currency": "usd", - "flow": "redirect", - "livemode": false, - "metadata": { - "hello": "world" - }, - "owner": { - "address": { - "city": "Berlin", - "country": "DE", - "line1": "Nollendorfstraße 27", - "line2": null, - "postal_code": "10777", - "state": null - }, - "email": "jenny.rosen@example.com", - "name": "Jenny Rosen", - "phone": "1234567", - "verified_address": null, - "verified_email": null, - "verified_name": null, - "verified_phone": null - }, -"receiver": { - "address": "121042882-38381234567890123", - "amount_charged": 10, - "amount_received": 101, - "amount_returned": 110, - "refund_attributes_method": "email", - "refund_attributes_status": "missing" - }, -"redirect": { - "failure_reason": "declined", - "return_url": "https://www.google.com", - "status": "pending", - "url": "https://www.apple.com" - }, -"status": "chargeable", -"type": "card", -"usage": "reusable", -"card": { - "funding": "credit", - "exp_month": 6, - "country": "US", - "three_d_secure": "optional", - "fingerprint": "6iB9myGBwx04f4XT", - "last4": "4242", - "brand": "Visa", - "exp_year": 2019 - } -} -""" - - func testCardSourceParsedProperly() throws { - do { - let body = HTTPBody(string: cardSourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.giropay) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.ideal) - XCTAssertNil(source.sofort) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.alipay) - XCTAssertNil(source.p24) - XCTAssertNil(source.achCreditTransfer) - - // Cards have already been tested in the token tests. - XCTAssertNotNil(source.card) - - XCTAssertEqual(source.id, "src_1AhIN74iJb0CbkEwmbRYPsd4") - XCTAssertEqual(source.object, "source") - XCTAssertEqual(source.amount, 20) - XCTAssertEqual(source.clientSecret, nil) - XCTAssertEqual(source.created, Date(timeIntervalSince1970: 1500471469)) - XCTAssertEqual(source.currency, .usd) - XCTAssertEqual(source.flow, Flow.redirect) - XCTAssertEqual(source.livemode, false) - XCTAssertEqual(source.metadata["hello"], "world") - XCTAssertEqual(source.status, .chargeable) - XCTAssertEqual(source.type, .card) - XCTAssertEqual(source.usage, "reusable") - - // This tests covers the owner object - XCTAssertNotNil(source.owner) - XCTAssertEqual(source.owner?.address?.city, "Berlin") - XCTAssertEqual(source.owner?.address?.country, "DE") - XCTAssertEqual(source.owner?.address?.line1, "Nollendorfstraße 27") - XCTAssertEqual(source.owner?.address?.line2, nil) - XCTAssertEqual(source.owner?.address?.postalCode, "10777") - XCTAssertEqual(source.owner?.address?.state, nil) - XCTAssertEqual(source.owner?.email, "jenny.rosen@example.com") - XCTAssertEqual(source.owner?.name, "Jenny Rosen") - XCTAssertEqual(source.owner?.phone, "1234567") - XCTAssertEqual(source.owner?.verifiedEmail, nil) - XCTAssertEqual(source.owner?.verifiedName, nil) - XCTAssertEqual(source.owner?.verifiedPhone, nil) - - // This tests covers the receiver object - XCTAssertNotNil(source.receiver) - XCTAssertEqual(source.receiver?.address, "121042882-38381234567890123") - XCTAssertEqual(source.receiver?.amountCharged, 10) - XCTAssertEqual(source.receiver?.amountReceived, 101) - XCTAssertEqual(source.receiver?.amountReturned, 110) - XCTAssertEqual(source.receiver?.refundAttributesMethod, "email") - XCTAssertEqual(source.receiver?.refundAttributesStatus, "missing") - - // This tests covers the redirect object - XCTAssertNotNil(source.redirect) - XCTAssertEqual(source.redirect?.failureReason, "declined") - XCTAssertEqual(source.redirect?.returnUrl, "https://www.google.com") - XCTAssertEqual(source.redirect?.status, "pending") - XCTAssertEqual(source.redirect?.url, "https://www.apple.com") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - let threeDSecureSourceString = """ - { - "id": "src_19YlvWAHEMiOZZp1QQlOD79v", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_kBwCSm6Xz5MQETiJ43hUH8qv", - "created": 1483663790, - "currency": "eur", - "flow": "redirect", - "livemode": false, - "metadata": {}, - "owner": { - "address": null, - "email": null, - "name": null, - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": null, - "verified_phone": null - }, - "redirect": { - "return_url": "https://shop.example.com/crtA6B28E1", - "status": "pending", - "url": "https://hooks.stripe.com/redirect/authenticate/src_19YlvWAHEMiOZZp1QQlOD79v?client_secret=src_client_secret_kBwCSm6Xz5MQETiJ43hUH8qv" - }, - "status": "pending", - "type": "three_d_secure", - "usage": "single_use", - "three_d_secure": { - "card": "src_19YP2AAHEMiOZZp1Di4rt1K6", - "customer": null, - "authenticated": false - } - } -""" - - func testThreeDSecureSourceParsedProperly() throws { - do { - let body = HTTPBody(string: threeDSecureSourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.giropay) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.ideal) - XCTAssertNil(source.sofort) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.alipay) - XCTAssertNil(source.p24) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.threeDSecure) - XCTAssertEqual(source.threeDSecure?.card, "src_19YP2AAHEMiOZZp1Di4rt1K6") - XCTAssertEqual(source.threeDSecure?.customer, nil) - XCTAssertEqual(source.threeDSecure?.authenticated, false) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - let sepaDebitSourceString = """ -{ - "id": "src_18HgGjHNCLa1Vra6Y9TIP6tU", - "object": "source", - "amount": null, - "client_secret": "src_client_secret_XcBmS94nTg5o0xc9MSliSlDW", - "created": 1464803577, - "currency": "eur", - "flow": "none", - "metadata": {}, - "livemode": false, - "owner": { - "address": null, - "email": null, - "name": "Jenny Rosen", - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": null, - "verified_phone": null - }, - "status": "chargeable", - "type": "sepa_debit", - "usage": "reusable", - "sepa_debit": { - "bank_code": "37040044", - "country": "DE", - "fingerprint": "NxdSyRegc9PsMkWy", - "last4": "3001", - "mandate_reference": "NXDSYREGC9PSMKWY", - "mandate_url": "https://hooks.stripe.com/adapter/sepa_debit/file/src_18HgGjHNCLa1Vra6Y9TIP6tU/src_client_secret_XcBmS94nTg5o0xc9MSliSlDW" - } -} -""" - - func testSepaDebitSourceParsedProperly() throws { - do { - let body = HTTPBody(string: sepaDebitSourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.giropay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.ideal) - XCTAssertNil(source.sofort) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.alipay) - XCTAssertNil(source.p24) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.sepaDebit) - XCTAssertEqual(source.sepaDebit?.bankCode, "37040044") - XCTAssertEqual(source.sepaDebit?.country, "DE") - XCTAssertEqual(source.sepaDebit?.fingerprint, "NxdSyRegc9PsMkWy") - XCTAssertEqual(source.sepaDebit?.last4, "3001") - XCTAssertEqual(source.sepaDebit?.mandateReference, "NXDSYREGC9PSMKWY") - XCTAssertEqual(source.sepaDebit?.mandateUrl, "https://hooks.stripe.com/adapter/sepa_debit/file/src_18HgGjHNCLa1Vra6Y9TIP6tU/src_client_secret_XcBmS94nTg5o0xc9MSliSlDW") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - let alipaySourceString = """ -{ - "id": "src_16xhynE8WzK49JbAs9M21jaR", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU", - "created": 1445277809, - "currency": "usd", - "flow": "redirect", - "metadata": {}, - "livemode": true, - "owner": { - "address": null, - "email": null, - "name": "null", - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": "null", - "verified_phone": null - }, - "redirect": { - "return_url": "https://shop.example.com/crtA6B28E1", - "status": "pending", - "url": "https://pay.stripe.com/redirect/src_16xhynE8WzK49JbAs9M21jaR?client_secret=src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU" - }, - "statement_descriptor": null, - "status": "pending", - "type": "alipay", - "usage": "single_use", - "alipay": { - "statement_descriptor": "Veggies are healthy", - "native_url": "https://www.vapor.codes" - } -} -""" - - func testAlipaySourceParsedProperly() throws { - do { - let body = HTTPBody(string: alipaySourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.giropay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.ideal) - XCTAssertNil(source.sofort) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.p24) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.alipay) - XCTAssertEqual(source.alipay?.statementDescriptor, "Veggies are healthy") - XCTAssertEqual(source.alipay?.nativeUrl, "https://www.vapor.codes") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - - let giroPaySourceString = """ -{ - "id": "src_16xhynE8WzK49JbAs9M21jaR", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU", - "created": 1445277809, - "currency": "eur", - "flow": "redirect", - "metadata": {}, - "livemode": true, - "owner": { - "address": null, - "email": null, - "name": null, - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": "Jenny Rosen", - "verified_phone": null - }, - "redirect": { - "return_url": "https://shop.example.com/crtA6B28E1", - "status": "pending", - "url": "https://pay.stripe.com/redirect/src_16xhynE8WzK49JbAs9M21jaR?client_secret=src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU" - }, - "statement_descriptor": null, - "status": "pending", - "type": "giropay", - "usage": "single_use", - "giropay": { - "bank_code": "76547382", - "bic": "No idea what this is", - "bank_name": "Vapor Bank", - "statement_descriptor": "Buy more Vapor Cloud" - } -} -""" - - func testGiropaySourceParsedProperly() throws { - do { - let body = HTTPBody(string: giroPaySourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.alipay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.ideal) - XCTAssertNil(source.sofort) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.p24) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.giropay) - XCTAssertEqual(source.giropay?.bankCode, "76547382") - XCTAssertEqual(source.giropay?.bic, "No idea what this is") - XCTAssertEqual(source.giropay?.bankName, "Vapor Bank") - XCTAssertEqual(source.giropay?.statementDescriptor, "Buy more Vapor Cloud") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - - let idealSourceString = """ -{ - "id": "src_16xhynE8WzK49JbAs9M21jaR", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU", - "created": 1445277809, - "currency": "eur", - "flow": "redirect", - "metadata": {}, - "livemode": true, - "owner": { - "address": null, - "email": null, - "name": "Jenny Rosen", - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": "Jenny Rosen", - "verified_phone": null - }, - "redirect": { - "return_url": "https://shop.example.com/crtA6B28E1", - "status": "pending", - "url": "https://pay.stripe.com/redirect/src_16xhynE8WzK49JbAs9M21jaR?client_secret=src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU" - }, - "statement_descriptor": null, - "status": "pending", - "type": "ideal", - "usage": "single_use", - "ideal": { - "bank": "Vapor Bank", - "bic": "who knows", - "iban_last4": "1234", - "statement_descriptor": "Buy more Vapor Cloud" - } -} -""" - - func testIdealSourceParsedProperly() throws { - do { - let body = HTTPBody(string: idealSourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.alipay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.giropay) - XCTAssertNil(source.sofort) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.p24) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.ideal) - XCTAssertEqual(source.ideal?.bank, "Vapor Bank") - XCTAssertEqual(source.ideal?.bic, "who knows") - XCTAssertEqual(source.ideal?.ibanLast4, "1234") - XCTAssertEqual(source.ideal?.statementDescriptor, "Buy more Vapor Cloud") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - - let p24SourceString = """ -{ - "id": "src_16xhynE8WzK49JbAs9M21jaR", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU", - "created": 1445277809, - "currency": "eur", - "flow": "redirect", - "metadata": {}, - "livemode": true, - "owner": { - "address": null, - "email": "jenny.rosen@example.com", - "name": "Jenny Rosen", - "phone": null, - "verified_address": null, - "verified_email": "jenny.rosen@example.com", - "verified_name": "Jenny Rosen", - "verified_phone": null - }, - "redirect": { - "return_url": "https://shop.example.com/crtA6B28E1", - "status": "pending", - "url": "https://pay.stripe.com/redirect/src_16xhynE8WzK49JbAs9M21jaR?client_secret=src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU" - }, - "statement_descriptor": null, - "status": "pending", - "type": "p24", - "usage": "single_use", - "p24": { - "reference": "P24-000-111-222" - } -} -""" - - func testP24SourceParsedProperly() throws { - do { - let body = HTTPBody(string: p24SourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.alipay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.giropay) - XCTAssertNil(source.sofort) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.ideal) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.p24) - XCTAssertEqual(source.p24?.reference, "P24-000-111-222") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - - let sofortSourceString = """ -{ - "id": "src_16xhynE8WzK49JbAs9M21jaR", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU", - "created": 1445277809, - "currency": "eur", - "flow": "redirect", - "metadata": {}, - "livemode": true, - "owner": { - "address": null, - "email": null, - "name": "Jenny Rosen", - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": "Jenny Rosen", - "verified_phone": null - }, - "redirect": { - "return_url": "https://shop.example.com/crtA6B28E1", - "status": "pending", - "url": "https://pay.stripe.com/redirect/src_16xhynE8WzK49JbAs9M21jaR?client_secret=src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU" - }, - "statement_descriptor": null, - "status": "pending", - "type": "sofort", - "usage": "single_use", - "sofort": { - "country": "DE", - "bank_code": "34569", - "bic": "Meh", - "bank_name": "Vapor Bank", - "iban_last4": "4560", - "preferred_language": "English", - "statement_descriptor": "Henlo friend" - } -} -""" - - func testSofortSourceParsedProperly() throws { - do { - let body = HTTPBody(string: sofortSourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.alipay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.giropay) - XCTAssertNil(source.p24) - XCTAssertNil(source.bancontact) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.ideal) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.sofort) - XCTAssertEqual(source.sofort?.country, "DE") - XCTAssertEqual(source.sofort?.bankCode, "34569") - XCTAssertEqual(source.sofort?.bic, "Meh") - XCTAssertEqual(source.sofort?.bankName, "Vapor Bank") - XCTAssertEqual(source.sofort?.ibanLast4, "4560") - XCTAssertEqual(source.sofort?.preferredLanguage, "English") - XCTAssertEqual(source.sofort?.statementDescriptor, "Henlo friend") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - - let bancontactSourceString = """ -{ - "id": "src_16xhynE8WzK49JbAs9M21jaR", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU", - "created": 1445277809, - "currency": "eur", - "statement_descriptor": null, - "flow": "redirect", - "metadata": {}, - "livemode": true, - "owner": { - "address": null, - "email": null, - "name": "Jenny Rosen", - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": "Jenny Rosen", - "verified_phone": null - }, - "redirect": { - "return_url": "https://shop.example.com/crtA6B28E1", - "status": "pending", - "url": "https://pay.stripe.com/redirect/src_16xhynE8WzK49JbAs9M21jaR?client_secret=src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU" - }, - "status": "pending", - "type": "bancontact", - "usage": "single_use", - "bancontact": { - "bank_code": "33333", - "bic": "Unknown", - "bank_name": "Vapor Bank", - "statement_descriptor": "Eat veggies", - "preferred_language": "English" - } -} -""" - - func testBancontactSourceParsedProperly() throws { - do { - let body = HTTPBody(string: bancontactSourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.alipay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.giropay) - XCTAssertNil(source.p24) - XCTAssertNil(source.sofort) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.ideal) - XCTAssertNil(source.achCreditTransfer) - - XCTAssertNotNil(source.bancontact) - XCTAssertEqual(source.bancontact?.bankCode, "33333") - XCTAssertEqual(source.bancontact?.bic, "Unknown") - XCTAssertEqual(source.bancontact?.bankName, "Vapor Bank") - XCTAssertEqual(source.bancontact?.statementDescriptor, "Eat veggies") - XCTAssertEqual(source.bancontact?.preferredLanguage, "English") - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - let achSourceString = """ -{ - "id": "src_16xhynE8WzK49JbAs9M21jaR", - "object": "source", - "amount": 1099, - "client_secret": "src_client_secret_UfwvW2WHpZ0s3QEn9g5x7waU", - "created": 1445277809, - "currency": "eur", - "statement_descriptor": null, - "flow": "code_verification", - "metadata": {}, - "livemode": true, - "owner": { - "address": null, - "email": null, - "name": "Jenny Rosen", - "phone": null, - "verified_address": null, - "verified_email": null, - "verified_name": "Jenny Rosen", - "verified_phone": null - }, - "code_verification": { - "attempts_remaining": 30, - "status": "pending", - }, - "status": "pending", - "type": "ach_credit_transfer", - "usage": "single_use", - "ach_credit_transfer": { - "account_number": "test_52796e3294dc", - "routing_number": "110000000", - "fingerprint": "nfd2882gh38h", - "bank_name": "TEST BANK", - "swift_code": "TSTEZ122" - } -} -""" - - func testACHSourceParsedProperly() throws { - do { - let body = HTTPBody(string: achSourceString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let source = try decoder.decode(StripeSource.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - source.do { (source) in - XCTAssertNil(source.card) - XCTAssertNil(source.alipay) - XCTAssertNil(source.threeDSecure) - XCTAssertNil(source.giropay) - XCTAssertNil(source.p24) - XCTAssertNil(source.sofort) - XCTAssertNil(source.sepaDebit) - XCTAssertNil(source.ideal) - XCTAssertNil(source.bancontact) - - XCTAssertNotNil(source.achCreditTransfer) - XCTAssertEqual(source.achCreditTransfer?.accountNumber, "test_52796e3294dc") - XCTAssertEqual(source.achCreditTransfer?.routingNumber, "110000000") - XCTAssertEqual(source.achCreditTransfer?.fingerprint, "nfd2882gh38h") - XCTAssertEqual(source.achCreditTransfer?.bankName, "TEST BANK") - XCTAssertEqual(source.achCreditTransfer?.swiftCode, "TSTEZ122") - - // CodeVerification - XCTAssertEqual(source.codeVerification?.attemptsRemaining, 30) - XCTAssertEqual(source.codeVerification?.status, .pending) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } -} diff --git a/Tests/StripeTests/SubscriptionTests.swift b/Tests/StripeTests/SubscriptionTests.swift deleted file mode 100644 index b25c146..0000000 --- a/Tests/StripeTests/SubscriptionTests.swift +++ /dev/null @@ -1,295 +0,0 @@ -// -// SubscriptionTests.swift -// Stripe -// -// Created by Andrew Edwards on 6/10/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class SubscriptionTests: XCTestCase { - func testSubscriptionParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: subscriptionString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let subscription = try decoder.decode(StripeSubscription.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - subscription.do({ (sub) in - - // This test covers the Discount object - XCTAssertNotNil(sub.discount) - XCTAssertEqual(sub.discount?.object, "discount") - XCTAssertEqual(sub.discount?.customer, "cus_CCMIISleHrbPlY") - XCTAssertEqual(sub.discount?.end, Date(timeIntervalSince1970: 1399384361)) - XCTAssertEqual(sub.discount?.start, Date(timeIntervalSince1970: 1391694761)) - XCTAssertEqual(sub.discount?.subscription, "sub_12345") - - // This test covers the Coupon object - XCTAssertNotNil(sub.discount?.coupon) - XCTAssertEqual(sub.discount?.coupon?.id, "35OFF") - XCTAssertEqual(sub.discount?.coupon?.object, "coupon") - XCTAssertEqual(sub.discount?.coupon?.amountOff, 5) - XCTAssertEqual(sub.discount?.coupon?.created, Date(timeIntervalSince1970: 1391694467)) - XCTAssertEqual(sub.discount?.coupon?.currency, .usd) - XCTAssertEqual(sub.discount?.coupon?.duration, .repeating) - XCTAssertEqual(sub.discount?.coupon?.durationInMonths, 3) - XCTAssertEqual(sub.discount?.coupon?.livemode, false) - XCTAssertEqual(sub.discount?.coupon?.maxRedemptions, 22) - XCTAssertEqual(sub.discount?.coupon?.metadata["hello"], "world") - XCTAssertEqual(sub.discount?.coupon?.percentOff, 25) - XCTAssertEqual(sub.discount?.coupon?.redeemBy, Date(timeIntervalSince1970: 1489793908)) - XCTAssertEqual(sub.discount?.coupon?.timesRedeemed, 1) - XCTAssertEqual(sub.discount?.coupon?.valid, true) - - // This test covers the Subscription item list object - XCTAssertNotNil(sub.items) - XCTAssertEqual(sub.items?.object, "list") - XCTAssertEqual(sub.items?.hasMore, false) - XCTAssertEqual(sub.items?.totalCount, 1) - XCTAssertEqual(sub.items?.url, "/v1/subscription_items?subscription=sub_AJ6s2Iy65K3RxN") - - // This test covers the SubscriptionItem object - XCTAssertNotNil(sub.items?.data) - XCTAssertNotNil(sub.items?.data?[0]) - XCTAssertEqual(sub.items?.data?[0].id, "si_19yUeQ2eZvKYlo2CnJwkz3pK") - XCTAssertEqual(sub.items?.data?[0].object, "subscription_item") - XCTAssertEqual(sub.items?.data?[0].created, Date(timeIntervalSince1970: 1489793911)) - XCTAssertEqual(sub.items?.data?[0].metadata["hello"], "world") - XCTAssertEqual(sub.items?.data?[0].quantity, 1) - XCTAssertEqual(sub.items?.data?[0].subscription, "sub_AJ6s2Iy65K3RxN") - - // These cover the Plan object - XCTAssertNotNil(sub.items?.data?[0].plan) - XCTAssertEqual(sub.items?.data?[0].plan?.id, "30990foo1489793903") - XCTAssertEqual(sub.items?.data?[0].plan?.object, "plan") - XCTAssertEqual(sub.items?.data?[0].plan?.amount, 100) - XCTAssertEqual(sub.items?.data?[0].plan?.created, Date(timeIntervalSince1970: 1489793908)) - XCTAssertEqual(sub.items?.data?[0].plan?.currency, .usd) - XCTAssertEqual(sub.items?.data?[0].plan?.interval, .week) - XCTAssertEqual(sub.items?.data?[0].plan?.intervalCount, 1) - XCTAssertEqual(sub.items?.data?[0].plan?.livemode, false) - XCTAssertEqual(sub.items?.data?[0].plan?.metadata["hello"], "world") - XCTAssertEqual(sub.items?.data?[0].plan?.nickname, "Foo") - XCTAssertEqual(sub.items?.data?[0].plan?.product, "prod_1234") - XCTAssertEqual(sub.items?.data?[0].plan?.transformUsage?.divideBy, 5) - XCTAssertEqual(sub.items?.data?[0].plan?.transformUsage?.round, .up) - XCTAssertEqual(sub.items?.data?[0].plan?.trialPeriodDays, 3) - - // These cover the Plan object - XCTAssertNotNil(sub.items?.data?[1].plan) - XCTAssertEqual(sub.items?.data?[1].plan?.amount, nil) - XCTAssertEqual(sub.items?.data?[1].plan?.tiers?[0].amount, 0) - XCTAssertEqual(sub.items?.data?[1].plan?.tiers?[0].upTo, 1) - XCTAssertEqual(sub.items?.data?[1].plan?.tiers?[1].amount, 200) - XCTAssertEqual(sub.items?.data?[1].plan?.tiers?[1].upTo, nil) - XCTAssertEqual(sub.items?.data?[1].plan?.tiersMode, .graduated) - - // These cover the Plan object - XCTAssertNotNil(sub.plan) - XCTAssertEqual(sub.plan?.id, "30990foo1489793903") - XCTAssertEqual(sub.plan?.object, "plan") - XCTAssertEqual(sub.plan?.billingScheme, .perUnit) - XCTAssertEqual(sub.plan?.usageType, .metered) - XCTAssertEqual(sub.plan?.active, false) - XCTAssertEqual(sub.plan?.amount, 100) - XCTAssertEqual(sub.plan?.created, Date(timeIntervalSince1970: 1489793908)) - XCTAssertEqual(sub.plan?.currency, .usd) - XCTAssertEqual(sub.plan?.interval, .week) - XCTAssertEqual(sub.plan?.intervalCount, 1) - XCTAssertEqual(sub.plan?.livemode, false) - XCTAssertEqual(sub.plan?.metadata["hello"], "world") - XCTAssertEqual(sub.plan?.nickname, "Foo") - XCTAssertEqual(sub.plan?.product, "prod_1234") - XCTAssertEqual(sub.plan?.trialPeriodDays, 14) - - XCTAssertEqual(sub.id, "sub_AJ6s2Iy65K3RxN") - XCTAssertEqual(sub.object, "subscription") - XCTAssertEqual(sub.applicationFeePercent, 12.7) - XCTAssertEqual(sub.billing, "charge_automatically") - XCTAssertEqual(sub.billingCycleAnchor, Date(timeIntervalSince1970: 1490398710)) - XCTAssertEqual(sub.cancelAtPeriodEnd, false) - XCTAssertEqual(sub.canceledAt, Date(timeIntervalSince1970: 1489793914)) - XCTAssertEqual(sub.created, Date(timeIntervalSince1970: 1489793910)) - XCTAssertEqual(sub.currentPeriodEnd, Date(timeIntervalSince1970: 1490398710)) - XCTAssertEqual(sub.currentPeriodStart, Date(timeIntervalSince1970: 1489793910)) - XCTAssertEqual(sub.customer, "cus_CCMIISleHrbPlY") - XCTAssertEqual(sub.daysUntilDue, 4) - XCTAssertEqual(sub.endedAt, Date(timeIntervalSince1970: 1489793914)) - XCTAssertEqual(sub.livemode, true) - XCTAssertEqual(sub.metadata["foo"], "bar") - XCTAssertEqual(sub.quantity, 1) - XCTAssertEqual(sub.start, Date(timeIntervalSince1970: 1489793910)) - XCTAssertEqual(sub.status, StripeSubscriptionStatus.pastDue) - XCTAssertEqual(sub.taxPercent, 4.5) - XCTAssertEqual(sub.trialEnd, Date(timeIntervalSince1970: 1489793910)) - XCTAssertEqual(sub.trialStart, Date(timeIntervalSince1970: 1489793910)) - }).catch({ (error) in - XCTFail("\(error)") - }) - } - catch { - XCTFail("\(error)") - } - } - - let subscriptionString = """ -{ - "id": "sub_AJ6s2Iy65K3RxN", - "object": "subscription", - "application_fee_percent": 12.7, - "billing": "charge_automatically", - "billing_cycle_anchor": 1490398710, - "cancel_at_period_end": false, - "canceled_at": 1489793914, - "created": 1489793910, - "current_period_end": 1490398710, - "current_period_start": 1489793910, - "customer": "cus_CCMIISleHrbPlY", - "days_until_due": 4, - "discount": { - "object": "discount", - "coupon": { - "id": "35OFF", - "object": "coupon", - "amount_off": 5, - "created": 1391694467, - "currency": "usd", - "duration": "repeating", - "duration_in_months": 3, - "livemode": false, - "max_redemptions": 22, - "metadata": { - "hello": "world" - }, - "percent_off": 25, - "redeem_by": 1489793908, - "times_redeemed": 1, - "valid": true - }, - "customer": "cus_CCMIISleHrbPlY", - "end": 1399384361, - "start": 1391694761, - "subscription": "sub_12345" - }, - "ended_at": 1489793914, - "items": { - "object": "list", - "data": [ - { - "id": "si_19yUeQ2eZvKYlo2CnJwkz3pK", - "object": "subscription_item", - "created": 1489793911, - "metadata": { - "hello": "world" - }, - "plan": { - "id": "30990foo1489793903", - "object": "plan", - "amount": 100, - "active": false, - "billing_scheme": "per_unit", - "usage_type": "metered", - "created": 1489793908, - "currency": "usd", - "interval": "week", - "interval_count": 1, - "livemode": false, - "metadata": { - "hello": "world" - }, - "nickname": "Foo", - "product": "prod_1234", - "transform_usage": { - "divide_by": 5, - "round": "up" - }, - "trial_period_days": 3 - }, - "quantity": 1, - "subscription": "sub_AJ6s2Iy65K3RxN" - }, - { - "id": "si_DKeuh94LM6FNyn", - "object": "subscription_item", - "created": 1533050240, - "metadata": { - }, - "plan": { - "id": "plan_DIkuyHGrZFW7DN", - "object": "plan", - "active": true, - "aggregate_usage": null, - "amount": null, - "billing_scheme": "tiered", - "created": 1532611277, - "currency": "usd", - "interval": "week", - "interval_count": 1, - "livemode": false, - "metadata": { - }, - "nickname": "Bar", - "product": "prod_DIksc7vKNkuiw3", - "tiers": [ - { - "amount": 0, - "up_to": 1 - }, - { - "amount": 200, - "up_to": null - } - ], - "tiers_mode": "graduated", - "transform_usage": null, - "trial_period_days": null, - "usage_type": "licensed" - }, - "quantity": 8, - "subscription": "sub_DKeur6TMKSqZqB" - } - ], - "has_more": false, - "total_count": 1, - "url": "/v1/subscription_items?subscription=sub_AJ6s2Iy65K3RxN" - }, - "livemode": true, - "metadata": { - "foo": "bar" - }, - "plan": { - "id": "30990foo1489793903", - "object": "plan", - "amount": 100, - "active": false, - "billing_scheme": "per_unit", - "usage_type": "metered", - "created": 1489793908, - "currency": "usd", - "interval": "week", - "interval_count": 1, - "livemode": false, - "metadata": { - "hello": "world" - }, - "nickname": "Foo", - "product": "prod_1234", - "trial_period_days": 14 - }, - "quantity": 1, - "start": 1489793910, - "status": "past_due", - "tax_percent": 4.5, - "trial_end": 1489793910, - "trial_start": 1489793910 -} -""" -} diff --git a/Tests/StripeTests/TokenTests.swift b/Tests/StripeTests/TokenTests.swift deleted file mode 100644 index 153dd99..0000000 --- a/Tests/StripeTests/TokenTests.swift +++ /dev/null @@ -1,180 +0,0 @@ -// -// TokenTests.swift -// Stripe -// -// Created by Anthony Castelli on 5/12/17. -// -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class TokenTests: XCTestCase { - func testCardTokenParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: cardTokenString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let cardToken = try decoder.decode(StripeToken.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - cardToken.do { (token) in - XCTAssertNil(token.bankAccount) - XCTAssertNotNil(token.card) - - // This test covers the card object - XCTAssertEqual(token.card?.id, "card_1BnxhQ2eZvKYlo2CPNu4CkoA") - XCTAssertEqual(token.card?.object, "card") - XCTAssertEqual(token.card?.addressCity, "Miami") - XCTAssertEqual(token.card?.addressCountry, "US") - XCTAssertEqual(token.card?.addressLine1, "123 Main Street") - XCTAssertEqual(token.card?.addressLine1Check, .failed) - XCTAssertEqual(token.card?.addressLine2, "Apt 123") - XCTAssertEqual(token.card?.addressState, "Florida") - XCTAssertEqual(token.card?.addressZip, "12345") - XCTAssertEqual(token.card?.addressZipCheck, .pass) - XCTAssertEqual(token.card?.brand, .visa) - XCTAssertEqual(token.card?.country, "US") - XCTAssertEqual(token.card?.cvcCheck, .pass) - XCTAssertEqual(token.card?.dynamicLast4, "1234") - XCTAssertEqual(token.card?.expMonth, 8) - XCTAssertEqual(token.card?.expYear, 2019) - XCTAssertEqual(token.card?.fingerprint, "Xt5EWLLDS7FJjR1c") - XCTAssertEqual(token.card?.funding, .credit) - XCTAssertEqual(token.card?.last4, "4242") - XCTAssertEqual(token.card?.metadata?["hello"], "world") - XCTAssertEqual(token.card?.name, "Vapor") - XCTAssertEqual(token.card?.tokenizationMethod, .applePay) - - XCTAssertEqual(token.id, "tok_1BnxhQ2eZvKYlo2CVEbDC7jK") - XCTAssertEqual(token.object, "token") - XCTAssertEqual(token.clientIp, "0.0.0.0") - XCTAssertEqual(token.created, Date(timeIntervalSince1970: 1516836636)) - XCTAssertEqual(token.livemode, false) - XCTAssertEqual(token.type, .card) - XCTAssertEqual(token.used, false) - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - func testBankTokenParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: bankAccountTokenString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let bankToken = try decoder.decode(StripeToken.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - bankToken.do { (token) in - XCTAssertNil(token.card) - XCTAssertNotNil(token.bankAccount) - - // This test covers the bank account object - XCTAssertEqual(token.bankAccount?.id, "ba_1BnxhQ2eZvKYlo2C5cM6hYK1") - XCTAssertEqual(token.bankAccount?.object, "bank_account") - XCTAssertEqual(token.bankAccount?.accountHolderName, "Jane Austen") - XCTAssertEqual(token.bankAccount?.accountHolderType, .individual) - XCTAssertEqual(token.bankAccount?.bankName, "STRIPE TEST BANK") - XCTAssertEqual(token.bankAccount?.country, "US") - XCTAssertEqual(token.bankAccount?.currency, .usd) - XCTAssertEqual(token.bankAccount?.fingerprint, "1JWtPxqbdX5Gamtc") - XCTAssertEqual(token.bankAccount?.last4, "6789") - XCTAssertEqual(token.bankAccount?.metadata?["hello"], "world") - XCTAssertEqual(token.bankAccount?.routingNumber, "110000000") - XCTAssertEqual(token.bankAccount?.status, .new) - - XCTAssertEqual(token.id, "btok_1BnxhQ2eZvKYlo2CbYrQL91x") - XCTAssertEqual(token.object, "token") - XCTAssertEqual(token.clientIp, "0.0.0.0") - XCTAssertEqual(token.created, Date(timeIntervalSince1970: 1516836636)) - XCTAssertEqual(token.livemode, false) - XCTAssertEqual(token.type, .bankAccount) - XCTAssertEqual(token.used, false) - - }.catch { (error) in - XCTFail("\(error)") - } - } - catch { - XCTFail("\(error)") - } - } - - let cardTokenString = """ -{ - "id": "tok_1BnxhQ2eZvKYlo2CVEbDC7jK", - "object": "token", - "card": { - "id": "card_1BnxhQ2eZvKYlo2CPNu4CkoA", - "object": "card", - "address_city":"Miami", - "address_country":"US", - "address_line1":"123 Main Street", - "address_line1_check":"failed", - "address_line2":"Apt 123", - "address_state":"Florida", - "address_zip":"12345", - "address_zip_check":"pass", - "brand": "Visa", - "country": "US", - "cvc_check": "pass", - "dynamic_last4": "1234", - "exp_month": 8, - "exp_year": 2019, - "fingerprint": "Xt5EWLLDS7FJjR1c", - "funding": "credit", - "last4": "4242", - "metadata": { - "hello": "world" - }, - "name": "Vapor", - "tokenization_method": "apple_pay" - }, - "client_ip": "0.0.0.0", - "created": 1516836636, - "livemode": false, - "type": "card", - "used": false -} -""" - - let bankAccountTokenString = """ -{ - "id": "btok_1BnxhQ2eZvKYlo2CbYrQL91x", - "object": "token", - "bank_account": { - "id": "ba_1BnxhQ2eZvKYlo2C5cM6hYK1", - "object": "bank_account", - "account_holder_name": "Jane Austen", - "account_holder_type": "individual", - "bank_name": "STRIPE TEST BANK", - "country": "US", - "currency": "usd", - "fingerprint": "1JWtPxqbdX5Gamtc", - "last4": "6789", - "metadata": { - "hello": "world" - }, - "routing_number": "110000000", - "status": "new" - }, - "client_ip": "0.0.0.0", - "created": 1516836636, - "livemode": false, - "type": "bank_account", - "used": false -} -""" -} diff --git a/Tests/StripeTests/TopUpTests.swift b/Tests/StripeTests/TopUpTests.swift deleted file mode 100644 index aa5d09f..0000000 --- a/Tests/StripeTests/TopUpTests.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// TopUpTests.swift -// StripeTests -// -// Created by Andrew Edwards on 3/24/19. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class TopUpTests: XCTestCase { - let topupString = """ -{ - "id": "tu_123456789", - "object": "topup", - "amount": 1000, - "balance_transaction": null, - "created": 123456789, - "currency": "usd", - "description": "Top-up description", - "expected_availability_date": 123456789, - "failure_code": "sorry", - "failure_message": "we're sorry", - "livemode": false, - "metadata": { - "order_id": "12345678" - }, - "source": null, - "statement_descriptor": null, - "status": "pending", - "transfer_group": null -} -""" - - func testTopUpParsesProperly() throws { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: topupString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let topup = try decoder.decode(StripeTopUp.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()).wait() - - XCTAssertEqual(topup.currency, .usd) - XCTAssertEqual(topup.expectedAvailabilityDate, Date(timeIntervalSince1970: 123456789)) - XCTAssertEqual(topup.failureCode, "sorry") - XCTAssertEqual(topup.failureMessage, "we're sorry") - XCTAssertEqual(topup.metadata?["order_id"], "12345678") - } -} diff --git a/Tests/StripeTests/TransferTests.swift b/Tests/StripeTests/TransferTests.swift deleted file mode 100644 index 9983909..0000000 --- a/Tests/StripeTests/TransferTests.swift +++ /dev/null @@ -1,106 +0,0 @@ -// -// TransferTests.swift -// StripeTests -// -// Created by Andrew Edwards on 4/3/18. -// - -import XCTest -@testable import Stripe -@testable import Vapor - -class TransferTests: XCTestCase { - let transferString = """ -{ - "id": "tr_164xRv2eZvKYlo2CZxJZWm1E", - "object": "transfer", - "amount": 200, - "amount_reversed": 200, - "balance_transaction": "txn_19XJJ02eZvKYlo2ClwuJ1rbA", - "created": 1432229235, - "currency": "usd", - "description": "transfers ahoy!", - "destination": "acct_164wxjKbnvuxQXGu", - "destination_payment": "py_164xRvKbnvuxQXGuVFV2pZo1", - "livemode": false, - "metadata": { - "order_id": "6735" - }, - "reversals": { - "object": "list", - "data": [ - { - "id": "trr_1BGmS02eZvKYlo2CklK9McmT", - "object": "transfer_reversal", - "amount": 100, - "balance_transaction": "txn_1BGmS02eZvKYlo2C9f16WPBN", - "created": 1508928572, - "currency": "usd", - "metadata": { - "hello":"world" - }, - "transfer": "tr_164xRv2eZvKYlo2CZxJZWm1E" - }, - ], - "has_more": false, - "total_count": 2, - "url": "/v1/transfers/tr_164xRv2eZvKYlo2CZxJZWm1E/reversals" - }, - "reversed": true, - "source_transaction": "ch_164xRv2eZvKYlo2Clu1sIJWB", - "source_type": "card", - "transfer_group": "group_ch_164xRv2eZvKYlo2Clu1sIJWB" -} -""" - - func testTransferParsedProperly() throws { - do { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .secondsSince1970 - - let body = HTTPBody(string: transferString) - var headers: HTTPHeaders = [:] - headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) - let request = HTTPRequest(headers: headers, body: body) - let transfer = try decoder.decode(StripeTransfer.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) - - transfer.do { (tran) in - - XCTAssertEqual(tran.id, "tr_164xRv2eZvKYlo2CZxJZWm1E") - XCTAssertEqual(tran.object, "transfer") - XCTAssertEqual(tran.amount, 200) - XCTAssertEqual(tran.amountReversed, 200) - XCTAssertEqual(tran.balanceTransaction, "txn_19XJJ02eZvKYlo2ClwuJ1rbA") - XCTAssertEqual(tran.created, Date(timeIntervalSince1970: 1432229235)) - XCTAssertEqual(tran.currency, .usd) - XCTAssertEqual(tran.description, "transfers ahoy!") - XCTAssertEqual(tran.destination, "acct_164wxjKbnvuxQXGu") - XCTAssertEqual(tran.destinationPayment, "py_164xRvKbnvuxQXGuVFV2pZo1") - XCTAssertEqual(tran.livemode, false) - XCTAssertEqual(tran.metadata["order_id"], "6735") - XCTAssertEqual(tran.reversed, true) - XCTAssertEqual(tran.sourceTransaction, "ch_164xRv2eZvKYlo2Clu1sIJWB") - XCTAssertEqual(tran.sourceType, "card") - XCTAssertEqual(tran.transferGroup, "group_ch_164xRv2eZvKYlo2Clu1sIJWB") - - // This test covers the transfer reversal - XCTAssertEqual(tran.reversals?.object, "list") - XCTAssertEqual(tran.reversals?.hasMore, false) - XCTAssertEqual(tran.reversals?.totalCount, 2) - XCTAssertEqual(tran.reversals?.url, "/v1/transfers/tr_164xRv2eZvKYlo2CZxJZWm1E/reversals") - XCTAssertEqual(tran.reversals?.data?[0].id, "trr_1BGmS02eZvKYlo2CklK9McmT") - XCTAssertEqual(tran.reversals?.data?[0].object, "transfer_reversal") - XCTAssertEqual(tran.reversals?.data?[0].amount, 100) - XCTAssertEqual(tran.reversals?.data?[0].balanceTransaction, "txn_1BGmS02eZvKYlo2C9f16WPBN") - XCTAssertEqual(tran.reversals?.data?[0].created, Date(timeIntervalSince1970: 1508928572)) - XCTAssertEqual(tran.reversals?.data?[0].metadata["hello"], "world") - XCTAssertEqual(tran.reversals?.data?[0].transfer, "tr_164xRv2eZvKYlo2CZxJZWm1E") - }.catch { (error) in - XCTFail("\(error.localizedDescription)") - } - } - catch { - XCTFail("\(error.localizedDescription)") - } - } -} diff --git a/Tests/StripeTests/XCTestManifests.swift b/Tests/StripeTests/XCTestManifests.swift index be8b652..3222d4a 100644 --- a/Tests/StripeTests/XCTestManifests.swift +++ b/Tests/StripeTests/XCTestManifests.swift @@ -1,185 +1,9 @@ import XCTest -extension AccountTests { - static let __allTests = [ - ("testAccountParsedProperly", testAccountParsedProperly), - ] -} - -extension ApplicationFeeTests { - static let __allTests = [ - ("testApplicationFeeParsesProperly", testApplicationFeeParsesProperly), - ("testApplicationFeeRefundParsesProperly", testApplicationFeeRefundParsesProperly), - ] -} - -extension BalanceTests { - static let __allTests = [ - ("testBalanceParsedProperly", testBalanceParsedProperly), - ("testBalanceTransactionParsedProperly", testBalanceTransactionParsedProperly), - ] -} - -extension ChargeTests { - static let __allTests = [ - ("testChargeParsedProperly", testChargeParsedProperly), - ] -} - -extension CountrySpecTests { - static let __allTests = [ - ("testCountrySpecParsesProperly", testCountrySpecParsesProperly), - ] -} - -extension CustomerTests { - static let __allTests = [ - ("testCustomerParsedProperly", testCustomerParsedProperly), - ] -} - -extension DisputeTests { - static let __allTests = [ - ("testDisputeParsedProperly", testDisputeParsedProperly), - ] -} - -extension EphemeralKeyTests { - static let __allTests = [ - ("testEphemeralKeyParsedProperly", testEphemeralKeyParsedProperly), - ] -} - -extension ErrorTests { - static let __allTests = [ - ("testErrorParsedProperly", testErrorParsedProperly), - ] -} - -extension FileTests { - static let __allTests = [ - ("testFileLinkParsedProperly", testFileLinkParsedProperly), - ("testFileUploadParsedProperly", testFileUploadParsedProperly), - ] -} - -extension InvoiceTests { - static let __allTests = [ - ("testInvoiceItemParsedProperly", testInvoiceItemParsedProperly), - ("testInvoiceParsedProperly", testInvoiceParsedProperly), - ] -} - -extension OrderTests { - static let __allTests = [ - ("testOrderIsProperlyParsed", testOrderIsProperlyParsed), - ] -} - -extension PaymentSourceTests { - static let __allTests = [ - ("testSourceListIsProperlyParsed", testSourceListIsProperlyParsed), - ] -} - -extension PayoutTests { - static let __allTests = [ - ("testPayoutsParsedProperly", testPayoutsParsedProperly), - ] -} - -extension ProductTests { - static let __allTests = [ - ("testProductParsedProperly", testProductParsedProperly), - ] -} - -extension QueryEncodingTests { - static let __allTests = [ - ("testNestedArrayQueryEncodedProperly", testNestedArrayQueryEncodedProperly), - ("testNestedDictionaryQueryEncodedProperly", testNestedDictionaryQueryEncodedProperly), - ("testSimpleQueryEncodedProperly", testSimpleQueryEncodedProperly), - ] -} - -extension RefundTests { - static let __allTests = [ - ("testRefundParsedProperly", testRefundParsedProperly), - ] -} -extension SKUTests { - static let __allTests = [ - ("testSkuParsedProperly", testSkuParsedProperly), - ] -} - -extension SourceTests { - static let __allTests = [ - ("testACHSourceParsedProperly", testACHSourceParsedProperly), - ("testAlipaySourceParsedProperly", testAlipaySourceParsedProperly), - ("testBancontactSourceParsedProperly", testBancontactSourceParsedProperly), - ("testCardSourceParsedProperly", testCardSourceParsedProperly), - ("testGiropaySourceParsedProperly", testGiropaySourceParsedProperly), - ("testIdealSourceParsedProperly", testIdealSourceParsedProperly), - ("testP24SourceParsedProperly", testP24SourceParsedProperly), - ("testSepaDebitSourceParsedProperly", testSepaDebitSourceParsedProperly), - ("testSofortSourceParsedProperly", testSofortSourceParsedProperly), - ("testThreeDSecureSourceParsedProperly", testThreeDSecureSourceParsedProperly), - ] -} - -extension SubscriptionTests { - static let __allTests = [ - ("testSubscriptionParsedProperly", testSubscriptionParsedProperly), - ] -} - -extension TokenTests { - static let __allTests = [ - ("testBankTokenParsedProperly", testBankTokenParsedProperly), - ("testCardTokenParsedProperly", testCardTokenParsedProperly), - ] -} - -extension TopUpTests { - static let __allTests = [ - ("testTopUpParsesProperly", testTopUpParsesProperly), - ] -} - -extension TransferTests { - static let __allTests = [ - ("testTransferParsedProperly", testTransferParsedProperly), - ] -} #if !os(macOS) public func __allTests() -> [XCTestCaseEntry] { - return [ - testCase(AccountTests.__allTests), - testCase(ApplicationFeeTests.__allTests), - testCase(BalanceTests.__allTests), - testCase(ChargeTests.__allTests), - testCase(CountrySpecTests.__allTests), - testCase(CustomerTests.__allTests), - testCase(DisputeTests.__allTests), - testCase(EphemeralKeyTests.__allTests), - testCase(ErrorTests.__allTests), - testCase(FileTests.__allTests), - testCase(InvoiceTests.__allTests), - testCase(OrderTests.__allTests), - testCase(PaymentSourceTests.__allTests), - testCase(PayoutTests.__allTests), - testCase(ProductTests.__allTests), - testCase(QueryEncodingTests.__allTests), - testCase(RefundTests.__allTests), - testCase(SKUTests.__allTests), - testCase(SourceTests.__allTests), - testCase(SubscriptionTests.__allTests), - testCase(TokenTests.__allTests), - testCase(TopUpTests.__allTests), - testCase(TransferTests.__allTests), - ] + return [] } #endif From a63472177ed91d98903c960fa4dad214e7f66544 Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Fri, 14 Jun 2019 19:52:31 -0400 Subject: [PATCH 10/14] Update Package.swift --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 0be83ec..9d9da19 100644 --- a/Package.swift +++ b/Package.swift @@ -8,7 +8,7 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-alpha"), - .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.0"), + .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.3"), ], targets: [ .target(name: "Stripe", dependencies: ["Vapor","StripeKit"]), From c1580bca2f8e998217e5f6caba83b2084a83b864 Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Tue, 18 Jun 2019 22:32:20 -0400 Subject: [PATCH 11/14] Update Package.swift --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 9d9da19..aa2b0a1 100644 --- a/Package.swift +++ b/Package.swift @@ -8,7 +8,7 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-alpha"), - .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.3"), + .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.4"), ], targets: [ .target(name: "Stripe", dependencies: ["Vapor","StripeKit"]), From b47488aacd7ca19608e207f9a9be7fe254ed23d5 Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Tue, 18 Jun 2019 22:41:46 -0400 Subject: [PATCH 12/14] Update Package.swift --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index aa2b0a1..d720938 100644 --- a/Package.swift +++ b/Package.swift @@ -8,7 +8,7 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-alpha"), - .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.4"), + .package(url: "https://github.com/vapor-community/StripeKit.git", .branch("master")), ], targets: [ .target(name: "Stripe", dependencies: ["Vapor","StripeKit"]), From 0cf3526bf27e2fa2c245c8c072fa75e28ab0e45e Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Tue, 18 Jun 2019 23:08:07 -0400 Subject: [PATCH 13/14] Update Package.swift --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index d720938..a93a309 100644 --- a/Package.swift +++ b/Package.swift @@ -8,7 +8,7 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-alpha"), - .package(url: "https://github.com/vapor-community/StripeKit.git", .branch("master")), + .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.5"), ], targets: [ .target(name: "Stripe", dependencies: ["Vapor","StripeKit"]), From f1add446688516a2861b61fb229639a8e8527b8f Mon Sep 17 00:00:00 2001 From: Andrew Edwards Date: Mon, 15 Jul 2019 20:13:22 -0400 Subject: [PATCH 14/14] Use latest StripeKit. --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index a93a309..eb45480 100644 --- a/Package.swift +++ b/Package.swift @@ -8,7 +8,7 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-alpha"), - .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.5"), + .package(url: "https://github.com/vapor-community/StripeKit.git", from: "1.0.6"), ], targets: [ .target(name: "Stripe", dependencies: ["Vapor","StripeKit"]),