在iOS的亚马逊产品广告API签名(Amazon Product Advertising API S

2019-06-25 08:06发布

我试图访问Amazon的产品广告API在我的iPhone应用程序。 创建签名似乎是艰难的部分。 在本页面:

http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/rest-signature.html

它说,“计算符合RFC 2104-HMAC与SHA256散列算法”。 亚马逊还提供了Java类来为你做这个:

http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/AuthJavaSampleSig2.html

有谁知道我可以在Objective-C这样做呢? 我看着AWS iOS的SDK,但它似乎并不包括产品广告API。

Answer 1:

实际上,AWS的iOS SDK确实有一个静态方法来处理所有身份验证的情况。 也许你应该采取的一瞥AmazonAuthUtils.h

+(NSString *)HMACSign:(NSData *)data withKey:(NSString *)key usingAlgorithm:(CCHmacAlgorithm)algorithm;
+(NSData *)sha256HMac:(NSData *)data withKey:(NSString *)key;

你可以找到它的文件中: http://docs.amazonwebservices.com/AWSiOSSDK/latest/Classes/AmazonAuthUtils.html



Answer 2:

只是有点添加到camelcc出色的观察。 这确实签署要求亚马逊产品广告API工作。 我不得不浪费时间有点搞不定。

获取安装SDK和#import <AWSiOSSDK/AmazonAuthUtils.h>

首先,你得请求字符串组织成正确的顺序,按照亚马逊的文档。 我发现这个页面是非常有用的解释如何订购请求

http://skilldrick.co.uk/2010/02/amazon-product-information-via-amazon-web-services/

注意在字符串中换行字符的需要,我的无符号的字符串看起来像这样

@"GET\necs.amazonaws.com\n/onca/xml\nAWSAccessKeyId=<ACCESS_KEY_ID>&AssociateTag=<ASSOCIATE_ID>&Keywords=harry%20potter&Operation=ItemSearch&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2012-07-03T10%3A52%3A21.000Z&Version=2011-08-01"

没有空间的任何地方,但\n在正确的地方字符。 在这个转换为NSData ,像这样

NSData *dataToSign = [unsignedString dataUsingEncoding:NSUTF8StringEncoding];

然后调用

[AmazonAuthUtils HMACSign:dataToSign withKey:SECRET_KEY usingAlgorithm:kCCHmacAlgSHA256]

这将返回您的签名作为NSString 。 你需要URL编码本(即交换非法/不安全%0X符号charecters(即“=”转换为“%3D”))

一旦做到这一点,把它贴在您的请求,希望你是好去!



Answer 3:

看看我的亚马逊产品广告客户https://github.com/m1entus/RWMAmazonProductAdvertisingManager

一些代码requesst序列:

NSString * const RWMAmazonProductAdvertisingStandardRegion = @"webservices.amazon.com";
NSString * const RWMAmazonProductAdvertisingAWSAccessKey = @"AWSAccessKeyId";
NSString * const RWMAmazonProductAdvertisingTimestampKey = @"Timestamp";
NSString * const RWMAmazonProductAdvertisingSignatureKey = @"Signature";
NSString * const RWMAmazonProductAdvertisingVersionKey = @"Version";
NSString * const RWMAmazonProductAdvertisingCurrentVersion = @"2011-08-01";

NSData * RWMHMACSHA256EncodedDataFromStringWithKey(NSString *string, NSString *key) {
    NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding];
    CCHmacContext context;
    const char *keyCString = [key cStringUsingEncoding:NSASCIIStringEncoding];

    CCHmacInit(&context, kCCHmacAlgSHA256, keyCString, strlen(keyCString));
    CCHmacUpdate(&context, [data bytes], [data length]);

    unsigned char digestRaw[CC_SHA256_DIGEST_LENGTH];
    NSUInteger digestLength = CC_SHA256_DIGEST_LENGTH;

    CCHmacFinal(&context, digestRaw);

    return [NSData dataWithBytes:digestRaw length:digestLength];
}

NSString * RWMISO8601FormatStringFromDate(NSDate *date) {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [dateFormatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'Z'"];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

    return [dateFormatter stringFromDate:date];
}

NSString * RWMBase64EncodedStringFromData(NSData *data) {

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    return [data base64EncodedStringWithOptions:0];
#else
    return [data base64Encoding];
#endif

}

//http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                               withParameters:(id)parameters
                                        error:(NSError * __autoreleasing *)error
{
    NSParameterAssert(request);

    NSMutableURLRequest *mutableRequest = [request mutableCopy];

    if (self.accessKey && self.secret) {
        NSMutableDictionary *mutableParameters = [parameters mutableCopy];
        NSString *timestamp = RWMISO8601FormatStringFromDate([NSDate date]);

        if (!mutableParameters[RWMAmazonProductAdvertisingAWSAccessKey]) {
            [mutableParameters setObject:self.accessKey forKey:RWMAmazonProductAdvertisingAWSAccessKey];
        }
        mutableParameters[RWMAmazonProductAdvertisingVersionKey] = RWMAmazonProductAdvertisingCurrentVersion;
        mutableParameters[RWMAmazonProductAdvertisingTimestampKey] = timestamp;

        NSMutableArray *canonicalStringArray = [[NSMutableArray alloc] init];
        for (NSString *key in [[mutableParameters allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
            id value = [mutableParameters objectForKey:key];
            [canonicalStringArray addObject:[NSString stringWithFormat:@"%@=%@", key, value]];
        }
        NSString *canonicalString = [canonicalStringArray componentsJoinedByString:@"&"];
        canonicalString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                    (__bridge CFStringRef)canonicalString,
                                                                                    NULL,
                                                                                    CFSTR(":,"),
                                                                                    kCFStringEncodingUTF8));

        NSString *method = [request HTTPMethod];

        NSString *signature = [NSString stringWithFormat:@"%@\n%@\n%@\n%@",method,self.region,self.formatPath,canonicalString];

        NSData *encodedSignatureData = RWMHMACSHA256EncodedDataFromStringWithKey(signature,self.secret);
        NSString *encodedSignatureString = RWMBase64EncodedStringFromData(encodedSignatureData);

        encodedSignatureString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                           (__bridge CFStringRef)encodedSignatureString,
                                                                                           NULL,
                                                                                           CFSTR("+="),
                                                                                           kCFStringEncodingUTF8));

        canonicalString = [canonicalString stringByAppendingFormat:@"&%@=%@",RWMAmazonProductAdvertisingSignatureKey,encodedSignatureString];

        mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", canonicalString]];

    } else {
        if (error) {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Access Key and Secret Required", @"RWMAmazonProductAdvertisingManager", nil)};
            *error = [[NSError alloc] initWithDomain:RWMAmazonProductAdvertisingManagerErrorDomain code:NSURLErrorUserAuthenticationRequired userInfo:userInfo];
        }
    }

    return mutableRequest;

}


Answer 4:

感谢这个页面上的所有答案。 这里是为我(雨燕3.0)工作:

Podfile:

pod 'AWSAPIGateway', '~> 2.4.7'

SWIFT代码

static let kAmazonAccessID = "BLAH BLAH BLAH"
static let kAmazonAccessSecretKey = "BLAH BLAH BLAH"

static let kAmazonAssociateTag = "BLAH BLAH BLAH"
private let timestampFormatter: DateFormatter

init() {
    timestampFormatter = DateFormatter()
    timestampFormatter.timeZone = TimeZone(identifier: "GMT")
    timestampFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss'Z'"
    timestampFormatter.locale = Locale(identifier: "en_US_POSIX")
}

private func signedParametersForParameters(parameters: [String: String]) -> [String: String] {
    let sortedKeys = Array(parameters.keys).sorted(by: <)

    let query = sortedKeys.map { String(format: "%@=%@", $0, parameters[$0] ?? "") }.joined(separator: "&")

    let stringToSign = "GET\nwebservices.amazon.com\n/onca/xml\n\(query)"

    let dataToSign = stringToSign.data(using: String.Encoding.utf8)
    let signature = AWSSignatureSignerUtility.hmacSign(dataToSign, withKey: AmazonAPI.kAmazonAccessSecretKey, usingAlgorithm: UInt32(kCCHmacAlgSHA256))!

    var signedParams = parameters;
    signedParams["Signature"] = urlEncode(signature)

    return signedParams
}

public func urlEncode(_ input: String) -> String {
    let allowedCharacterSet = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)

    if let escapedString = input.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
        return escapedString
    }

    return ""
}

func send(url: String) -> String {
    guard let url = URL(string: url) else {
        print("Error! Invalid URL!") //Do something else
        return ""
    }

    let request = URLRequest(url: url)
    let semaphore = DispatchSemaphore(value: 0)

    var data: Data? = nil

    URLSession.shared.dataTask(with: request) { (responseData, _, _) -> Void in
        data = responseData
        semaphore.signal()
    }.resume()

    semaphore.wait(timeout: .distantFuture)

    let reply = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
    return reply
}

这里是让亚马逊商品的价格的功能:

public func getProductPrice(_ asin: AmazonStandardIdNumber) -> Double {

    let operationParams: [String: String] = [
        "Service": "AWSECommerceService",
        "Operation": "ItemLookup",
        "ResponseGroup": "Offers",
        "IdType": "ASIN",
        "ItemId": asin,
        "AWSAccessKeyId": urlEncode(AmazonAPI.kAmazonAccessID),
        "AssociateTag": urlEncode(AmazonAPI.kAmazonAssociateTag),
        "Timestamp": urlEncode(timestampFormatter.string(from: Date())),]

    let signedParams = signedParametersForParameters(parameters: operationParams)

    let query = signedParams.map { "\($0)=\($1)" }.joined(separator: "&")
    let url = "http://webservices.amazon.com/onca/xml?" + query

    let reply = send(url: url)

    // USE THE RESPONSE
}


