斯威夫特 2.0
这是一个将为 Swift 签名一组参数的函数。请注意,此代码需要安装Alamofire
和AWSCore
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")
}
您可以使用/修改以满足您的需要,但所有必要的东西都应该在那里。