Cómo validar compras en la aplicación en iOS localmente

Hola,
Por favor, implemente este controlador de vista

#import
#import

#define IS_IOS6_AWARE (__IPHONE_OS_VERSION_MAX_ALLOWED> __IPHONE_5_1)

#define ITMS_PROD_VERIFY_RECEIPT_URL @ “Página en apple.com”
#define ITMS_SANDBOX_VERIFY_RECEIPT_URL @ “Página en apple.com”;

#define KNOWN_TRANSACTIONS_KEY @ “knownIAPTransactions”

#define ITC_CONTENT_PROVIDER_SHARED_SECRET @ “6b9657772148413ca420855195c51e5c”

char * base64_encode (const void * buf, size_t size);
void * base64_decode (const char * s, size_t * data_len);

typedef void (^ VerifyCompletionHandler) (éxito BOOL);

@interface VerificationController: NSObject {
NSMutableDictionary * transaccionesReceiptStorageDictionary;
}

+ (VerificationController *) sharedInstance;

// Comprobar los resultados de esto no es suficiente.
// La verificación final ocurre en la conexión: didReceiveData: devolución de llamada dentro de
// esta clase. Así que asegúrese de que las características de IAP estén desbloqueadas desde allí.
– (nulo) verificar compra: (SKPaymentTransaction *) transacción completeHandler: (VerifyCompletionHandler) completeHandler;

@fin

#import “VerificationController.h”
#import “NSData + Base64.h”

VerificationController estático * singleton;

@implementation VerificationController {
NSMutableDictionary * _completionHandlers;
}

+ (VerificationController *) sharedInstance
{
if (singleton == nil)
{
singleton = [[VerificationController alloc] init];
}
volver singleton;
}

– (id) init
{
self = [superinicio];
if (self! = nil)
{
transaccionesReceiptStorageDictionary = [[NSMutableDictionary alloc] init];
_completionHandlers = [[NSMutableDictionary alloc] init];
}
volver a sí mismo;
}

– (NSDictionary *) dictionaryFromPlistData: (NSData *) datos
{
NSError * error;
NSDictionary * dictionaryParsed = [NSPropertyListSerialization propertyListWithData: data
opciones: NSPropertyListImmutable
formato: nulo
error: & error];
if (! dictionaryParsed)
{
si (error)
{
NSLog (@ “Error al analizar plist”);
}
volver nulo
}
return dictionaryParsed;
}

– (NSDictionary *) dictionaryFromJSONData: (NSData *) data
{
NSError * error;
NSDictionary * dictionaryParsed = [NSJSONSerialization JSONObjectWithData: data
opciones: 0
error: & error];
if (! dictionaryParsed)
{
si (error)
{
NSLog (@ “Diccionario de análisis de errores”);
}
volver nulo
}
return dictionaryParsed;
}

#pragma mark Verificación de recibo

// Este método debe llamarse una vez que una transacción llega al estado SKPaymentTransactionStatePurchased o SKPaymentTransactionStateRestored
// Llámalo con SKPaymentTransaction.transactionReceipt
– (nulo) verificar compra: (SKPaymentTransaction *) transacción completeHandler: (VerifyCompletionHandler) completeHandler
{
BOOL isOk = [self isTransactionAndItsReceiptValid: transacción];
si (! isOk)
{
// Hubo un problema con la transacción que recibimos, por lo que no es necesario llamar a verifyReceipt.
NSLog (@ “Transacción no válida”);
completeHandler (FALSO);
regreso;
}

// La transacción se ve bien, así que comienza el proceso de verificación.

// Codifique el recibo de datos para la solicitud POST de verificación de recibo de itms.
NSString * jsonObjectString = [self encodeBase64: (uint8_t *) transaction.transactionReceipt.bytes
longitud: transaction.transactionReceipt.length];

// Cree la carga útil de la solicitud POST.
NSString * payload = [NSString stringWithFormat: @ “{\” recibo-datos \ “: \”% @ \ “, \” contraseña \ “: \”% @ \ “}”,
jsonObjectString, ITC_CONTENT_PROVIDER_SHARED_SECRET];

NSData * payloadData = [datos de carga útilUsingEncoding: NSUTF8StringEncoding];

// Usa ITMS_SANDBOX_VERIFY_RECEIPT_URL mientras pruebas contra el sandbox.
NSString * serverURL = ITMS_SANDBOX_VERIFY_RECEIPT_URL; // ITMS_PROD_VERIFY_RECEIPT_URL;

// Cree la solicitud POST al servidor.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: serverURL]];
[solicitud setHTTPMethod: @ “POST”];
[solicitud setHTTPBody: payloadData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest: request delegate: self];

_completionHandlers [[NSValue valueWithNonretainedObject: conn]] = completeHandler;

[inicio conn];

// El recibo de la transición aún no se ha validado. Eso se hace desde la devolución de llamada NSURLConnection.
}

// Verifique la validez del recibo. Si se retira, también asegúrese de que la transacción sea algo
// no hemos visto antes y luego decodificamos y guardamos la información de compra del recibo para su posterior validación.
– (BOOL) isTransactionAndItsReceiptValid: (SKPaymentTransaction *) transacción
{
if (! (transacción && transacción.transactionReceipt && [transacción.transactionReceipt longitud]> 0))
{
// La transacción no es válida.
devolver NO;
}

// Extraiga la información de compra del recibo de la transacción, decodifíquela y guárdela para más adelante.
// se puede hacer una verificación cruzada con generateReceipt.
NSDictionary * ticketDict = [self dictionaryFromPlistData: transaction.transactionReceipt];
NSString * transactionPurchaseInfo = [ticketDict objectForKey: @ “información de compra”];
NSString * decodedPurchaseInfo = [self decodeBase64: transacciónPurchaseInfo longitud: nil];
NSDictionary * buyInfoDict = [self dictionaryFromPlistData: [decodedPurchaseInfo dataUsingEncoding: NSUTF8StringEncoding]];

NSString * transactionId = [adquirirInfoDict objectForKey: @ “id-transacción”];
NSString *chaseDateString = [adquirirInfoDict objectForKey: @ “fecha de compra”];
NSString * firma = [ticketDict objectForKey: @ “firma”];

// Convierte la cadena en una fecha
NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat: @ “aaaa-MM-dd HH: mm: ss z”];

NSDate *chaseDate = [dateFormat dateFromString: [adquirirDateString stringByReplacingOccurrencesOfString: @ “Etc /” withString: @ “”]];

if (! [self isTransactionIdUnique: transactionId])
{
// Hemos visto esta transacción antes.
// Tenía [transaccionesReceiptStorageDictionary objectForKey: transacciónId]
// Consiguió la compraInfoDict
devolver NO;
}

// Verifique la autenticidad de la respuesta / firma del recibo, etc.

Resultado BOOL = checkReceiptSecurity (transactionPurchaseInfo, firma,
(__bridge CFDateRef) (fecha de compra));

si (! resultado)
{
devolver NO;
}

// Asegúrese de que la transacción en sí misma sea legítima
if (! [self doTransactionDetailsMatchPurchaseInfo: transacción conPurchaseInfo: buyInfoDict])
{
devolver NO;
}

// Tome nota del hecho de que ya hemos visto la identificación de la transacción
[self saveTransactionId: transacciónId];

// Guarde la información de compra del recibo de transacción en las transaccionesReceiptStorageDictionary
[transaccionesReceiptStorageDictionary setObject: buyInfoDict forKey: transacciónId];

devuelva SÍ;
}

// Asegúrese de que los detalles de la transacción realmente coincidan con la información de compra
– (BOOL) doTransactionDetailsMatchPurchaseInfo: (SKPaymentTransaction *) transacción conPurchaseInfo: (NSDictionary *) buyInfoDict

{
if (! transacción ||! buyInfoDict)
{
devolver NO;
}

int failCount = 0;

if (! [transaction.payment.productIdentifier isEqualToString: [adquirirInfoDict objectForKey: @ “product-id”]])
{

failCount ++;
}

if (transaction.payment.quantity! = [[adquirirInfoDict objectForKey: @ “cantidad”] intValue])
{
failCount ++;
}

if (! [transaction.transactionIdentifier isEqualToString: [adquirirInfoDict objectForKey: @ “id-transacción”]])
{
failCount ++;
}

// Opcionalmente, verifique que la oferta y los bvrs coincidan con el ID del paquete y la versión del paquete actuales de esta aplicación.
// Opcionalmente, verifique requestData.
// Opcionalmente verifica las fechas.

if (failCount! = 0)
{
devolver NO;
}

// La transacción y su contenido firmado parecen estar bien.
devuelva SÍ;
}

– (BOOL) isTransactionIdUnique: (NSString *) transactionId
{
NSString * transactionDictionary = KNOWN_TRANSACTIONS_KEY;
// Guarde el Id. De transacción en los valores predeterminados de usuario estándar para que podamos verificarlo más adelante
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[valores predeterminados de sincronización];

if (! [predeterminado objectForKey: transactionDictionary])
{
[predeterminado setObject: [[NSMutableDictionary alloc] init] forKey: transactionDictionary];
[valores predeterminados de sincronización];
}

if (! [[por defecto objectForKey: transactionDictionary] objectForKey: transactionId])
{
devuelva SÍ;
}
// La transacción ya existe en los valores predeterminados.
devolver NO;
}

– (nulo) saveTransactionId: (NSString *) transactionId
{
// Guarde el Id. De transacción en los valores predeterminados de usuario estándar para que podamos verificarlo más adelante
// Si el diccionario ya existe, recupéralo y agrega una nueva ID de transacción
// Independientemente de guardar Id. De transacción en el diccionario que se guarda en NSUserDefaults
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSString * transactionDictionary = KNOWN_TRANSACTIONS_KEY;
NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithDictionary:
[por defecto objectForKey: transactionDictionary]];
si (diccionario)
{
diccionario = [[NSMutableDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt: 1], transactionId, nil];
} más {
[diccionario setObject: [NSNumber numberWithInt: 1] forKey: transactionId];
}
[predeterminado setObject: dictionary forKey: transactionDictionary];
[valores predeterminados de sincronización];

}

– (BOOL) doesTransactionInfoMatchReceipt: (NSString *) ticketString
{
// Convierta el responseString en un diccionario y extraiga los datos del recibo.
NSDictionary * VerifiedReceiptDictionary = [self dictionaryFromJSONData: [ticketString dataUsingEncoding: NSUTF8StringEncoding]];

// Verifica el estado de la llamada generateReceipt
id status = [VerifiedReceiptDictionary objectForKey: @ “status”];
si (! estado)
{
devolver NO;
}
int understandReceiptStatus = (int) [status integerValue];
// 21006 = Este recibo es válido pero la suscripción ha expirado.
if (0! = verifiedReceiptStatus && 21006! = generateReceiptStatus)
{
devolver NO;
}

// El recibo es válido, así que verifique los detalles del recibo ahora.

NSDictionary * VerifiedReceiptReceiptDictionary = [VerifiedReceiptDictionary objectForKey: @ “recibo”];
// NSString * VerifiedReceiptUniqueIdentifier = [VerifiedReceiptReceiptDictionary objectForKey: @ “unique_identifier”];
NSString * transactionIdFromVerifiedReceipt = [VerifiedReceiptReceiptDictionary objectForKey: @ “transacción_id”];

// Obtenga los datos del recibo de la transacción de las transaccionesReceiptStorageDictionary
NSDictionary * buyInfoFromTransaction = [transaccionesReceiptStorageDictionary objectForKey: transacciónIdFromVerifiedReceipt];

if (! buyInfoFromTransaction)
{
// No encontramos un recibo para esta transacción.
devolver NO;
}

// NOTA: en lugar de contar los errores, puede regresar temprano.
int failCount = 0;

// Verifique todos los detalles del recibo para asegurarse de que todo coincida como se esperaba
if (! [[VerifiedReceiptReceiptDictionary objectForKey: @ “bid”]
isEqualToString: [buyInfoFromTransaction objectForKey: @ “bid”]])
{
failCount ++;
}

if (! [[VerifiedReceiptReceiptDictionary objectForKey: @ “product_id”]
isEqualToString: [buyInfoFromTransaction objectForKey: @ “product-id”]])
{
failCount ++;
}

if (! [[VerifiedReceiptReceiptDictionary objectForKey: @ “cantidad”]
isEqualToString: [adquirirInfoFromTransaction objectForKey: @ “cantidad”]])
{
failCount ++;
}

if (! [[VerifiedReceiptReceiptDictionary objectForKey: @ “item_id”]
isEqualToString: [adquirirInfoFromTransaction objectForKey: @ “item-id”]])
{
failCount ++;
}

if ([[UIDevice currentDevice] respondeToSelector: NSSelectorFromString (@ “identifierForVendor”)]) // iOS 6?
{
// iOS 6 (o posterior)
NSString * localIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSString * buyInfoUniqueVendorId = [adquirirInfoFromTransaction objectForKey: @ “identificador de proveedor único”];
NSString * VerifiedReceiptVendorIdentifier = [VerifiedReceiptReceiptDictionary objectForKey: @ “unique_vendor_identifier”];

if (VerifiedReceiptVendorIdentifier)
{
if (! [buyInfoUniqueVendorId isEqualToString: VerifiedReceiptVendorIdentifier]
|| ! [buyInfoUniqueVendorId isEqualToString: localIdentifier])
{
// Comenta esta línea para probar en el simulador.
failCount ++;
}
}
}

// Hacer comprobaciones de tiempo de adición para la transacción y el recibo.

if (failCount! = 0)
{
devolver NO;
}

devuelva SÍ;
}

#pragma mark NSURLConnectionDelegate (para la conexión generateReceipt)

– (nula) conexión: (NSURLConnection *) conexión didFailWithError: (NSError *) error {

NSLog (@ “Error de conexión:% @”, error);

VerifyCompletionHandler completeHandler = _completionHandlers [[NSValue valueWithNonretainedObject: conexión]];
[_completionHandlers removeObjectForKey: [NSValue valueWithNonretainedObject: conexión]];
completeHandler (FALSO);

}

– (vacío) conexión: (NSURLConnection *) conexión didReceiveData: (NSData *) datos
{
NSString * responseString = [[NSString alloc] initWithData: codificación de datos: NSUTF8StringEncoding];

// Entonces tenemos algunos datos de recibo. ¿Ahora todo se ve?
BOOL isOk = [self doesTransactionInfoMatchReceipt: responseString];

VerifyCompletionHandler completeHandler = _completionHandlers [[NSValue valueWithNonretainedObject: conexión]];
[_completionHandlers removeObjectForKey: [NSValue valueWithNonretainedObject: conexión]];
if (isOk)
{
// Validación exitosa. Desbloquee contenido aquí.
NSLog (@ “Validación exitosa”);
completeHandler (VERDADERO);

} más {
NSLog (@ “Error de validación”);
completeHandler (FALSO);
}
}

– (vacío) conexión: (NSURLConnection *) conexión willSendRequestForAuthenticationChallenge: (NSURLAuthenticationChallenge *) desafío
{
if ([[[desafío protecciónSpace] autenticaciónMetodo] isEqualToString: NSURLAuthenticationMethodServerTrust])
{
SecTrustRef trust = [[desafío protecciónSpace] serverTrust];
NSError * error = nil;
BOOL didUseCredential = NO;
BOOL isTrusted = [self validateTrust: error de confianza: & error];
if (isTrusted)
{
NSURLCredential * trust_credential = [NSURLCredential credentialForTrust: confianza];
if (trust_credential)
{
[[remitente del desafío] useCredential: trust_credential forAuthenticationChallenge: challenge];
didUseCredential = YES;
}
}
if (! didUseCredential)
{
[[remitente del desafío] cancelAuthenticationChallenge: challenge];
}
} más {
[[remitente del desafío] performDefaultHandlingForAuthenticationChallenge: challenge];
}
}

// NOTA: Estos son necesarios para 4.x (como willSendRequestForAuthenticationChallenge: no es compatible)
– Conexión (BOOL): (NSURLConnection *) la conexión puedeAuthenticateAgainstProtectionSpace: (NSURLProtectionSpace *) protectionSpace
{
return [[protectionSpace autenticaciónMethod] isEqualToString: NSURLAuthenticationMethodServerTrust];
}

– (nula) conexión: (NSURLConnection *) conexión didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *) challenge
{
if ([[[desafío protecciónSpace] autenticaciónMetodo] isEqualToString: NSURLAuthenticationMethodServerTrust])
{
SecTrustRef trust = [[desafío protecciónSpace] serverTrust];
NSError * error = nil;
BOOL didUseCredential = NO;
BOOL isTrusted = [self validateTrust: error de confianza: & error];
if (isTrusted)
{
NSURLCredential * credential = [NSURLCredential credentialForTrust: confianza];
si (credencial)
{
[[remitente del desafío] useCredential: credencial paraAuthenticationChallenge: challenge];
didUseCredential = YES;
}
}
if (! didUseCredential) {
[[remitente del desafío] cancelAuthenticationChallenge: challenge];
}
} más {
[[remitente del desafío] performDefaultHandlingForAuthenticationChallenge: challenge];
}
}

# marca pragma
#pragma mark NSURLConnection – Validación de confianza

– (BOOL) validateTrust: (SecTrustRef) error de confianza: (NSError **) error
{

// Incluya algunas SPI del marco de seguridad
CFStringRef externo kSecTrustInfoExtendedValidationKey;
CFDictionaryRef externo SecTrustCopyInfo (confianza SecTrustRef);

BOOL confiable = NO;
SecTrustResultType trust_result;
if ((noErr == SecTrustEvaluate (trust, & trust_result)) && (trust_result == kSecTrustResultUnspecified))
{
NSDictionary * trust_info = (__bridge_transfer NSDictionary *) SecTrustCopyInfo (confianza);
id hasEV = [trust_info objectForKey: (__ bridge NSString *) kSecTrustInfoExtendedValidationKey];
confiable = [hasEV isKindOfClass: [clase NSValue]] && [hasEV boolValue];
}

si (confianza)
{
if (! Trusted && error)
{
* error = [NSError errorWithDomain: @ código “kSecTrustError”: (NSInteger) trust_result userInfo: nil];
}
volver confiable;
}
devolver NO;
}

# marca pragma
#pragma mark Firma del recibo de verificación

#include
#include
#include
unsigned int iTS_intermediate_der_len = 1039;

unsigned char iTS_intermediate_der [] = {
0x30, 0x82, 0x04, 0x0b, 0x30, 0x82, 0x02, 0xf3, 0xa0, 0x03, 0x02, 0x01,
0x02, 0x02, 0x01, 0x1a, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x62, 0x31, 0x0b, 0x30,
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13,
0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x0a, 0x41, 0x70, 0x70,
0x6c, 0x65, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x31, 0x26, 0x30, 0x24, 0x06,
0x03, 0x55, 0x04, 0x0b, 0x13, 0x1d, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20,
0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x31,
0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x0d, 0x41, 0x70,
0x70, 0x6c, 0x65, 0x20, 0x52, 0x6f, 0x6f, 0x74, 0x20, 0x43, 0x41, 0x30,
0x1e, 0x17, 0x0d, 0x30, 0x39, 0x30, 0x35, 0x31, 0x39, 0x31, 0x38, 0x33,
0x31, 0x33, 0x30, 0x5a, 0x17, 0x0d, 0x31, 0x36, 0x30, 0x35, 0x31, 0x38,
0x31, 0x38, 0x33, 0x31, 0x33, 0x30, 0x5a, 0x30, 0x7f, 0x31, 0x0b, 0x30,
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13,
0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0a, 0x41, 0x70, 0x70,
0x6c, 0x65, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x31, 0x26, 0x30, 0x24, 0x06,
0x03, 0x55, 0x04, 0x0b, 0x0c, 0x1d, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20,
0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x31,
0x33, 0x30, 0x31, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x2a, 0x41, 0x70,
0x70, 0x6c, 0x65, 0x20, 0x69, 0x54, 0x75, 0x6e, 0x65, 0x73, 0x20, 0x53,
0x74, 0x6f, 0x72, 0x65, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69,
0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f,
0x72, 0x69, 0x74, 0x79, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03,
0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
0x00, 0xa4, 0xbc, 0xaf, 0x32, 0x94, 0x43, 0x3e, 0x0b, 0xbc, 0x37, 0x87,
0xcd, 0x63, 0x89, 0xf2, 0xcc, 0xd9, 0xbe, 0x20, 0x4d, 0x5a, 0xb4, 0xfe,
0x87, 0x67, 0xd2, 0x9a, 0xde, 0x1a, 0x54, 0x9d, 0xa2, 0xf3, 0xdf, 0x87,
0xe4, 0x4c, 0xcb, 0x93, 0x11, 0x78, 0xa0, 0x30, 0x8f, 0x34, 0x41, 0xc1,
0xd3, 0xbe, 0x66, 0x6d, 0x47, 0x6c, 0x98, 0xb8, 0xec, 0x7a, 0xd5, 0xc9,
0xdd, 0xa5, 0xe4, 0xea, 0xc6, 0x70, 0xf4, 0x35, 0xd0, 0x91, 0xf7, 0xb3,
0xd8, 0x0a, 0x11, 0x99, 0xab, 0x3a, 0x62, 0x3a, 0xbd, 0x7b, 0xf4, 0x56,
0x4f, 0xdb, 0x9f, 0x24, 0x93, 0x51, 0x50, 0x7c, 0x20, 0xd5, 0x66, 0x4d,
0x66, 0xf3, 0x18, 0xa4, 0x13, 0x96, 0x22, 0x16, 0xfd, 0x31, 0xa7, 0xf4,
0x39, 0x66, 0x9b, 0xfb, 0x62, 0x69, 0x5c, 0x4b, 0x9f, 0x94, 0xa8, 0x4b,
0xe8, 0xec, 0x5b, 0x64, 0x5a, 0x18, 0x79, 0x8a, 0x16, 0x75, 0x63, 0x42,
0xa4, 0x49, 0xd9, 0x8c, 0x33,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0e, 0xd7, 0x43, 0x0b, 0x91, 0x58, 0x43, 0x3a, 0x30, 0x1f, 0x06, 0x03,
0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x2b, 0xd0, 0x69,
0x47, 0x94, 0x76, 0x09, 0xfe, 0xf4, 0x6b, 0x8d, 0x2e, 0x40, 0xa6, 0xf7,
0x47, 0x4d, 0x7f, 0x08, 0x5e, 0x30, 0x36, 0x06, 0x03, 0x55, 0x1d, 0x1f,
0x04, 0x2f, 0x30, 0x2d, 0x30, 0x2b, 0xa0, 0x29, 0xa0, 0x27, 0x86, 0x25,
0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x61,
0x70, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x70, 0x70,
0x6c, 0x65, 0x63, 0x61, 0x2f, 0x72, 0x6f, 0x6f, 0x74, 0x2e, 0x63, 0x72,
0x6c, 0x30, 0x10, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x63, 0x64,
0x06, 0x02, 0x02, 0x04, 0x02, 0x05, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x82,
0x01, 0x01, 0x00, 0x75, 0xa6, 0x90, 0xe6, 0x9a, 0xa7, 0xdb, 0x65, 0x70,
0xa6, 0x09, 0x93, 0x6f, 0x08, 0xdf, 0x2c, 0xdb, 0xe9, 0x28, 0x8d, 0x40,
0x1b, 0x57, 0x5e, 0xa0, 0xea, 0xf4, 0xec, 0x13, 0x65, 0x1b, 0x71, 0x4a,
0x4d, 0xdc, 0x80, 0x48, 0x4f, 0xf2, 0xe5, 0xa9, 0xfb, 0x85, 0x6c, 0xb7,
0x1e, 0x9d, 0xdb, 0xf4, 0x18, 0x48, 0x10, 0x79, 0x17, 0xea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, 0x65, 0xb5, 0x21, 0x76, 0xdb, 0xa4, 0xef, 0xcb, 0x72, 0xef,
0x54, 0x6b, 0x01, 0x0d, 0xc7, 0xdd, 0x1a
};

