-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPIclient.swift
46 lines (43 loc) · 1.99 KB
/
APIclient.swift
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
import StripeTerminal
// Example API client class for communicating with your backend
class APIClient: ConnectionTokenProvider {
// For simplicity, this example class is a singleton
static let shared = APIClient()
// Fetches a ConnectionToken from your backend
func fetchConnectionToken(_ completion: @escaping ConnectionTokenCompletionBlock) {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
guard let url = URL(string: "https://{{YOUR_BACKEND_URL}}/connection_token") else {
fatalError("Invalid backend URL")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let task = session.dataTask(with: request) { (data, response, error) in
if let data = data {
do {
// Warning: casting using `as? [String: String]` looks simpler, but isn't safe:
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
if let secret = json?["secret"] as? String {
completion(secret, nil)
}
else {
let error = NSError(domain: "com.stripe-terminal-ios.example",
code: 2000,
userInfo: [NSLocalizedDescriptionKey: "Missing `secret` in ConnectionToken JSON response"])
completion(nil, error)
}
}
catch {
completion(nil, error)
}
}
else {
let error = NSError(domain: "com.stripe-terminal-ios.example",
code: 1000,
userInfo: [NSLocalizedDescriptionKey: "No data in response from ConnectionToken endpoint"])
completion(nil, error)
}
}
task.resume()
}
}