AppleIap.m 5.81 KB
//
//  AppleIap.m
//  Demo_youdian
//
//  Created by 许 on 17/6/20.
//  Copyright © 2017年 winFan. All rights reserved.
//

#import "AppleIap.h"

#import "IAPShare.h"
#import "PoolSdk.h"

@implementation AppleIap

/**
 @return 商品ID
 */
- (NSString*)getProductIdByAmount:(NSString*)products amount:(NSString*)amount
{
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:products options:NSJSONWritingPrettyPrinted error:nil];
    if(jsonData){
        NSDictionary* productList = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
        if(productList){
            NSEnumerator* keysList = [productList keyEnumerator];
            id keyValue;
            while (keyValue = [keysList nextObject])
            {
                NSString* appleAmount = [[productList objectForKey:keyValue] objectForKey:@"amount"];
                if(appleAmount.intValue == amount.intValue){
                    NSLog(@"appleAmount:%@ amount:%@",appleAmount,amount);
                    return keyValue;
                }
            }
        }
    }
    NSLog(@"amount get productId error amount:%@",amount);
    return nil;
}


-(void)applePay:(NSString *)products amount:(NSString *)amount queryId:(NSString *)queryId
{
    //内购ID
    NSString* productId = [self getProductIdByAmount:products amount:amount];
    if(productId){
        [self ipaPay:productId queryId:queryId];
    }else{
        NSLog(@"get apple product id error");
    }
}

/**
 苹果支付结果回调
 */

- (void)applePayCallBack:(NSString*)receiptStr queryId:(NSString*)queryId
{
    //NSDictionary* payResultDic = notification.object;
    //NSString* receiptStr = [payResultDic objectForKey:@"payResult"];
    //NSString* queryId = [payResultDic objectForKey:@"query_id"];
    
    NSDictionary* receiptDic = [NSDictionary dictionaryWithObjectsAndKeys:receiptStr,@"receipt",queryId,@"query_id", nil];
    NSString* result = [[NetCenter getInstance] httpPostSyn:[PoolUtils createPayUrl] :receiptDic];
    
    if([@"success" isEqualToString:result]){//确认订单成功
    }else{//失败
        NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray* queryIdArray = [userDefaults objectForKey:@"queryIds"];
        
        NSMutableArray* tempQueryIdArray = [[NSMutableArray alloc] initWithCapacity:10];
        
        if (queryIdArray) {
        }else{
            queryIdArray = [[NSMutableArray alloc]initWithCapacity:10];
        }
        
        for (NSString* arrayQueryId in queryIdArray) {
            [tempQueryIdArray addObject:arrayQueryId];
        }
        
        [tempQueryIdArray addObject:queryId];
        [userDefaults setObject:tempQueryIdArray forKey:@"queryIds"];
        [userDefaults setObject:receiptStr forKey:queryId];
        [userDefaults synchronize];
    }
}



- (void)initIpa:(NSString*)productId{
    if(![IAPShare sharedHelper].iap){
        NSLog(@"iap init");
    }
    NSSet* dataSet = [[NSSet alloc]initWithObjects:productId, nil];
    [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
}


- (void)ipaPay:(NSString*) productId queryId:(NSString*)queryId{
    @synchronized([PoolSdk shareSDK]) {
        if([PoolSdk shareSDK].isApplePaying) {
            NSLog(@"apple paying");
            return;
        };
        [PoolSdk shareSDK].isApplePaying = true;
    }
    NSLog(@"productId:%@",productId);
    [self initIpa:productId];
    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest* request,SKProductsResponse* response)
     {
         NSLog(@"response");
         if(response && response > 0 ) {
             NSLog(@"response %lu",(unsigned long)[[IAPShare sharedHelper].iap.products count]);
             if([[IAPShare sharedHelper].iap.products count] > 0){
                 NSLog(@"product count 1");
                 SKProduct* product =[[IAPShare sharedHelper].iap.products objectAtIndex:0];
                 
                 [[IAPShare sharedHelper].iap buyProduct:product
                                            onCompletion:^(SKPaymentTransaction* trans){
                                                [PoolSdk shareSDK].isApplePaying = false;
                                                if(trans.error)
                                                {
                                                    NSLog(@"Fail %@",[trans.error localizedDescription]);
                                                }
                                                else if(trans.transactionState == SKPaymentTransactionStatePurchased) {
                                                    
                                                    NSData* receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
                                                    
                                                    NSString* receiptStr = [receiptData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                                                    
                                                    receiptStr = [receiptStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                                                    
                                                    [self applePayCallBack:receiptStr queryId:queryId];
                                                }
                                                else if(trans.transactionState == SKPaymentTransactionStateFailed) {
                                                    NSLog(@"Fail");
                                                }
                                            }];
             }else{
                 [PoolSdk shareSDK].isApplePaying = false;
             }
         }else{
             [PoolSdk shareSDK].isApplePaying = false;
         }
     }];
}

@end