BOOL checkReceiptSecurity (NSString * buy_info_string, NSString * signature_string, CFDateRef adquirir la fecha)
{
BOOL válido = NO;
SecCertificateRef leaf = NULL, intermedia = NULL;
SecTrustRef trust = NULL;
Política SecPolicyRef = SecPolicyCreateBasicX509 ();

NSData * certificate_data;
Anclajes NSArray *;

/ *
Analizar entradas:
buy_info_string y signature_string son blobs JSON codificados en base64 que necesitan
ser decodificado
* /

require ([buy_info_string canBeConvertedToEncoding: NSASCIIStringEncoding] &&
[signature_string canBeConvertedToEncoding: NSASCIIStringEncoding], outLabel);

size_t adquirir_información_longitud;
uint8_t * buyer_info_bytes = base64_decode ([adquirir_info_string cStringUsingEncoding: NSASCIIStringEncoding],
& compra_info_length);

size_t signature_length;
uint8_t * signature_bytes = base64_decode ([signature_string cStringUsingEncoding: NSASCIIStringEncoding],
& firma_length);

require (buy_info_bytes && signature_bytes, outLabel);

/ *
El formato binario tiene el siguiente aspecto:

RECEIPTVERSION | FIRMA | TAMAÑO DE CERTIFICADO | CERTIFICADO
1 byte 128 4 bytes
gran endian

Extraer versión, firma y certificado (s).
Verifique la versión del recibo == 2.
Verifique que la firma tenga 128 bytes.
Tamaño del certificado de comprobación de cordura <= datos de carga útil restantes.
* /

#pragma pack (push, 1)
struct signature_blob {
versión uint8_t;
uint8_t firma [128];
uint32_t cert_len;
certificado uint8_t [];
} * signature_blob_ptr = (struct signature_blob *) signature_bytes;
#pragma pack (pop)
uint32_t certificate_len;

/ *
Asegúrese de que el blob de firma sea lo suficientemente largo como para extraer la versión y
cert_len campos, luego realice una verificación de cordura en los campos.
* /
require (signature_length> offsetof (struct signature_blob, certificado), outLabel);
require (signature_blob_ptr-> version == 2, outLabel);
certificate_len = ntohl (signature_blob_ptr-> cert_len);

require (signature_length – offsetof (struct signature_blob, certificate)> = certificate_len, outLabel);

/ *
Validar las cadenas de certificados de vuelta al firmante de recibo válido; aproximación de políticas por ahora
establecer intermedio como un ancla de confianza; Lapsos intermedios actuales en 2016.
* /

certificate_data = [NSData dataWithBytes: signature_blob_ptr-> longitud del certificado: certificate_len];
require (leaf = SecCertificateCreateWithData (NULL, (__bridge CFDataRef) certificate_data), outLabel);

certificate_data = [NSData dataWithBytes: iTS_intermediate_der length: iTS_intermediate_der_len];
require (intermedio = SecCertificateCreateWithData (NULL, (__bridge CFDataRef) certificate_data), outLabel);

anchors = [NSArray arrayWithObject: (__ bridge id) intermedio];
require (anclas, outLabel);

require_noerr (SecTrustCreateWithCertificates (hoja, política y confianza), outLabel);
require_noerr (SecTrustSetAnchorCertificates (confianza, (__bridge CFArrayRef) anclajes), outLabel);

si (fecha de compra)
{
require_noerr (SecTrustSetVerifyDate (confianza, compraDate), outLabel);
}

SecTrustResultType trust_result;
require_noerr (SecTrustEvaluate (confianza, y confianza_resultado), outLabel);
require (trust_result == kSecTrustResultUnspecified, outLabel);

require (2 == SecTrustGetCertificateCount (confianza), outLabel);

/ *
La cadena es válida, use la tecla de hoja para verificar la firma al recibirla
Cálculo de SHA1 (versión | compraInfo)
* /

CC_SHA1_CTX sha1_ctx;
uint8_t a_be_verified_data [CC_SHA1_DIGEST_LENGTH];

CC_SHA1_Init (& sha1_ctx);
CC_SHA1_Update (& sha1_ctx, & signature_blob_ptr-> version, sizeof (signature_blob_ptr-> version));
CC_SHA1_Update (& sha1_ctx, buy_info_bytes, adquirir_info_length);
CC_SHA1_Final (to_be_verified_data, & sha1_ctx);

SecKeyRef ticket_signing_key = SecTrustCopyPublicKey (confianza);
require (ticket_signing_key, outLabel);
require_noerr (SecKeyRawVerify (ticket_signing_key, kSecPaddingPKCS1SHA1,
to_be_verified_data, sizeof (to_be_verified_data),
signature_blob_ptr-> signature, sizeof (signature_blob_ptr-> signature)),
outLabel);

/ *
Opcional: Verifique que el certificado de recibo tenga el OID nulo 1.2.840.113635.100.6.5.1

La firma es una firma RSA de 1024 bits.
* /

válido = SÍ;

outLabel:
if (hoja) CFRelease (hoja);
if (intermedio) CFRelease (intermedio);
if (confianza) CFRelease (confianza);
if (política) CFRelease (política);

devolución válida;
}

