Skip to content

Instantly share code, notes, and snippets.

@Schadenfeude
Last active August 18, 2020 12:22
Show Gist options
  • Save Schadenfeude/09f74f669409684cd34ab772bc4e4114 to your computer and use it in GitHub Desktop.
Save Schadenfeude/09f74f669409684cd34ab772bc4e4114 to your computer and use it in GitHub Desktop.
A facade which provides an implementation of a billing manager depending on whether in-app billing via PlayStore is available
import android.content.Context
import android.util.Log
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.Purchase
import com.wacom.cloud.billing.manager.BillingManagerAliPay
import com.wacom.cloud.billing.manager.BillingManagerPlayStore
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.withContext
import kotlin.coroutines.experimental.suspendCoroutine
object BillingManagerProvider {
private val TAG by lazy { BillingManagerProvider::class.java.simpleName }
private const val DEBUG = false
/**
* Returns PlayStore billing manager (if available) or falls back to
* the AliPay implementation
*/
suspend fun get(context: Context): BillingManagerInterface {
return withContext(Dispatchers.Main) {
return@withContext if (!isPlayStoreAvailable(context)) {
BillingManagerAliPay(context)
} else {
BillingManagerPlayStore(context)
}
}
}
/**
* Possible responses (also tested in China):
* 0 - [com.android.billingclient.api.BillingClient.BillingResponse.OK]
* 3 - [com.android.billingclient.api.BillingClient.BillingResponse.BILLING_UNAVAILABLE]
*/
private suspend fun isPlayStoreAvailable(context: Context): Boolean =
suspendCoroutine { cont ->
if (DEBUG) {
Log.d(TAG, "suspendCoroutine: startConnection")
}
val billingClient: BillingClient = BillingClient.newBuilder(context)
.setListener { _: Int, _: MutableList<Purchase>? -> }.build()
billingClient.startConnection(
object : BillingClientStateListener {
override fun onBillingSetupFinished(responseCode: Int) {
if (DEBUG) {
Log.d(TAG, "onBillingSetupFinished = $responseCode")
}
cont.resume(responseCode == BillingClient.BillingResponse.OK)
billingClient.endConnection()
}
override fun onBillingServiceDisconnected() {
if (DEBUG) {
Log.d(TAG, "onBillingServiceDisconnected")
}
cont.resume(false)
billingClient.endConnection()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment