코딩하는 나귀

아이템을 구매한 후에 결제 내역이 유효한지 확인하기 위한 방법
테스트(SandBox)와 실제 확이하는 애플 URL이 다르므로 실제 반영할 때는
변경해 주어야 한다. 

내부적인 동작 과정은 서버에서 하던 클라이언트에서 하던 동일하다
transactionReceipt 를 Base64로 Encoding한 후에 'receipt-data'라는 Key에 Encoding된 
transactionReceipt값을
Json 형태로 만들어 Post 방식으로 애플 확인 서버로 보내면 된다.

ASIFormDataRequest를 사용할 때는 HTTP  Request부분만 아래와 같이

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

ASIFormDataRequest* request = [[[ASIFormDataRequest alloc] initWithURL:verifyURL] autorelease];

[request setRequestMethod:@"POST"];

[request appendPostData:jsonData];

[request startSynchronous];
.


 - (NSString*)base64forData:(NSData*)theData {

    const uint8_t* input = (const uint8_t*)[theData bytes];

    NSInteger length = [theData length];

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];

    uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;

    for (i=0; i < length; i += 3) {

        NSInteger value = 0;

        NSInteger j;

        for (j = i; j < (i + 3); j++) {

            value <<= 8;

            if (j < length) {

                value |= (0xFF & input[j]);

            }

        }

        NSInteger theIndex = (i / 3) * 4;

        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];

        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];

        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';

        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';

    }

    return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];

}


//Service URL : https://buy.itunes.apple.com/verifyReceipt

- (BOOL)verifyReceipt:(SKPaymentTransaction*)transaction

{

    NSString* recieptString = [self base64forData:transaction.transactionReceipt];

    NSError* error = nil;

    NSDictionary* dict = [NSDictionary dictionaryWithObject:recieptString forKey:@"receipt-data"];

    NSData* jsonData = [[CJSONSerializer serializer] serializeObject:dict error:&error];

    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://sandbox.itunes.apple.com/verifyReceipt"]]] autorelease];                          

    [request setHTTPMethod:@"POST"];   

    [request setHTTPBody:jsonData];

    NSData* responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSDictionary* jsonDict = [[CJSONDeserializer deserializer] deserializeAsDictionary:responseData error:nil];

    return [[jsonDict objectForKey:@"status"] integerValue] == 0;

}