JNYJ

JNYJ - IOS - DEV

 

如何实现程序内购买(In app purchase)?

XXXXXX...... 未整理!!!!

#pragma mark IBAction methods

- (IBAction) back: (id) sender;
{
    [self.target performSelector:self.action withObject:nil];
    [self dismissModalViewControllerAnimated:YES];
}
- (IBAction) unlock: (id) sender
{
    if ([self assetNetworkAvailable]) {
        NSString *productID = nil;
        if ([self.arrayOfProducts count] == 0) {
            [ModalAlert say:@"You have been complete all the upgrades! "];
            return;
        }
        if ([self.arrayOfSelectedProducts count] == 0) {
            [ModalAlert say:@"Please choose which product to upgrade."];
            return;
        }else{
            NSIndexPath *selectedIndexPath = (NSIndexPath *)[self.arrayOfSelectedProducts objectAtIndex:0];
            productID = ((VMProduct *)[self.arrayOfProducts objectAtIndex:selectedIndexPath.row]).productID;
            if ([BGLInAppPurchase assetUnlockForiZipFeature:productID]) {
                [ModalAlert say:@"You're already purchased this In App Purchase."];
                return;
            }
        }
        // Init log
        [self doLog:@"Submitting Request... Please wait."];
        // Create the product request and start it
        [self doLog:productID];
        [self startCheckPurchasing];
        SKProductsRequest *preq = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:productID]];
        preq.delegate = self;
        [preq start];
    }
}
#pragma mark SK Product request and Payment transactionObsever methods

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    [ModalAlert say:[NSString stringWithFormat:@"Error: Could not contact App Store properly, %@", [error localizedDescription]]];
    [self doLog:[NSString stringWithFormat:@"Error: Could not contact App Store properly, %@", [error localizedDescription]]];
    [self loadingViewData];
}

- (void)requestDidFinish:(SKRequest *)request
{
	// Release the request
	[request release];
	[self doLog:@"Request finished."];
}

- (void) repurchase
{
	[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
#pragma mark SKProductsRequestDelegate methods
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    
	SKProduct *product = [[response products] lastObject];
	if (!product)
	{    
        [self doLog:@"Error retrieving product information from App Store. Sorry! Please try again later."];
        [ModalAlert say:@"Error retrieving product information from App Store. Sorry! Please try again later."];
        [self loadingViewData];
		return;
	}
    
	// Retrieve the localized price
	NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
	[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
	[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
	[numberFormatter setLocale:product.priceLocale];
	NSString *formattedString = [numberFormatter stringFromNumber:product.price];
	[numberFormatter release];
	
	// Create a description that gives a heads up about 
	// a non-consumable purchase
	NSString *buyString = formattedString; 
	NSString *describeString = [NSString stringWithFormat:@"%@\n\nIf you have already purchased this item, you will not be charged again.", product.localizedDescription];
	NSArray *buttons = [NSArray arrayWithObject: buyString];
	
	// Offer the user a choice to buy or not buy
	if ([ModalAlert ask:describeString withCancel:@"No Thanks" withButtons:buttons])
	{
        [self startCheckPurchasing];
        SKPayment *payment = [SKPayment paymentWithProductIdentifier:product.productIdentifier];  //[response.products objectAtIndex:0].productIdentifier];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
	}
	else
	{
		// restore the GUI to provide a buy/purchase button
		// or otherwise to a ready-to-buy state   
        [self loadingViewData];
	}
}

#pragma mark SKPaymentTransactionObserver delegate motheds
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions
{
}

- (void) completedPurchaseTransaction: (SKPaymentTransaction *) transaction
{
	// PERFORM THE SUCCESS ACTION THAT UNLOCKS THE FEATURE HERE
    
    // Check the receipt
	NSString *json = [NSString stringWithFormat:@"{\"receipt-data\":\"%@\"}", [transaction.transactionReceipt base64Encoding]];
	NSString *urlsting = SANDBOX ? @"https://sandbox.itunes.apple.com/verifyReceipt" : @"https://buy.itunes.apple.com/verifyReceipt";
	NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlsting]];
	if (!urlRequest) NOTIFY_AND_LEAVE(@"Error creating the URL Request");
	
	[urlRequest setHTTPMethod: @"POST"];
	[urlRequest setHTTPBody:[json dataUsingEncoding:NSUTF8StringEncoding]];
	
	NSError *error;
	NSURLResponse *response;
	NSData *result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
	
	NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
	[self doLog:resultString];
    NSString *productID = nil;
    if ([BGLInAppPurchase assetReceipt:resultString]) {
        
        //Get product id from selected products.
        if ([self.arrayOfSelectedProducts count] >0 && [self.arrayOfProducts count] >0 ) {
            NSIndexPath *selectedIndexPath = (NSIndexPath *)[self.arrayOfSelectedProducts objectAtIndex:0];
            if (selectedIndexPath.row <[self.arrayOfProducts count]) {
                
                productID = ((VMProduct *)[self.arrayOfProducts objectAtIndex:selectedIndexPath.row]).productID;
                [BGLInAppPurchase unlockForiZipFeature:productID];
            }
        }else{
            //Get product id from json code
            productID = [BGLInAppPurchase getProductIDByParseJSON:resultString];
            if (productID != nil) {        
                [BGLInAppPurchase unlockForiZipFeature:productID];
            }
        }
    }
    [resultString release];
	
	// Finish transaction
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    [self.target performSelector:self.action withObject:productID];
    [self loadingViewData];
}
- (void) restoredPurchaseTransaction: (SKPaymentTransaction *) transaction
{
	// PERFORM THE SUCCESS ACTION THAT UNLOCKS THE FEATURE HERE
    
    // Check the receipt
	NSString *json = [NSString stringWithFormat:@"{\"receipt-data\":\"%@\"}", [transaction.transactionReceipt base64Encoding]];
	NSString *urlsting = SANDBOX ? @"https://sandbox.itunes.apple.com/verifyReceipt" : @"https://buy.itunes.apple.com/verifyReceipt";
	NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlsting]];
	if (!urlRequest) NOTIFY_AND_LEAVE(@"Error creating the URL Request");
	
	[urlRequest setHTTPMethod: @"POST"];
	[urlRequest setHTTPBody:[json dataUsingEncoding:NSUTF8StringEncoding]];
	
	NSError *error;
	NSURLResponse *response;
	NSData *result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
	
	NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
	[self doLog:resultString];
    NSString *productID = nil;
    if ([BGLInAppPurchase assetReceipt:resultString]) {
        
        //Get product id from selected products.
        if ([self.arrayOfSelectedProducts count] >0 && [self.arrayOfProducts count] >0 ) {
            NSIndexPath *selectedIndexPath = (NSIndexPath *)[self.arrayOfSelectedProducts objectAtIndex:0];
            if (selectedIndexPath.row <[self.arrayOfProducts count]) {
                
                productID = ((VMProduct *)[self.arrayOfProducts objectAtIndex:selectedIndexPath.row]).productID;
                [BGLInAppPurchase unlockForiZipFeature:productID];
            }
        }else{
            //Get product id from json code
            productID = [BGLInAppPurchase getProductIDByParseJSON:resultString];
            if (productID != nil) {        
                [BGLInAppPurchase unlockForiZipFeature:productID];
            }
        }
    }
    [resultString release];
	
	// Finish transaction
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    [self.target performSelector:self.action withObject:productID];
    [self loadingViewData];
}
- (void) handleFailedTransaction: (SKPaymentTransaction *) transaction
{
	if (transaction.error.code != SKErrorPaymentCancelled){
		[ModalAlert say:@"Cancelled. Please try again later."];
    }
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    [self loadingViewData];
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions 
{
	for (SKPaymentTransaction *transaction in transactions) {
        if (![self assetNetworkAvailable]) {
            [self handleFailedTransaction:transaction];
            break;
        }
		switch (transaction.transactionState) {
			case SKPaymentTransactionStatePurchased: 
                DebugLog(@"\n -----> Purchased. ");
				[self completedPurchaseTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored: 
                DebugLog(@"\n -----> Completed purchased. ");
				[self restoredPurchaseTransaction:transaction];
				break;
			case SKPaymentTransactionStateFailed: 
                DebugLog(@"\n -----> Purchase failed. ");
				[self handleFailedTransaction:transaction]; 
				break;
			default: 
                DebugLog(@"\n -----> None. ");
				break;
		}
	}
}

posted on 2011-05-04 17:56  JNYJ  阅读(3851)  评论(0)    收藏  举报

导航