Answer 5:

有几个步骤,从P-双后失踪。

此前构建的无符号的字符串,则需要在地方得到的时间戳值。

NSTimeZone *zone = [NSTimeZone defaultTimeZone];                //get the current application default time zone
NSInteger interval = [zone secondsFromGMTForDate:[NSDate date]];//sec Returns the time difference of the current application with the world standard time (Green Venice time)

NSDate *nowDate = [NSDate dateWithTimeIntervalSinceNow:interval];
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];

[formatter setTimeZone:[NSTimeZone systemTimeZone]];// get current date/time
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSString *currentTime = [dateFormatter stringFromDate:nowDate];

NSString* encodedTime = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef) currentTime,NULL, CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8));

NSString* unsignedString = [NSString stringWithFormat:@"GET\nwebservices.amazon.com\n/onca/xml\nAWSAccessKeyId=AKIAI443QEMWI6KW55QQ&AssociateTag=sajjmanz-20&Condition=All&IdType=ASIN&ItemId=3492264077&Operation=ItemLookup&ResponseGroup=Images%%2CItemAttributes%%2COffers&Service=AWSECommerceService&Timestamp=%@&Version=2011-08-01", encodedTime];

如果日期是URL编码的友好,中其余的步骤就像一个魅力。

最后,我也使用上面列出CFURLCreateStringByAddingPercentEscapes由AmazonAuthUtils HMACSign消息呼叫产生的串进行编码。



Answer 6:

我错了,这不是“法律”(根据亚马逊自己的准则)使用的iOS应用亚马逊的产品广告API没有亚马逊的明确书面同意?



Answer 7:

雨燕2.0

这里是一个将签署一套斯威夫特参数的函数。 请注意,此代码需要AlamofireAWSCore要安装的CocoaPods。 您还需要添加#import <CommonCrypto/CommonCrypto.h>您的Objective-C桥接报否则kCCHmacAlgSHA256不会被发现。

private func signedParametersForParameters(parameters: [String: String]) -> [String: String] {
    let sortedKeys = Array(parameters.keys).sort(<)

    var components: [(String, String)] = []
    for key in sortedKeys {
        components += ParameterEncoding.URLEncodedInURL.queryComponents(key, parameters[key]!)
    }

    let query = (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")

    let stringToSign = "GET\nwebservices.amazon.com\n/onca/xml\n\(query)"
    let dataToSign = stringToSign.dataUsingEncoding(NSUTF8StringEncoding)
    let signature = AWSSignatureSignerUtility.HMACSign(dataToSign, withKey: kAmazonAccessSecretKey, usingAlgorithm: UInt32(kCCHmacAlgSHA256))!

    let signedParams = parameters + ["Signature": signature]

    return signedParams
}

这就是所谓的是这样的:

let operationParams: [String: String] = ["Service": "AWSECommerceService", "Operation": "ItemLookup", "ItemId": "045242127733", "IdType": "UPC", "ResponseGroup": "Images,ItemAttributes", "SearchIndex": "All"]
let keyParams = ["AWSAccessKeyId": kAmazonAccessID, "AssociateTag": kAmazonAssociateTag, "Timestamp": timestampFormatter.stringFromDate(NSDate())]
let fullParams = operationParams + keyParams

let signedParams = signedParametersForParameters(fullParams)

Alamofire.request(.GET, "http://webservices.amazon.com/onca/xml", parameters: signedParams).responseString { (response) in
    print("Success: \(response.result.isSuccess)")
    print("Response String: \(response.result.value)")
}

最后,timestampFormatter声明如下:

private let timestampFormatter: NSDateFormatter

init() {
    timestampFormatter = NSDateFormatter()
    timestampFormatter.dateFormat = AWSDateISO8601DateFormat3
    timestampFormatter.timeZone = NSTimeZone(name: "GMT")
    timestampFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
}

您可以使用/修改以满足您的需求,但一切的需要应该在那里。



Answer 8:

而不是使用CommonCrypto,这是在现代OS X过时的,你也可以使用SecTransforms:

CFErrorRef error = NULL;

SecTransformRef digestRef = SecDigestTransformCreate(kSecDigestHMACSHA2, 256, &error);
SecTransformSetAttribute(digestRef, kSecTransformInputAttributeName, (__bridge CFDataRef)self, &error);
SecTransformSetAttribute(digestRef, kSecDigestHMACKeyAttribute, (__bridge CFDataRef)key, &error);

CFDataRef resultData = SecTransformExecute(digestRef, &error);
NSData* hashData = (__bridge NSData*)resultData;

CFRelease(digestRef);


文章来源: Amazon Product Advertising API Signature in iOS