UnityEarlyTransactionObserver.mm 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #import "UnityEarlyTransactionObserver.h"
  2. #import "UnityPurchasing.h"
  3. void Log(NSString *message) {
  4. NSLog(@"UnityIAP UnityEarlyTransactionObserver: %@\n", message);
  5. }
  6. @implementation UnityEarlyTransactionObserver
  7. static UnityEarlyTransactionObserver *s_Observer = nil;
  8. +(void)load {
  9. if (!s_Observer) {
  10. s_Observer = [[UnityEarlyTransactionObserver alloc] init];
  11. Log(@"Created");
  12. [s_Observer registerLifeCycleListener];
  13. }
  14. }
  15. + (UnityEarlyTransactionObserver*)defaultObserver {
  16. return s_Observer;
  17. }
  18. - (void)registerLifeCycleListener {
  19. UnityRegisterLifeCycleListener(self);
  20. Log(@"Registered for lifecycle events");
  21. }
  22. - (void)didFinishLaunching:(NSNotification*)notification {
  23. Log(@"Added to the payment queue");
  24. [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
  25. }
  26. - (void)setDelegate:(id<UnityEarlyTransactionObserverDelegate>)delegate {
  27. _delegate = delegate;
  28. [self sendQueuedPaymentsToInterceptor];
  29. }
  30. - (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product {
  31. Log(@"Payment queue shouldAddStorePayment");
  32. if (self.readyToReceiveTransactionUpdates && !self.delegate) {
  33. return YES;
  34. } else {
  35. if (m_QueuedPayments == nil) {
  36. m_QueuedPayments = [[NSMutableSet alloc] init];
  37. }
  38. // If there is a delegate and we have not seen this payment yet, it means we should intercept promotional purchases
  39. // and just return the payment to the delegate.
  40. // Do not try to process it now.
  41. if (self.delegate && [m_QueuedPayments member:payment] == nil) {
  42. [self.delegate promotionalPurchaseAttempted:payment];
  43. }
  44. [m_QueuedPayments addObject:payment];
  45. return NO;
  46. }
  47. return YES;
  48. }
  49. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {}
  50. - (void)initiateQueuedPayments {
  51. Log(@"Request to initiate queued payments");
  52. if (m_QueuedPayments != nil) {
  53. Log(@"Initiating queued payments");
  54. for (SKPayment *payment in m_QueuedPayments) {
  55. [[SKPaymentQueue defaultQueue] addPayment:payment];
  56. }
  57. [m_QueuedPayments removeAllObjects];
  58. }
  59. }
  60. - (void)sendQueuedPaymentsToInterceptor {
  61. Log(@"Request to send queued payments to interceptor");
  62. if (m_QueuedPayments != nil) {
  63. Log(@"Sending queued payments to interceptor");
  64. for (SKPayment *payment in m_QueuedPayments) {
  65. if (self.delegate) {
  66. [self.delegate promotionalPurchaseAttempted:payment];
  67. }
  68. }
  69. }
  70. }
  71. @end