package com.example.checkout import android.os.Handler import android.os.Looper import org.json.JSONObject import java.net.HttpURLConnection import java.net.URL import java.util.concurrent.Executors // Application-owned API, not the platform API. Supply your customer's session token. class CheckoutApi(private val origin: String, private val customerToken: () -> String) { private val worker = Executors.newSingleThreadExecutor() private val main = Handler(Looper.getMainLooper()) init { require(origin.startsWith("https://") && !origin.endsWith("/")) } fun request(path: String, body: JSONObject? = null, done: (Result) -> Unit) { require(path.startsWith("/api/")) worker.execute { val result = runCatching { val connection = URL(origin + path).openConnection() as HttpURLConnection try { connection.instanceFollowRedirects = false connection.connectTimeout = 15000 connection.readTimeout = 15000 connection.requestMethod = if (body == null) "GET" else "POST" connection.setRequestProperty("Authorization", "Bearer ${customerToken()}") connection.setRequestProperty("Accept", "application/json") if (body != null) { connection.doOutput = true connection.setRequestProperty("Content-Type", "application/json") connection.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) } } check(connection.responseCode in 200..299) { "Application API returned ${connection.responseCode}" } JSONObject(connection.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }) } finally { connection.disconnect() } } main.post { done(result) } } } fun close() { worker.shutdown() } }