in_app_store.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*************************************************************************/
  2. /* in_app_store.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifdef STOREKIT_ENABLED
  31. #include "in_app_store.h"
  32. extern "C" {
  33. #import <Foundation/Foundation.h>
  34. #import <StoreKit/StoreKit.h>
  35. };
  36. bool auto_finish_transactions = true;
  37. NSMutableDictionary *pending_transactions = [NSMutableDictionary dictionary];
  38. @interface SKProduct (LocalizedPrice)
  39. @property(nonatomic, readonly) NSString *localizedPrice;
  40. @end
  41. //----------------------------------//
  42. // SKProduct extension
  43. //----------------------------------//
  44. @implementation SKProduct (LocalizedPrice)
  45. - (NSString *)localizedPrice {
  46. NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
  47. [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
  48. [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
  49. [numberFormatter setLocale:self.priceLocale];
  50. NSString *formattedString = [numberFormatter stringFromNumber:self.price];
  51. [numberFormatter release];
  52. return formattedString;
  53. }
  54. @end
  55. InAppStore *InAppStore::instance = NULL;
  56. void InAppStore::_bind_methods() {
  57. ClassDB::bind_method(D_METHOD("request_product_info"), &InAppStore::request_product_info);
  58. ClassDB::bind_method(D_METHOD("restore_purchases"), &InAppStore::restore_purchases);
  59. ClassDB::bind_method(D_METHOD("purchase"), &InAppStore::purchase);
  60. ClassDB::bind_method(D_METHOD("get_pending_event_count"), &InAppStore::get_pending_event_count);
  61. ClassDB::bind_method(D_METHOD("pop_pending_event"), &InAppStore::pop_pending_event);
  62. ClassDB::bind_method(D_METHOD("finish_transaction"), &InAppStore::finish_transaction);
  63. ClassDB::bind_method(D_METHOD("set_auto_finish_transaction"), &InAppStore::set_auto_finish_transaction);
  64. };
  65. @interface ProductsDelegate : NSObject <SKProductsRequestDelegate> {
  66. };
  67. @end
  68. @implementation ProductsDelegate
  69. - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
  70. NSArray *products = response.products;
  71. Dictionary ret;
  72. ret["type"] = "product_info";
  73. ret["result"] = "ok";
  74. PoolStringArray titles;
  75. PoolStringArray descriptions;
  76. PoolRealArray prices;
  77. PoolStringArray ids;
  78. PoolStringArray localized_prices;
  79. PoolStringArray currency_codes;
  80. for (int i = 0; i < [products count]; i++) {
  81. SKProduct *product = [products objectAtIndex:i];
  82. const char *str = [product.localizedTitle UTF8String];
  83. titles.push_back(String::utf8(str != NULL ? str : ""));
  84. str = [product.localizedDescription UTF8String];
  85. descriptions.push_back(String::utf8(str != NULL ? str : ""));
  86. prices.push_back([product.price doubleValue]);
  87. ids.push_back(String::utf8([product.productIdentifier UTF8String]));
  88. localized_prices.push_back(String::utf8([product.localizedPrice UTF8String]));
  89. currency_codes.push_back(String::utf8([[[product priceLocale] objectForKey:NSLocaleCurrencyCode] UTF8String]));
  90. };
  91. ret["titles"] = titles;
  92. ret["descriptions"] = descriptions;
  93. ret["prices"] = prices;
  94. ret["ids"] = ids;
  95. ret["localized_prices"] = localized_prices;
  96. ret["currency_codes"] = currency_codes;
  97. PoolStringArray invalid_ids;
  98. for (NSString *ipid in response.invalidProductIdentifiers) {
  99. invalid_ids.push_back(String::utf8([ipid UTF8String]));
  100. };
  101. ret["invalid_ids"] = invalid_ids;
  102. InAppStore::get_singleton()->_post_event(ret);
  103. [request release];
  104. };
  105. @end
  106. Error InAppStore::request_product_info(Variant p_params) {
  107. Dictionary params = p_params;
  108. ERR_FAIL_COND_V(!params.has("product_ids"), ERR_INVALID_PARAMETER);
  109. PoolStringArray pids = params["product_ids"];
  110. printf("************ request product info! %i\n", pids.size());
  111. NSMutableArray *array = [[[NSMutableArray alloc] initWithCapacity:pids.size()] autorelease];
  112. for (int i = 0; i < pids.size(); i++) {
  113. printf("******** adding %ls to product list\n", pids[i].c_str());
  114. NSString *pid = [[[NSString alloc] initWithUTF8String:pids[i].utf8().get_data()] autorelease];
  115. [array addObject:pid];
  116. };
  117. NSSet *products = [[[NSSet alloc] initWithArray:array] autorelease];
  118. SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:products];
  119. ProductsDelegate *delegate = [[ProductsDelegate alloc] init];
  120. request.delegate = delegate;
  121. [request start];
  122. return OK;
  123. };
  124. Error InAppStore::restore_purchases() {
  125. printf("restoring purchases!\n");
  126. [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
  127. return OK;
  128. };
  129. @interface TransObserver : NSObject <SKPaymentTransactionObserver> {
  130. };
  131. @end
  132. @implementation TransObserver
  133. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
  134. printf("transactions updated!\n");
  135. for (SKPaymentTransaction *transaction in transactions) {
  136. switch (transaction.transactionState) {
  137. case SKPaymentTransactionStatePurchased: {
  138. printf("status purchased!\n");
  139. String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
  140. String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]);
  141. InAppStore::get_singleton()->_record_purchase(pid);
  142. Dictionary ret;
  143. ret["type"] = "purchase";
  144. ret["result"] = "ok";
  145. ret["product_id"] = pid;
  146. ret["transaction_id"] = transactionId;
  147. NSData *receipt = nil;
  148. int sdk_version = 6;
  149. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
  150. NSURL *receiptFileURL = nil;
  151. NSBundle *bundle = [NSBundle mainBundle];
  152. if ([bundle respondsToSelector:@selector(appStoreReceiptURL)]) {
  153. // Get the transaction receipt file path location in the app bundle.
  154. receiptFileURL = [bundle appStoreReceiptURL];
  155. // Read in the contents of the transaction file.
  156. receipt = [NSData dataWithContentsOfURL:receiptFileURL];
  157. sdk_version = 7;
  158. } else {
  159. // Fall back to deprecated transaction receipt,
  160. // which is still available in iOS 7.
  161. // Use SKPaymentTransaction's transactionReceipt.
  162. receipt = transaction.transactionReceipt;
  163. }
  164. } else {
  165. receipt = transaction.transactionReceipt;
  166. }
  167. NSString *receipt_to_send = nil;
  168. if (receipt != nil) {
  169. receipt_to_send = [receipt description];
  170. }
  171. Dictionary receipt_ret;
  172. receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : "");
  173. receipt_ret["sdk"] = sdk_version;
  174. ret["receipt"] = receipt_ret;
  175. InAppStore::get_singleton()->_post_event(ret);
  176. if (auto_finish_transactions) {
  177. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  178. } else {
  179. [pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier];
  180. }
  181. }; break;
  182. case SKPaymentTransactionStateFailed: {
  183. printf("status transaction failed!\n");
  184. String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
  185. Dictionary ret;
  186. ret["type"] = "purchase";
  187. ret["result"] = "error";
  188. ret["product_id"] = pid;
  189. InAppStore::get_singleton()->_post_event(ret);
  190. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  191. } break;
  192. case SKPaymentTransactionStateRestored: {
  193. printf("status transaction restored!\n");
  194. String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]);
  195. InAppStore::get_singleton()->_record_purchase(pid);
  196. Dictionary ret;
  197. ret["type"] = "restore";
  198. ret["result"] = "ok";
  199. ret["product_id"] = pid;
  200. InAppStore::get_singleton()->_post_event(ret);
  201. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  202. } break;
  203. default: {
  204. printf("status default %i!\n", (int)transaction.transactionState);
  205. }; break;
  206. };
  207. };
  208. };
  209. @end
  210. Error InAppStore::purchase(Variant p_params) {
  211. ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE);
  212. if (![SKPaymentQueue canMakePayments])
  213. return ERR_UNAVAILABLE;
  214. printf("purchasing!\n");
  215. Dictionary params = p_params;
  216. ERR_FAIL_COND_V(!params.has("product_id"), ERR_INVALID_PARAMETER);
  217. NSString *pid = [[[NSString alloc] initWithUTF8String:String(params["product_id"]).utf8().get_data()] autorelease];
  218. SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid];
  219. SKPaymentQueue *defq = [SKPaymentQueue defaultQueue];
  220. [defq addPayment:payment];
  221. printf("purchase sent!\n");
  222. return OK;
  223. };
  224. int InAppStore::get_pending_event_count() {
  225. return pending_events.size();
  226. };
  227. Variant InAppStore::pop_pending_event() {
  228. Variant front = pending_events.front()->get();
  229. pending_events.pop_front();
  230. return front;
  231. };
  232. void InAppStore::_post_event(Variant p_event) {
  233. pending_events.push_back(p_event);
  234. };
  235. void InAppStore::_record_purchase(String product_id) {
  236. String skey = "purchased/" + product_id;
  237. NSString *key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease];
  238. [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
  239. [[NSUserDefaults standardUserDefaults] synchronize];
  240. };
  241. InAppStore *InAppStore::get_singleton() {
  242. return instance;
  243. };
  244. InAppStore::InAppStore() {
  245. ERR_FAIL_COND(instance != NULL);
  246. instance = this;
  247. auto_finish_transactions = false;
  248. TransObserver *observer = [[TransObserver alloc] init];
  249. [[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
  250. //pending_transactions = [NSMutableDictionary dictionary];
  251. };
  252. void InAppStore::finish_transaction(String product_id) {
  253. NSString *prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding];
  254. if ([pending_transactions objectForKey:prod_id]) {
  255. [[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]];
  256. [pending_transactions removeObjectForKey:prod_id];
  257. }
  258. };
  259. void InAppStore::set_auto_finish_transaction(bool b) {
  260. auto_finish_transactions = b;
  261. }
  262. InAppStore::~InAppStore(){};
  263. #endif