Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marchbold/851359b9e456e1a85d65 to your computer and use it in GitHub Desktop.
Save marchbold/851359b9e456e1a85d65 to your computer and use it in GitHub Desktop.
Making a purchase
// The service must be setup and a list of products retrieved.
// Make sure you have the following listeners
InAppBilling.service.addEventListener( PurchaseEvent.PURCHASES_UPDATED, purchases_updatedHandler );
InAppBilling.service.addEventListener( PurchaseEvent.PURCHASE_FAILED, purchase_failedHandler );
var request:PurchaseRequest = new PurchaseRequest();
request.productId = productId;
request.quantity = 1;
var success:Boolean = InAppBilling.service.makePurchase( request );
trace( "makePurchase( "+productId+" ) = " + success );
...
//
// PURCHASE EVENTS
//
function purchases_updatedHandler( event:PurchaseEvent ):void
{
for each (var purchase:Purchase in event.data)
{
switch (purchase.transactionState)
{
// These transactions are in progress, so don't finish them unless you don't want them to complete
case Purchase.STATE_PURCHASING:
case Purchase.STATE_DEFERRED:
break;
// The purchased state should finished after you have delivered the product if applicable
case Purchase.STATE_PURCHASED:
{
trace( "purchase success" );
//
// If you wish you can add the purchase to your inventory
// and finish the purchase here
addPurchaseToInventory( purchase );
InAppBilling.service.finishPurchase( purchase );
//
// Alternatively hold onto this purchase so we can call
// finish when you've delivered the product
//
// You would do this if you are validating the purchase on a server or
// other operation that is required to complete before the product is delivered
//_purchases.push( purchase );
break;
}
// For all other states you should handle appropriately and call finish purchase
case Purchase.STATE_FAILED:
case Purchase.STATE_REFUNDED:
case Purchase.STATE_RESTORED:
case Purchase.STATE_REMOVED:
case Purchase.STATE_CANCELLED:
case Purchase.STATE_NOTALLOWED:
InAppBilling.service.finishPurchase( purchase );
break;
}
}
}
function purchase_failedHandler( event:PurchaseEvent ):void
{
// This transaction failed so you should notify your user and finish the purchase
trace( "purchase failed [" + event.errorCode + "] :: "+ event.message );
if (event.data && event.data.length > 0)
{
InAppBilling.service.finishPurchase( event.data[0] );
}
//
// Android may return this code if the item is already owned
//
if (event.errorCode == ErrorCodes.ITEM_ALREADY_OWNED)
{
// You should use getPurchases() to retrieve the users purchases
// and then add them as missing from their current inventory
InAppBilling.service.getPurchases();
}
}
// com.distriqt.InAppBilling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment