Validate Google Play Purchase at Ktor server

71 Views Asked by At

I am using a Ktor server to check if the purchase made on google play is valid using a purchase token:

Here is my code :

fun Route.validatePurchase() {
route("/validatePurchase") {
    get {
        val purchaseToken = call.request.queryParameters[PURCHASE_TOKEN_RF] ?: return@get
        //create a tracker that contains the total items modified
        val isValid = validateThePurchase(purchaseToken)
        //Successful
        if (isValid == "True") {
            call.respond(HttpStatusCode.OK, isValid)
        } else if ( isValid == "False") {
            call.respond(HttpStatusCode.Forbidden, isValid)
        } else if ( isValid == "Error") {
            call.respond(HttpStatusCode.ServiceUnavailable, isValid) // This error is being returned always
        }else {
            call.respond(HttpStatusCode.NotImplemented, isValid)
        }
    }
}
}

private fun validateThePurchase(purchaseToken: String) : String {

val packageName = "com.packaganame.app"
val subscriptionId = "god_mode"


return try {

    val httpTransport = GoogleNetHttpTransport.newTrustedTransport()
    val jsonFactory = JacksonFactory.getDefaultInstance()

    val credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(listOf("https://androidpublisher.googleapis.com/auth/androidpublisher"))

    val httpRequestInitializer = HttpCredentialsAdapter(credentials)

    val androidPublisher = AndroidPublisher.Builder(httpTransport, jsonFactory, httpRequestInitializer)
        .setApplicationName("com.package.app")
        .build()

    val subscriptionPurchase: SubscriptionPurchase = androidPublisher.Purchases()
        .subscriptions()
        .get(packageName, subscriptionId, purchaseToken)
        .execute()

    // Check if the subscription is currently active.
    val currentTimeMillis = System.currentTimeMillis()
    val expiryTimeMillis = subscriptionPurchase.expiryTimeMillis

    if (currentTimeMillis < expiryTimeMillis) {
        "True" // The subscription is active.
    } else {
        "False" // The subscription has expired.
    }

} catch (e: Exception) {
    //function enters this catch block
    "Error"
}


}

I keep getting a HttpStatusCode.Forbidden error.

I have also done the following

  • Enabled the "Google Play Developer API" at Google Cloud Project.
  • I have linked the default Google App Engine Service account with Google Play
  • Given it the "view financial data" and "Manage orders/subscriptions" permissions at the Google Play API Access section

Any suggestions on what is wrong with my code?

0

There are 0 best solutions below