# marca pragma
#pragma mark Codificación Base 64

– (NSString *) encodeBase64: (const uint8_t *) longitud de entrada: (NSInteger) longitud
{
NSData * data = [NSData dataWithBytes: input length: length];
return [base de datos64EncodedString];
}

– (NSString *) decodeBase64: (NSString *) longitud de entrada: (NSInteger *) longitud
{
NSData * data = [NSData dataFromBase64String: input];
return [[NSString alloc] initWithData: codificación de datos: NSUTF8StringEncoding];
}

char * base64_encode (const void * buf, size_t size) {
size_t outputLength;
return NewBase64Encode (buf, tamaño, NO, y outputLength);
}

void * base64_decode (const char * s, size_t * data_len)
{
return NewBase64Decode (s, strlen (s), data_len);
}

@fin

Para usarlo puedes usar este código,
VerificationController * verifier = [VerificationController sharedInstance];
[verificador verificar Compra: finalización de la transacción Manejador: ^ (éxito de BOOL) {
si (éxito) {
NSLog (@ “¡Recibo verificado con éxito!”);
[self provideContentForProductIdentifier: transaction.payment.productIdentifier];
} más {
NSLog (@ “Error al validar el recibo”);
[[SKPaymentQueue defaultQueue] finishTransaction: transacción];
}
}];

aquí Un secreto compartido es un código único que debe usar cuando realiza una llamada a nuestros servidores para recibir sus recibos de compra en la aplicación.