godot/platform/iphone/in_app_store.mm

345 lines
12 KiB
Plaintext
Raw Normal View History

2014-02-10 01:10:30 +00:00
/*************************************************************************/
/* in_app_store.mm */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
2014-02-10 01:10:30 +00:00
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
2014-02-10 01:10:30 +00:00
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
2014-02-10 01:10:30 +00:00
#ifdef STOREKIT_ENABLED
#include "in_app_store.h"
2014-02-10 01:10:30 +00:00
extern "C" {
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
2014-02-10 01:10:30 +00:00
};
bool auto_finish_transactions = true;
NSMutableDictionary *pending_transactions = [NSMutableDictionary dictionary];
static NSArray *latestProducts;
2014-02-10 01:10:30 +00:00
@interface SKProduct (LocalizedPrice)
@property(nonatomic, readonly) NSString *localizedPrice;
2014-02-10 01:10:30 +00:00
@end
//----------------------------------//
// SKProduct extension
//----------------------------------//
@implementation SKProduct (LocalizedPrice)
2017-04-09 11:22:40 +00:00
- (NSString *)localizedPrice {
2014-02-10 01:10:30 +00:00
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:self.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:self.price];
[numberFormatter release];
return formattedString;
}
2014-02-10 01:10:30 +00:00
@end
InAppStore *InAppStore::instance = NULL;
2014-02-10 01:10:30 +00:00
void InAppStore::_bind_methods() {
ClassDB::bind_method(D_METHOD("request_product_info"), &InAppStore::request_product_info);
2018-02-22 19:28:37 +00:00
ClassDB::bind_method(D_METHOD("restore_purchases"), &InAppStore::restore_purchases);
ClassDB::bind_method(D_METHOD("purchase"), &InAppStore::purchase);
2014-02-10 01:10:30 +00:00
ClassDB::bind_method(D_METHOD("get_pending_event_count"), &InAppStore::get_pending_event_count);
ClassDB::bind_method(D_METHOD("pop_pending_event"), &InAppStore::pop_pending_event);
ClassDB::bind_method(D_METHOD("finish_transaction"), &InAppStore::finish_transaction);
ClassDB::bind_method(D_METHOD("set_auto_finish_transaction"), &InAppStore::set_auto_finish_transaction);
2014-02-10 01:10:30 +00:00
};
@interface ProductsDelegate : NSObject <SKProductsRequestDelegate> {
2014-02-10 01:10:30 +00:00
};
@end
@implementation ProductsDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray *products = response.products;
latestProducts = products;
2014-02-10 01:10:30 +00:00
Dictionary ret;
ret["type"] = "product_info";
ret["result"] = "ok";
PackedStringArray titles;
PackedStringArray descriptions;
PackedFloat32Array prices;
PackedStringArray ids;
PackedStringArray localized_prices;
PackedStringArray currency_codes;
2014-02-10 01:10:30 +00:00
for (NSUInteger i = 0; i < [products count]; i++) {
SKProduct *product = [products objectAtIndex:i];
2014-02-10 01:10:30 +00:00
const char *str = [product.localizedTitle UTF8String];
2014-02-10 01:10:30 +00:00
titles.push_back(String::utf8(str != NULL ? str : ""));
str = [product.localizedDescription UTF8String];
descriptions.push_back(String::utf8(str != NULL ? str : ""));
prices.push_back([product.price doubleValue]);
ids.push_back(String::utf8([product.productIdentifier UTF8String]));
localized_prices.push_back(String::utf8([product.localizedPrice UTF8String]));
currency_codes.push_back(String::utf8([[[product priceLocale] objectForKey:NSLocaleCurrencyCode] UTF8String]));
2014-02-10 01:10:30 +00:00
};
ret["titles"] = titles;
ret["descriptions"] = descriptions;
ret["prices"] = prices;
ret["ids"] = ids;
ret["localized_prices"] = localized_prices;
ret["currency_codes"] = currency_codes;
2014-02-10 01:10:30 +00:00
PackedStringArray invalid_ids;
2014-02-10 01:10:30 +00:00
for (NSString *ipid in response.invalidProductIdentifiers) {
2014-02-10 01:10:30 +00:00
invalid_ids.push_back(String::utf8([ipid UTF8String]));
};
ret["invalid_ids"] = invalid_ids;
InAppStore::get_singleton()->_post_event(ret);
[request release];
};
@end
Error InAppStore::request_product_info(Dictionary p_params) {
ERR_FAIL_COND_V(!p_params.has("product_ids"), ERR_INVALID_PARAMETER);
2014-02-10 01:10:30 +00:00
PackedStringArray pids = p_params["product_ids"];
2014-02-10 01:10:30 +00:00
printf("************ request product info! %i\n", pids.size());
NSMutableArray *array = [[[NSMutableArray alloc] initWithCapacity:pids.size()] autorelease];
for (int i = 0; i < pids.size(); i++) {
printf("******** adding %s to product list\n", pids[i].utf8().get_data());
NSString *pid = [[[NSString alloc] initWithUTF8String:pids[i].utf8().get_data()] autorelease];
2014-02-10 01:10:30 +00:00
[array addObject:pid];
};
NSSet *products = [[[NSSet alloc] initWithArray:array] autorelease];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:products];
2014-02-10 01:10:30 +00:00
ProductsDelegate *delegate = [[ProductsDelegate alloc] init];
request.delegate = delegate;
[request start];
return OK;
};
2018-02-22 19:28:37 +00:00
Error InAppStore::restore_purchases() {
printf("restoring purchases!\n");
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
return OK;
};
@interface TransObserver : NSObject <SKPaymentTransactionObserver> {
2014-02-10 01:10:30 +00:00
};
@end
@implementation TransObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
2017-04-09 11:22:40 +00:00
printf("transactions updated!\n");
for (SKPaymentTransaction *transaction in transactions) {
2014-02-10 01:10:30 +00:00
switch (transaction.transactionState) {
2017-04-09 11:22:40 +00:00
case SKPaymentTransactionStatePurchased: {
printf("status purchased!\n");
String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]);
InAppStore::get_singleton()->_record_purchase(pid);
Dictionary ret;
ret["type"] = "purchase";
ret["result"] = "ok";
ret["product_id"] = pid;
ret["transaction_id"] = transactionId;
NSData *receipt = nil;
2017-04-09 11:22:40 +00:00
int sdk_version = 6;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
2017-04-09 11:22:40 +00:00
NSURL *receiptFileURL = nil;
NSBundle *bundle = [NSBundle mainBundle];
if ([bundle respondsToSelector:@selector(appStoreReceiptURL)]) {
// Get the transaction receipt file path location in the app bundle.
receiptFileURL = [bundle appStoreReceiptURL];
// Read in the contents of the transaction file.
receipt = [NSData dataWithContentsOfURL:receiptFileURL];
sdk_version = 7;
} else {
// Fall back to deprecated transaction receipt,
// which is still available in iOS 7.
// Use SKPaymentTransaction's transactionReceipt.
receipt = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
2017-04-09 11:22:40 +00:00
}
} else {
receipt = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
2017-04-09 11:22:40 +00:00
}
NSString *receipt_to_send = nil;
2017-04-09 11:22:40 +00:00
if (receipt != nil) {
receipt_to_send = [receipt base64EncodedStringWithOptions:0];
2017-04-09 11:22:40 +00:00
}
Dictionary receipt_ret;
receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : "");
receipt_ret["sdk"] = sdk_version;
ret["receipt"] = receipt_ret;
InAppStore::get_singleton()->_post_event(ret);
if (auto_finish_transactions) {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} else {
[pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier];
2017-04-09 11:22:40 +00:00
}
2014-02-10 01:10:30 +00:00
2017-04-09 11:22:40 +00:00
}; break;
case SKPaymentTransactionStateFailed: {
printf("status transaction failed!\n");
String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
Dictionary ret;
ret["type"] = "purchase";
ret["result"] = "error";
ret["product_id"] = pid;
ret["error"] = String::utf8([transaction.error.localizedDescription UTF8String]);
2017-04-09 11:22:40 +00:00
InAppStore::get_singleton()->_post_event(ret);
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} break;
case SKPaymentTransactionStateRestored: {
printf("status transaction restored!\n");
String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]);
InAppStore::get_singleton()->_record_purchase(pid);
2018-02-22 19:28:37 +00:00
Dictionary ret;
ret["type"] = "restore";
ret["result"] = "ok";
ret["product_id"] = pid;
InAppStore::get_singleton()->_post_event(ret);
2017-04-09 11:22:40 +00:00
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} break;
default: {
printf("status default %i!\n", (int)transaction.transactionState);
}; break;
2014-02-10 01:10:30 +00:00
};
};
};
@end
Error InAppStore::purchase(Dictionary p_params) {
2014-02-10 01:10:30 +00:00
ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE);
if (![SKPaymentQueue canMakePayments])
return ERR_UNAVAILABLE;
2017-04-09 11:22:40 +00:00
printf("purchasing!\n");
ERR_FAIL_COND_V(!p_params.has("product_id"), ERR_INVALID_PARAMETER);
NSString *pid = [[[NSString alloc] initWithUTF8String:String(p_params["product_id"]).utf8().get_data()] autorelease];
SKProduct *product = nil;
if (latestProducts) {
for (SKProduct *storedProduct in latestProducts) {
if ([storedProduct.productIdentifier isEqualToString:pid]) {
product = storedProduct;
break;
}
}
}
if (!product) {
return ERR_INVALID_PARAMETER;
}
2014-02-10 01:10:30 +00:00
SKPayment *payment = [SKPayment paymentWithProduct:product];
SKPaymentQueue *defq = [SKPaymentQueue defaultQueue];
2014-02-10 01:10:30 +00:00
[defq addPayment:payment];
2017-04-09 11:22:40 +00:00
printf("purchase sent!\n");
2014-02-10 01:10:30 +00:00
return OK;
};
int InAppStore::get_pending_event_count() {
return pending_events.size();
};
Variant InAppStore::pop_pending_event() {
Variant front = pending_events.front()->get();
pending_events.pop_front();
return front;
};
void InAppStore::_post_event(Variant p_event) {
pending_events.push_back(p_event);
};
void InAppStore::_record_purchase(String product_id) {
String skey = "purchased/" + product_id;
NSString *key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease];
2014-02-10 01:10:30 +00:00
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
};
InAppStore *InAppStore::get_singleton() {
2014-02-10 01:10:30 +00:00
return instance;
};
InAppStore::InAppStore() {
ERR_FAIL_COND(instance != NULL);
instance = this;
auto_finish_transactions = false;
2014-02-10 01:10:30 +00:00
TransObserver *observer = [[TransObserver alloc] init];
2014-02-10 01:10:30 +00:00
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
//pending_transactions = [NSMutableDictionary dictionary];
2014-02-10 01:10:30 +00:00
};
void InAppStore::finish_transaction(String product_id) {
NSString *prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding];
2016-04-02 18:26:12 +00:00
if ([pending_transactions objectForKey:prod_id]) {
[[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]];
2017-04-09 11:22:40 +00:00
[pending_transactions removeObjectForKey:prod_id];
}
};
void InAppStore::set_auto_finish_transaction(bool b) {
2017-04-09 11:22:40 +00:00
auto_finish_transactions = b;
}
InAppStore::~InAppStore() {}
2014-02-10 01:10:30 +00:00
#endif