AppStore in the audit, if you sell in the app is a virtual product, then you may be asked not to use the third-party payment tool, only use the IAP in-app payment function.
Using this feature requires the Apple developer to sign the contract, set the bank account number, set the price, this does not speak, this article mainly about the integration of IAP code PHONEGAP
/**
* Apple in-app payment
*/
(function (cordova) {
Var define = cordova.define;
Define("cordova/plugin/applepay", function (require, exports, module) {
Var argscheck = require('cordova/argscheck'),
Exec = require('cordova/exec');
Exports.pay = function (productID,quantity, successCB, failCB) {
Exec(successCB, failCB, "ApplePay", "pay", [productID,quantity]);
};
});
cordova.addConstructor(function () {
If (!window.plugins) {
Window.plugins = {};
}
Console.log("Inject the plugin into cordovaapplepay...");
Window.plugins.applepay = cordova.require("cordova/plugin/applepay");
Console.log("applepay injection result:" + typeof (window.plugins.applepay));
});
})(cordova);
<feature name="ApplePay">
<param name="ios-package" value="CDVApplePay" />
</feature>
#import <Cordova/CDV.h>
@interface CDVApplePay : CDVPlugin
@property (nonatomic,copy) NSString*callbackID;
//Instance Method
- (void)pay:(CDVInvokedUrlCommand*)command;
@end
#import "CDVApplePay.h"
#import "AppDelegate.h"
#import <StoreKit/StoreKit.h>
#import "MainViewController.h"
#import "Conts.h"
@implementation CDVApplePay
@synthesize callbackID;
- (void)pay:(CDVInvokedUrlCommand*)command {
If ([SKPaymentQueue canMakePayments]) {
NSString *produtid = [command.arguments objectAtIndex:0];
NSString* strQuantity =[command.arguments objectAtIndex:1];
buyQuantity = [strQuantity intValue];
MainViewController* view = [[MainViewController alloc] init];
[view getProductInfo:produtid];
// [[AppDelegate appDelegate] getProductInfo:produtid];
} else {
NSLog (@" failed, the user prohibits in-app purchases.");
NSString *js = [[NSString alloc]initWithFormat:@"yooshow.alert('%@')", @"You have disabled in-app purchases, please enable "] first;
[[AppDelegate appDelegate] runJS:js];
}
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end
Add in MAINVIEWCONTROLLER.M
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
/ / Monitor the purchase results
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
For (SKPaymentTransaction *transaction in transactions)
{
Switch (transaction.transactionState)
{
Case SKPaymentTransactionStatePurchased://Transaction completed
NSLog(@"transactionIdentifier = %@", transaction.transactionIdentifier);
[self completeTransaction:transaction];
Break;
Case SKPaymentTransactionStateFailed://transaction failed
[self failedTransaction:transaction];
Break;
Case SKPaymentTransactionStateRestored:// has already purchased this item
[self restoreTransaction:transaction];
Break;
Case SKPaymentTransactionStatePurchasing: //Items added to the list
NSLog (@"Apple trading serial number starts trading transactionIdentifier = %@", transaction.transactionIdentifier);
NSLog (@"Products added to the list here our server should create an order");
Break;
Default:
Break;
}
}
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
// Your application should implement these two methods.
NSString * productIdentifier = transaction.payment.productIdentifier;
NSString * receipt = [transaction.transactionReceipt base64Encoding];
NSLog (@"Apple transaction serial number complete transaction transactionIdentifier = %@", transaction.transactionIdentifier);
If ([productIdentifier length] > 0) {
// Verify purchase credentials to your own server
NSLog (@" purchase success should modify our server user data credentials to %@, product information%@", receipt, productIdentifier);
NSString *js = [[NSString alloc]initWithFormat:@"pay.applePayResult('%@','%@')", transaction.transactionIdentifier,receipt];
[[AppDelegate appDelegate] runJS:js];
}
// Remove the transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
If(transaction.error.code != SKErrorPaymentCancelled) {
NSLog (@"buy failed");
} else {
NSLog (@"user cancels transaction");
}
NSString *js = [[NSString alloc]initWithFormat:@"$.ui.hideMask();" ];
[[AppDelegate appDelegate] runJS:js];
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
NSLog (@"Restore purchase");
NSString * productIdentifier = transaction.payment.productIdentifier;
NSString * receipt = [transaction.transactionReceipt base64Encoding];
If ([productIdentifier length] > 0) {
// Verify purchase credentials to your own server
NSLog (@" recovery purchase success should modify our server user data credentials to %@, product information%@", receipt, productIdentifier);
}
// Deal with the logic to restore purchases for purchased items
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
// The ProductId below should be a pre-existing paid item added to itunesConnect. Otherwise the query will fail.
- (void)getProductInfo:(NSString*) productID
{
NSSet * set = [NSSet setWithArray:@[productID]];
SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
Request.delegate = self;
[request start];
}
// The callback function of the above query
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray *myProduct = response.products;
If (myProduct.count == 0) {
NSLog (@"Unable to get product information, purchase failed.");
NSString *js = [[NSString alloc]initWithFormat:@"$.ui.hideMask();" ];
[[AppDelegate appDelegate] runJS:js];
Return;
}
// SKPayment * payment = [SKPayment paymentWithProduct:myProduct[0]];
// payment.quantity =buyQuantity;
SKMutablePayment * payment = [SKMutablePayment paymentWithProduct:myProduct[0]];
Payment.quantity = buyQuantity;
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
Note the callback after the client succeeds
End of server authentication, server I use C #
Public bool ApplePayNotifyVerify(ApplePayParam param)
{
/ / Verify payment vouchers
/ / Initialize the communication processing class
Try
{
//The payment voucher cannot be reused. Check whether the payment voucher has been counted in the running account. If it is used, it will return false directly. If it has not been used, it can be verified and processed.
Var payment = PaymentService.Instance.GetList(p => p.AppleReceipt == param.AppleReceipt).FirstOrDefault();
If (payment == null)
{
Var config = AppService.Instance.GetThirdPartyConfig();
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Var receipt = "{\"receipt-data\":\"" + param.AppleReceipt + "\"}";
HttpContent content = new StringContent(receipt, Encoding.UTF8);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = httpClient.PostAsync(new Uri(config.ApplePayVerify), content).Result;
String result = response.Content.ReadAsStringAsync().Result.Replace(Environment.NewLine, string.Empty).Replace("\n", string.Empty);
Var entity= JObject.Parse(result);
//AppleVerifyEntity entity = JsonConvert.DeserializeObject<AppleVerifyEntity>(result);
If (entity.Value<int>("status") == 0)
{
/ / Modify the order status after successful, billing, plus flowers
OrderPaySuccessParam payParam = new OrderPaySuccessParam();
//order number
payParam.OrderNO = param.OrderNO;
//transaction number
payParam.TradeNO = param.TradeNO;
//payment method
payParam.PayMethod = PaymentMethodKind.Online;
//Seller's collection account
payParam.Account = config.ApplePayBankAccount;
//Seller's collection account bank
payParam.Bank = config.ApplePayBankName;
// buyer account
payParam.PayAccount = "";
// buyer collection account bank
payParam.PayBank = "";
/ / Actual payment amount
Var order = OrderService.Instance.GetList(o => o.OrderNO == param.OrderNO).FirstOrDefault();
//Apple payment does not return the payment amount. In order to avoid the late verification, the total amount is set to the actual order amount.
payParam.TotalAmount = order.TotalAmount;
//Payment time
payParam.PayDate = DateTime.Now;
/ / Payment instrument type
payParam.PayType = PayTypeKind.ApplePay;
/ / Record payment vouchers to the running account
payParam.AppleReceipt = param.AppleReceipt;
OrderService.Instance.OrderPaySuccess(payParam);
Return true;
}
Else
{
Return false;
}
}
Else
{
Throw new Exception("This payment voucher has been used, please do not reuse");
}
}
Catch
{
Return false;
}
}
PhoneGap (Cordova) Custom Plugin Code chapter (i)----IAP in-app payment