iOS develops the built-in function and builds the source code of live broadcasting platform during the development of live broadcasting platform

1. Log on to the Apple account first. After the source code of the live broadcasting platform is set up, enter the background management center to add goods. Select functions - --- purchasing items in App - - - add the type of goods, the ID of goods, and the description information.

2. Set up a sandbox test account in the background of the source code of the live broadcast platform: Sandbox account can be filled in according with the mailbox format at will.

3. Set up the backstage recharge rules in the source code of the live broadcasting platform, the ID of the apple project filled in and the ID of the commodity in the apple account above, and the price information of the commodity.

4. When the user clicks on the purchase, the purchase begins. First, the interface requests the order information in the source code of the live broadcasting platform, obtains the commodity information with the Apple Payment ID, and initiates the order request to Apple.

//Buy-in Start
-(void)applePay:(NSDictionary *)dic{

    [self.delegate applePayShowHUD];
    NSDictionary *dics = @{
                          @"uid":[Config getOwnID],
                          @"coin":[dic valueForKey:@"coin"],
                          @"money":[dic valueForKey:@"money_ios"],
                          @"changeid":dic[@"id"]
                          };
    [YBToolClass postNetworkWithUrl:@"Charge.getIosOrder" andParameter:dics success:^(int code, id  _Nonnull info, NSString * _Nonnull msg) {
        if (code == 0) {
            NSString *infos = [[info firstObject] valueForKey:@"orderid"];
            self.OrderNo = infos;//Order
            //Apple Payment ID
            NSString *setStr = [NSString stringWithFormat:@"%@",[dic valueForKey:@"product_id"]];
            NSSet *set = [[NSSet alloc] initWithObjects:setStr, nil];
            self.request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
            self.request.delegate = self;
            [self.request start];  
        }
        else{
            [self.delegate applePayHUD];
            [MBProgressHUD showError:msg];
        }
    } fail:^{ 
    }];
}

5. Get product information and join the payment queue

 (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    [self.delegate applePayHUD];
    self.products = response.products;
    self.request = nil;
    for (SKProduct *product in response.products) {
NSLog(@"A product letter has been obtained
//Interest%@,%@,%@, product. localizedTitle, product. localizedDescription, product. price;
        self.product = product;
    }
    if (!self.product) {
        [self showAlertView:YZMsg(@"Failure to obtain commodity information")];
        return;
    }
    //3. Get product information and join the payment queue
    SKPayment *payment = [SKPayment paymentWithProduct:self.product];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

6. Obtain payment results based on Apple Payment API callback

- (void)recordTransaction:(SKPaymentTransaction *)transaction {
    // Optional: Record the transaction on the server side...
//Record current successful purchases
    // NSLog(@"recordTransaction");
}
- (void)provideContent:(NSString *)productIdentifier {
    // NSLog(@"provideContent %@", productIdentifier);
    //Provide different services for purchased goods.
    [_purchasedProducts addObject:productIdentifier];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
            default:
                break;
        }
    }
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    //NSLog(@"completeTransaction...");
    [self recordTransaction: transaction];
    [self provideContent: transaction.payment.productIdentifier];
    [self verifyReceipt:transaction];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

7. The server validates the purchase voucher, submits the validation request, and obtains the result of the official validation, verifies the payment success, updates the interface and adds diamonds, and then the whole Apple Payment is completed.

#pragma mark server validates purchase credentials
- (void) verifyReceipt:(SKPaymentTransaction *)transaction
{
        //Apple: Domain name +/Appapi/Pay/notify_ios
    [self.delegate applePayHUD];
    NSURL *url = [NSURL URLWithString:[h5url stringByAppendingFormat:@"/Appapi/Pay/notify_ios"]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    request.HTTPMethod = @"POST";
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    NSData *transData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
    NSString *encodeStr = [transData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\",\"sandbox\":%@,\"out_trade_no\" : \"%@\"}", encodeStr,@"0",self.OrderNo];
    //Converting body String to NSData data
    NSData *bodyData = [payload dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];//Converting body String to NSData data
    [request setHTTPBody:bodyData];
    // Submit validation requests and obtain official validation JSON results
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if (result == nil) {
       // [MBProgress HUD showError:@ "Validation Failure"];
    }
    else
    {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
        if(dict==nil)
        {
             [MBProgressHUD showError:YZMsg(@"Check to see if the debugging mode is enabled on the website")];
            return;
        }
        if ([[dict valueForKey:@"status"] isEqual:@"success"]) {
          //Comparing the following information in a dictionary basically ensures data security
            [MBProgressHUD showError:YZMsg(@"Successful recharge")];
            [self.delegate applePaySuccess];
        }
        else
        {
            [MBProgressHUD showError:[dict valueForKey:@"info"]];
            
        }
    }
}

Above is iOS development buy-in function when developing live broadcasting platform. In the process of building source code of live broadcasting platform, when the source code of live broadcasting platform is completed, it enters the background management center to add commodities, select functions - - purchase items in App - - add commodity types, commodity ID, and description information.
Statement: This article is a small original article, reproduced please indicate the source and author.

Keywords: JSON iOS

Added by vh3r on Fri, 09 Aug 2019 12:37:09 +0300