verify receipt send to server

iOS 2015. 8. 14. 00:19
반응형

//

//  ViewController.m

//  PaymentTest01

//

//  Created by smilejsu on 2015. 8. 13..

//  Copyright (c) 2015 smilejsu. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()

    

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    _btnBuynow.enabled = NO;

    

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

    

    NSSet *productID = [NSSet setWithObject:@"smilejsu.iap.coinpack"];

    

    SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers: productID];

    

    request.delegate = self;

    

    [request start];

}


/*

 아래 같은 방식으로 smsURL이라는 주소로 post 형식으로 데이터를 감싸 전송이 가능해진다.

 */

- (void)sendToServer:(NSData*)data

{

    NSURL *aUrl = [NSURL URLWithString:@"http://smilejsu.iptime.org:8080/VerifyReceipt"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl

                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:60.0];

    

    [request setHTTPMethod:@"POST"];

    NSString *postString = [[NSString alloc] initWithFormat:@"content=%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];//@"content=AWESOME!";

    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    

    NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request

                                                                 delegate:self];

}


-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@",returnString);

}


-(void) paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error {

    NSLog(@"%@", [error localizedDescription]);

}


-(void) paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {

    for( SKPaymentTransaction *transaction in transactions ){

        switch (transaction.transactionState) {

            case SKPaymentTransactionStatePurchased:

                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                [self validateReceipt];

                break;

                

            case SKPaymentTransactionStateRestored:

                [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

                break;

                

            case SKPaymentTransactionStateFailed:

                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                break;

                

            default:

                break;

        }

    }

}


-(void) validateReceipt {

    

    // Load the receipt from the app bundle.

    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];

    NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];

    if (!receipt) { /* No local receipt -- handle the error. */ }

    

    /* ... Send the receipt data to your server ... */

    NSLog(@"Send the receipt data to your server");

    

    // Create the JSON object that describes the request

    NSError *error;

    NSDictionary *requestContents = @{

                                      @"receipt-data": [receipt base64EncodedStringWithOptions:0]

                                      };

    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents

                                                          options:0

                                                            error:&error];

    

    if (!requestData) { /* ... Handle error ... */ }

    

//    NSLog(@"%@", requestData);

    [self sendToServer:requestData];

    

    

//    NSURL *storeURL = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];

//    NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];

//    [storeRequest setHTTPMethod:@"POST"];

//    [storeRequest setHTTPBody:requestData];

//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

//    

//    [NSURLConnection sendAsynchronousRequest:storeRequest queue:queue

//                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

//                               if (connectionError) {

//                                   /* ... Handle error ... */

//                               } else {

//                                   NSError *error;

//                                   NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

//                                   if (!jsonResponse) { /* ... Handle error ...*/ }

//                                   /* ... Send a response back to the device ... */

//                                   

//                                   NSLog(@"%@", jsonResponse);

//                                   

//                               }

//                           }];


    

    

    

}


-(void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {

    if(response.products.count != 0 ){

        _product = (SKProduct*)response.products[0];

        NSLog(@"%@", _product.productIdentifier);

        _btnBuynow.enabled = YES;

        NSLog(@"now you can buy!");

    }

}


- (IBAction)BuyNow:(id)sender {

    NSLog(@"%@", _product.productIdentifier);



    if([SKPaymentQueue canMakePayments]){

        SKPayment *payment = [SKPayment paymentWithProduct:_product];

        [[SKPaymentQueue defaultQueue] addPayment:payment];

    }

}


@end


















#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import webapp2
import json
import base64
import urllib, urllib2
import datetime
from itunesiap import Request

liveURL = 'https://buy.itunes.apple.com/verifyReceipt'
sandboxURL = 'https://sandbox.itunes.apple.com/verifyReceipt'
URL = sandboxURL


class HelloWebapp2(webapp2.RequestHandler):
def get(self):
self.response.write('Hello, webapp2!')


class VerifyReceiptHandler(webapp2.RequestHandler):
def post(self):
raw_data = base64.b64encode(self.request.get("content"))
request = Request(raw_data)
receipt = request.verify()
# receiptData = base64.b64encode(self.request.get("content"))
# url = 'https://sandbox.itunes.apple.com/verifyReceipt'
# receipt_data = self.request.get("content")
#
# data = {"receipt-data": receipt_data}
# headers = {'Content-Type': 'text/json; charset=utf-8'}
# dataj = json.dumps(data)
# request = urllib2.Request(url, dataj, headers)
# # In case you are wondering what is being sent and the format
# print "request%s" % request.get_data()
# # This shows the method either POST or GET (App store wants POST and not GET)
# print "request type %s" % request.get_method()
# start_time = datetime.datetime.now()
# response = urllib2.urlopen(request)
# wait_time = datetime.datetime.now() - start_time
# print('Wait time for validation call: %s' % wait_time)
# response_json = json.loads(response.read())
# print response_json

# receiptData = self.request.get("content")
# jsonData = json.dumps({'receipt-data': receiptData})
#
# s = urllib2.urlopen(URL, jsonData)
# responseData = s.read()
# s.close()
#
# responseJSON = json.loads(responseData)
# print json.dumps(responseJSON, sort_keys=True, indent=4)

self.response.out.write(receipt)

def get(self):
self.response.out.write('VerifyReceiptHandler')


app = webapp2.WSGIApplication([
('/', HelloWebapp2),
('/VerifyReceipt', VerifyReceiptHandler)
], debug=True)


def main():
app.run()


if __name__ == "__main__":
main()


반응형

'iOS' 카테고리의 다른 글

iOS in app purchase (iap) objective-c  (0) 2015.08.13
swift IAP  (0) 2015.08.11
Linking is broken for static library (since Xcode6)  (0) 2015.07.30
[Swift] Class 1-1 (inheritance, referance copy)  (0) 2015.07.25
[Swift] function 1-4  (0) 2015.07.23
: