Skip to content

Instantly share code, notes, and snippets.

@jonathanpeppers
Last active May 5, 2017 19:41
Show Gist options
  • Save jonathanpeppers/abf7fc6f70f1bc54f8a7ac875297a828 to your computer and use it in GitHub Desktop.
Save jonathanpeppers/abf7fc6f70f1bc54f8a7ac875297a828 to your computer and use it in GitHub Desktop.
Google Play PurchaseService.BuyNative
protected async override Task<Receipt> BuyNative(Purchase purchase)
{
var context = (Activity)Xamarin.Forms.Forms.Context;
string developerPayload = Guid.NewGuid().ToString("N");
var buyIntent = _connection.Service.GetBuyIntent(BillingConstants.ApiVersion, context.PackageName, purchase.Id, BillingConstants.ItemTypeInApp, developerPayload);
int response = buyIntent.GetInt(BillingConstants.ResponseCode);
if (response != BillingConstants.ResultOk)
{
//NOTE: see my full example for handling BillingConstants.ResultItemAlreadyOwned
throw new Exception("GetBuyIntent failed, code: " + response);
}
var source =
_purchaseSource = new TaskCompletionSource<Order>();
var pendingIntent = (PendingIntent)buyIntent.GetParcelable(BillingConstants.BuyIntent);
context.StartIntentSenderForResult(pendingIntent.IntentSender, BillingConstants.PurchaseRequestCode, new Intent(), 0, 0, 0);
var order = await source.Task;
if (order.DeveloperPayload != developerPayload)
{
throw new Exception($"DeveloperPayload did not match {developerPayload} != {order.DeveloperPayload}");
}
return await ConsumePurchase(order);
}
//NOTE: this is split out into a separate method for handling BillingConstants.ResultItemAlreadyOwned
private async Task<Receipt> ConsumePurchase(Order order)
{
if (string.IsNullOrEmpty(order.PurchaseToken))
{
throw new Exception("PurchaseToken not found, cannot consume purchase!");
}
int response = await Task.Factory.StartNew(() => _connection.Service.ConsumePurchase(BillingConstants.ApiVersion, Application.Context.PackageName, order.PurchaseToken));
if (response != BillingConstants.ResultOk)
{
throw new Exception("ConsumePurchase failed, code: " + response);
}
return new GoogleReceipt
{
Id = order.ProductId,
TransactionId = order.OrderId ?? "TEST", //NOTE: if null, it is a test purchase
PurchaseToken = order.PurchaseToken,
DeveloperPayload = order.DeveloperPayload,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment