in_app_store.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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. #import <Foundation/Foundation.h>
  33. #import <StoreKit/StoreKit.h>
  34. bool auto_finish_transactions = true;
  35. NSMutableDictionary *pending_transactions = [NSMutableDictionary dictionary];
  36. @interface SKProduct (LocalizedPrice)
  37. @property(nonatomic, readonly) NSString *localizedPrice;
  38. @end
  39. //----------------------------------//
  40. // SKProduct extension
  41. //----------------------------------//
  42. @implementation SKProduct (LocalizedPrice)
  43. - (NSString *)localizedPrice {
  44. NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
  45. [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
  46. [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
  47. [numberFormatter setLocale:self.priceLocale];
  48. NSString *formattedString = [numberFormatter stringFromNumber:self.price];
  49. [numberFormatter release];
  50. return formattedString;
  51. }
  52. @end
  53. InAppStore *InAppStore::instance = NULL;
  54. void InAppStore::_bind_methods() {
  55. ClassDB::bind_method(D_METHOD("request_product_info"), &InAppStore::request_product_info);
  56. ClassDB::bind_method(D_METHOD("restore_purchases"), &InAppStore::restore_purchases);
  57. ClassDB::bind_method(D_METHOD("purchase"), &InAppStore::purchase);
  58. ClassDB::bind_method(D_METHOD("get_pending_event_count"), &InAppStore::get_pending_event_count);
  59. ClassDB::bind_method(D_METHOD("pop_pending_event"), &InAppStore::pop_pending_event);
  60. ClassDB::bind_method(D_METHOD("finish_transaction"), &InAppStore::finish_transaction);
  61. ClassDB::bind_method(D_METHOD("set_auto_finish_transaction"), &InAppStore::set_auto_finish_transaction);
  62. };
  63. @interface ProductsDelegate : NSObject <SKProductsRequestDelegate> {
  64. };
  65. @end
  66. @implementation ProductsDelegate
  67. - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
  68. NSArray *products = response.products;
  69. Dictionary ret;
  70. ret["type"] = "product_info";
  71. ret["result"] = "ok";
  72. PoolStringArray titles;
  73. PoolStringArray descriptions;
  74. PoolRealArray prices;
  75. PoolStringArray ids;
  76. PoolStringArray localized_prices;
  77. PoolStringArray currency_codes;
  78. for (NSUInteger i = 0; i < [products count]; i++) {
  79. SKProduct *product = [products objectAtIndex:i];
  80. const char *str = [product.localizedTitle UTF8String];
  81. titles.push_back(String::utf8(str != NULL ? str : ""));
  82. str = [product.localizedDescription UTF8String];
  83. descriptions.push_back(String::utf8(str != NULL ? str : ""));
  84. prices.push_back([product.price doubleValue]);
  85. ids.push_back(String::utf8([product.productIdentifier UTF8String]));
  86. localized_prices.push_back(String::utf8([product.localizedPrice UTF8String]));
  87. currency_codes.push_back(String::utf8([[[product priceLocale] objectForKey:NSLocaleCurrencyCode] UTF8String]));
  88. };
  89. ret["titles"] = titles;
  90. ret["descriptions"] = descriptions;
  91. ret["prices"] = prices;
  92. ret["ids"] = ids;
  93. ret["localized_prices"] = localized_prices;
  94. ret["currency_codes"] = currency_codes;
  95. PoolStringArray invalid_ids;
  96. for (NSString *ipid in response.invalidProductIdentifiers) {
  97. invalid_ids.push_back(String::utf8([ipid UTF8String]));
  98. };
  99. ret["invalid_ids"] = invalid_ids;
  100. InAppStore::get_singleton()->_post_event(ret);
  101. [request release];
  102. };
  103. @end
  104. Error InAppStore::request_product_info(Variant p_params) {
  105. Dictionary params = p_params;
  106. ERR_FAIL_COND_V(!params.has("product_ids"), ERR_INVALID_PARAMETER);
  107. PoolStringArray pids = params["product_ids"];
  108. printf("************ request product info! %i\n", pids.size());
  109. NSMutableArray *array = [[[NSMutableArray alloc] initWithCapacity:pids.size()] autorelease];
  110. for (int i = 0; i < pids.size(); i++) {
  111. printf("******** adding %ls to product list\n", pids[i].c_str());
  112. NSString *pid = [[[NSString alloc] initWithUTF8String:pids[i].utf8().get_data()] autorelease];
  113. [array addObject:pid];
  114. };
  115. NSSet *products = [[[NSSet alloc] initWithArray:array] autorelease];
  116. SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:products];
  117. ProductsDelegate *delegate = [[ProductsDelegate alloc] init];
  118. request.delegate = delegate;
  119. [request start];
  120. return OK;
  121. };
  122. Error InAppStore::restore_purchases() {
  123. printf("restoring purchases!\n");
  124. [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
  125. return OK;
  126. };
  127. @interface TransObserver : NSObject <SKPaymentTransactionObserver> {
  128. };
  129. @end
  130. @implementation TransObserver
  131. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
  132. printf("transactions updated!\n");
  133. for (SKPaymentTransaction *transaction in transactions) {
  134. switch (transaction.transactionState) {
  135. case SKPaymentTransactionStatePurchased: {
  136. printf("status purchased!\n");
  137. String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
  138. String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]);
  139. InAppStore::get_singleton()->_record_purchase(pid);
  140. Dictionary ret;
  141. ret["type"] = "purchase";
  142. ret["result"] = "ok";
  143. ret["product_id"] = pid;
  144. ret["transaction_id"] = transactionId;
  145. NSData *receipt = nil;
  146. int sdk_version = 6;
  147. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
  148. NSURL *receiptFileURL = nil;
  149. NSBundle *bundle = [NSBundle mainBundle];
  150. if ([bundle respondsToSelector:@selector(appStoreReceiptURL)]) {
  151. // Get the transaction receipt file path location in the app bundle.
  152. receiptFileURL = [bundle appStoreReceiptURL];
  153. // Read in the contents of the transaction file.
  154. receipt = [NSData dataWithContentsOfURL:receiptFileURL];
  155. sdk_version = 7;
  156. } else {
  157. // Fall back to deprecated transaction receipt,
  158. // which is still available in iOS 7.
  159. // Use SKPaymentTransaction's transactionReceipt.
  160. receipt = transaction.transactionReceipt;
  161. }
  162. } else {
  163. receipt = transaction.transactionReceipt;
  164. }
  165. NSString *receipt_to_send = nil;
  166. if (receipt != nil) {
  167. receipt_to_send = [receipt base64EncodedStringWithOptions:0];
  168. }
  169. Dictionary receipt_ret;
  170. receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : "");
  171. receipt_ret["sdk"] = sdk_version;
  172. ret["receipt"] = receipt_ret;
  173. InAppStore::get_singleton()->_post_event(ret);
  174. if (auto_finish_transactions) {
  175. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  176. } else {
  177. [pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier];
  178. }
  179. }; break;
  180. case SKPaymentTransactionStateFailed: {
  181. printf("status transaction failed!\n");
  182. String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
  183. Dictionary ret;
  184. ret["type"] = "purchase";
  185. ret["result"] = "error";
  186. ret["product_id"] = pid;
  187. ret["error"] = String::utf8([transaction.error.localizedDescription UTF8String]);
  188. InAppStore::get_singleton()->_post_event(ret);
  189. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  190. } break;
  191. case SKPaymentTransactionStateRestored: {
  192. printf("status transaction restored!\n");
  193. String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]);
  194. InAppStore::get_singleton()->_record_purchase(pid);
  195. Dictionary ret;
  196. ret["type"] = "restore";
  197. ret["result"] = "ok";
  198. ret["product_id"] = pid;
  199. InAppStore::get_singleton()->_post_event(ret);
  200. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  201. } break;
  202. default: {
  203. printf("status default %i!\n", (int)transaction.transactionState);
  204. }; break;
  205. };
  206. };
  207. };
  208. @end
  209. Error InAppStore::purchase(Variant p_params) {
  210. ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE);
  211. if (![SKPaymentQueue canMakePayments])
  212. return ERR_UNAVAILABLE;
  213. printf("purchasing!\n");
  214. Dictionary params = p_params;
  215. ERR_FAIL_COND_V(!params.has("product_id"), ERR_INVALID_PARAMETER);
  216. NSString *pid = [[[NSString alloc] initWithUTF8String:String(params["product_id"]).utf8().get_data()] autorelease];
  217. SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid];
  218. SKPaymentQueue *defq = [SKPaymentQueue defaultQueue];
  219. [defq addPayment:payment];
  220. printf("purchase sent!\n");
  221. return OK;
  222. };
  223. int InAppStore::get_pending_event_count() {
  224. return pending_events.size();
  225. };
  226. Variant InAppStore::pop_pending_event() {
  227. Variant front = pending_events.front()->get();
  228. pending_events.pop_front();
  229. return front;
  230. };
  231. void InAppStore::_post_event(Variant p_event) {
  232. pending_events.push_back(p_event);
  233. };
  234. void InAppStore::_record_purchase(String product_id) {
  235. String skey = "purchased/" + product_id;
  236. NSString *key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease];
  237. [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
  238. [[NSUserDefaults standardUserDefaults] synchronize];
  239. };
  240. InAppStore *InAppStore::get_singleton() {
  241. return instance;
  242. };
  243. InAppStore::InAppStore() {
  244. ERR_FAIL_COND(instance != NULL);
  245. instance = this;
  246. auto_finish_transactions = false;
  247. TransObserver *observer = [[TransObserver alloc] init];
  248. [[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
  249. //pending_transactions = [NSMutableDictionary dictionary];
  250. };
  251. void InAppStore::finish_transaction(String product_id) {
  252. NSString *prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding];
  253. if ([pending_transactions objectForKey:prod_id]) {
  254. [[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]];
  255. [pending_transactions removeObjectForKey:prod_id];
  256. }
  257. };
  258. void InAppStore::set_auto_finish_transaction(bool b) {
  259. auto_finish_transactions = b;
  260. }
  261. InAppStore::~InAppStore(){};
  262. #endif