IOSIAP.m 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /****************************************************************************
  2. Copyright (c) 2013 cocos2d-x.org
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #import "IOSIAP.h"
  21. #define OUTPUT_LOG(...) if (self.debug) NSLog(__VA_ARGS__);
  22. @implementation IOSIAP
  23. @synthesize debug,_isServerMode;
  24. NSSet * _productIdentifiers;
  25. NSArray *_productArray;
  26. bool _isAddObserver = false;
  27. //productsRequest;
  28. SKProductsRequest * _productsRequest;
  29. //productTransation
  30. NSArray * _transactionArray;
  31. -(void) configDeveloperInfo: (NSMutableDictionary*) cpInfo{
  32. }
  33. - (void) payForProduct: (NSMutableDictionary*) cpInfo{
  34. NSString * pid = [cpInfo objectForKey:@"productId"];
  35. SKProduct *skProduct = [self getProductById:pid];
  36. if(skProduct){
  37. SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:skProduct];
  38. [[SKPaymentQueue defaultQueue] addPayment:payment];
  39. OUTPUT_LOG(@"add PaymentQueue");
  40. }
  41. }
  42. - (void) setDebugMode: (BOOL) _debug{
  43. self.debug = _debug;
  44. }
  45. - (NSString*) getSDKVersion{
  46. return @"1.0";
  47. }
  48. - (NSString*) getPluginVersion{
  49. return @"1.0";
  50. }
  51. /*------------------------IAP functions-------------------------------*/
  52. -(void)setServerMode{
  53. _isServerMode = true;
  54. }
  55. -(void)requestProducts:(NSString*) paramMap{
  56. [self setDebug:true];
  57. if(!_isAddObserver){
  58. [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
  59. _isAddObserver = true;
  60. }
  61. NSArray *producIdArray = [paramMap componentsSeparatedByString:@","];
  62. _productIdentifiers = [[NSSet alloc] initWithArray:producIdArray];
  63. OUTPUT_LOG(@"param is %@",_productIdentifiers);
  64. _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:_productIdentifiers];
  65. _productsRequest.delegate = self;
  66. [_productsRequest start];
  67. }
  68. -(NSString *)parseProductToString:(NSArray *) products{
  69. return @"1";
  70. }
  71. -(SKProduct *)getProductById:(NSString *)productid{
  72. for (SKProduct * skProduct in _productArray) {
  73. if([skProduct.productIdentifier isEqualToString:productid]){
  74. return skProduct;
  75. }
  76. }
  77. return NULL;
  78. }
  79. - (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
  80. OUTPUT_LOG(@"Failed to load list of products.");
  81. [IAPWrapper onRequestProduct:self withRet:RequestFail withProducts:NULL];
  82. _productsRequest = nil;
  83. }
  84. //SKProductsRequestDelegate needed
  85. - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
  86. _productArray = response.products;
  87. NSArray * skProducts = response.products;
  88. for (SKProduct * skProduct in skProducts) {
  89. OUTPUT_LOG(@"Found product: %@ %@ %0.2f",
  90. skProduct.productIdentifier,
  91. skProduct.localizedTitle,
  92. skProduct.price.floatValue);
  93. }
  94. [IAPWrapper onRequestProduct:self withRet:RequestSuccees withProducts:skProducts];
  95. }
  96. //SKPaymentTransactionObserver needed
  97. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
  98. _transactionArray = transactions;
  99. for (SKPaymentTransaction * transaction in transactions) {
  100. switch (transaction.transactionState)
  101. {
  102. case SKPaymentTransactionStatePurchased:
  103. [self completeTransaction:transaction];
  104. break;
  105. case SKPaymentTransactionStateFailed:
  106. [self failedTransaction:transaction];
  107. break;
  108. case SKPaymentTransactionStateRestored:
  109. [self restoreTransaction:transaction];
  110. default:
  111. break;
  112. }
  113. };
  114. }
  115. - (void)completeTransaction:(SKPaymentTransaction *)transaction {
  116. NSString *receipt = nil;
  117. if(_isServerMode){
  118. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
  119. // iOS 6.1 or earlier.
  120. // Use SKPaymentTransaction's transactionReceipt.
  121. receipt = [self encode:(uint8_t *)transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length];
  122. } else {
  123. // iOS 7 or later.
  124. NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
  125. NSData *recData = [[NSData dataWithContentsOfURL:receiptURL] base64EncodedDataWithOptions:0];
  126. receipt = [[NSString alloc] initWithData:recData encoding:NSUTF8StringEncoding];
  127. if (!receipt) {
  128. receipt = [self encode:(uint8_t *)transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length];
  129. }
  130. }
  131. [IAPWrapper onPayResult:self withRet:PaymentTransactionStatePurchased withMsg:receipt];
  132. }else{
  133. [self finishTransaction: transaction.payment.productIdentifier];
  134. [IAPWrapper onPayResult:self withRet:PaymentTransactionStatePurchased withMsg:@""];
  135. }
  136. }
  137. - (void)restoreTransaction:(SKPaymentTransaction *)transaction {
  138. OUTPUT_LOG(@"restoreTransaction...");
  139. [self finishTransaction:transaction.payment.productIdentifier];
  140. [IAPWrapper onPayResult:self withRet:PaymentTransactionStateRestored withMsg:@""];
  141. }
  142. - (void)failedTransaction:(SKPaymentTransaction *)transaction {
  143. OUTPUT_LOG(@"failedTransaction...");
  144. if (transaction.error.code != SKErrorPaymentCancelled)
  145. {
  146. OUTPUT_LOG(@"Transaction error: %@", transaction.error.localizedDescription);
  147. [[[UIAlertView alloc] initWithTitle:@"支付结果" message:transaction.error.localizedDescription delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] show];
  148. }
  149. [self finishTransaction:transaction.payment.productIdentifier];
  150. [IAPWrapper onPayResult:self withRet:PaymentTransactionStateFailed withMsg:@""];
  151. }
  152. - (void)restoreCompletedTransactions {
  153. [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
  154. }
  155. -(void) finishTransaction:(NSString *)productId{
  156. SKPaymentTransaction *transaction = [self getTranscationByProductId:productId];
  157. if(transaction){
  158. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  159. }
  160. }
  161. -(SKPaymentTransaction *) getTranscationByProductId:(NSString *)productId{
  162. for(SKPaymentTransaction *tran in _transactionArray){
  163. if([tran.payment.productIdentifier isEqualToString:productId]){
  164. return tran;
  165. }
  166. }
  167. return NULL;
  168. }
  169. - (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
  170. static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  171. NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
  172. uint8_t *output = (uint8_t *)data.mutableBytes;
  173. for (NSInteger i = 0; i < length; i += 3) {
  174. NSInteger value = 0;
  175. for (NSInteger j = i; j < (i + 3); j++) {
  176. value <<= 8;
  177. if (j < length) {
  178. value |= (0xFF & input[j]);
  179. }
  180. }
  181. NSInteger index = (i / 3) * 4;
  182. output[index + 0] = table[(value >> 18) & 0x3F];
  183. output[index + 1] = table[(value >> 12) & 0x3F];
  184. output[index + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
  185. output[index + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
  186. }
  187. return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] ;
  188. }
  189. @end