This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathTransactionsServiceRemote.swift
More file actions
209 lines (171 loc) · 8.45 KB
/
Copy pathTransactionsServiceRemote.swift
File metadata and controls
209 lines (171 loc) · 8.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import Foundation
@objc public class TransactionsServiceRemote: ServiceRemoteWordPressComREST {
public enum ResponseError: Error {
case decodingFailure
}
private enum Constants {
static let freeDomainPaymentMethod = "WPCOM_Billing_WPCOM"
}
@objc public func getSupportedCountries(success: @escaping ([WPCountry]) -> Void,
failure: @escaping (Error) -> Void) {
let endPoint = "me/transactions/supported-countries/"
let servicePath = path(forEndpoint: endPoint, withVersion: ._1_1)
wordPressComRESTAPI.get(servicePath,
parameters: nil,
success: {
response, _ in
do {
guard let json = response as? [AnyObject] else {
throw ResponseError.decodingFailure
}
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let decodedResult = try JSONDecoder.apiDecoder.decode([WPCountry].self, from: data)
success(decodedResult)
} catch {
WPKitLogError("Error parsing Supported Countries (\(error)): \(response)")
failure(error)
}
}, failure: { error, _ in
failure(error)
})
}
/// Creates a shopping cart with products
/// - Parameters:
/// - siteID: id of the current site
/// - products: an array of products to be added to the newly created cart
/// - temporary: true if the card is temporary, false otherwise
public func createShoppingCart(siteID: Int?,
products: [TransactionsServiceProduct],
temporary: Bool,
success: @escaping (CartResponse) -> Void,
failure: @escaping (Error) -> Void) {
let siteIDString = siteID != nil ? "\(siteID ?? 0)" : "no-site"
let endPoint = "me/shopping-cart/\(siteIDString)"
let urlPath = path(forEndpoint: endPoint, withVersion: ._1_1)
var productsDictionary: [[String: AnyObject]] = []
for product in products {
switch product {
case .domain(let domainSuggestion, let privacyProtectionEnabled):
productsDictionary.append(["product_id": domainSuggestion.productID as AnyObject,
"meta": domainSuggestion.domainName as AnyObject,
"extra": ["privacy": privacyProtectionEnabled] as AnyObject])
case .plan(let productId):
productsDictionary.append(["product_id": productId as AnyObject])
case .other(let productDict):
productsDictionary.append(productDict)
}
}
let parameters: [String: AnyObject] = ["temporary": (temporary ? "true" : "false") as AnyObject,
"products": productsDictionary as AnyObject]
wordPressComRESTAPI.post(urlPath,
parameters: parameters,
success: { (response, _) in
guard let jsonResponse = response as? [String: AnyObject],
let cart = CartResponse(jsonDictionary: jsonResponse),
!cart.products.isEmpty else {
failure(TransactionsServiceRemote.ResponseError.decodingFailure)
return
}
success(cart)
}) { (error, _) in
failure(error)
}
}
// MARK: - Domains
public func redeemCartUsingCredits(cart: CartResponse,
domainContactInformation: [String: String],
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
let endPoint = "me/transactions"
let urlPath = path(forEndpoint: endPoint, withVersion: ._1_1)
let paymentDict = ["payment_method": Constants.freeDomainPaymentMethod]
let parameters: [String: AnyObject] = ["domain_details": domainContactInformation as AnyObject,
"cart": cart.jsonRepresentation() as AnyObject,
"payment": paymentDict as AnyObject]
wordPressComRESTAPI.post(urlPath, parameters: parameters, success: { (_, _) in
success()
}) { (error, _) in
failure(error)
}
}
/// Creates a temporary shopping cart for a domain purchase
@available(*, deprecated, message: "Use createShoppingCart(_:) and pass an array of specific products instead")
public func createTemporaryDomainShoppingCart(siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponse) -> Void,
failure: @escaping (Error) -> Void) {
createShoppingCart(siteID: siteID,
products: [.domain(domainSuggestion, privacyProtectionEnabled)],
temporary: true,
success: success,
failure: failure)
}
/// Creates a persistent shopping cart for a domain purchase
@available(*, deprecated, message: "Use createShoppingCart(_:) and pass an array of specific products instead")
public func createPersistentDomainShoppingCart(siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponse) -> Void,
failure: @escaping (Error) -> Void) {
createShoppingCart(siteID: siteID,
products: [.domain(domainSuggestion, privacyProtectionEnabled)],
temporary: false,
success: success,
failure: failure)
}
}
public enum TransactionsServiceProduct {
public typealias ProductId = Int
public typealias PrivacyProtection = Bool
case domain(DomainSuggestion, PrivacyProtection)
case plan(ProductId)
case other([String: AnyObject])
}
public struct CartResponse {
let blogID: Int
let cartKey: Any // cart key can be either Int or String
let products: [Product]
init?(jsonDictionary: [String: AnyObject]) {
guard
let cartKey = jsonDictionary["cart_key"],
let blogID = jsonDictionary["blog_id"] as? Int,
let products = jsonDictionary["products"] as? [[String: AnyObject]]
else {
return nil
}
let mappedProducts = products.compactMap { (product) -> Product? in
guard
let productID = product["product_id"] as? Int else {
return nil
}
let meta = product["meta"] as? String
let extra = product["extra"] as? [String: AnyObject]
return Product(productID: productID, meta: meta, extra: extra)
}
self.blogID = blogID
self.cartKey = cartKey
self.products = mappedProducts
}
fileprivate func jsonRepresentation() -> [String: AnyObject] {
return ["blog_id": blogID as AnyObject,
"cart_key": cartKey as AnyObject,
"products": products.map { $0.jsonRepresentation() } as AnyObject]
}
}
public struct Product {
let productID: Int
let meta: String?
let extra: [String: AnyObject]?
fileprivate func jsonRepresentation() -> [String: AnyObject] {
var returnDict: [String: AnyObject] = [:]
returnDict["product_id"] = productID as AnyObject
if let meta = meta {
returnDict["meta"] = meta as AnyObject
}
if let extra = extra {
returnDict["extra"] = extra as AnyObject
}
return returnDict
}
}