2

我正在尝试通过HPP方法将Adyen支付集成到iOS中。不断出错,我怀疑编码部分有问题。Merchant signature was not valid

以下是我用来创建请求正文的代码片段

var urlComponents = URLComponents()
urlComponents.queryItems = []
let contentKeys1: [String] = Array(content.keys)
for contentKey in contentKeys1 {
    if let contentValue = content[contentKey] {
        urlComponents.queryItems?.append(URLQueryItem(name: contentKey, value: contentValue))
    }
}
self.httpBody = urlComponents.query?.data(using: .utf8)

Android中,它工作正常,我在 iOS 中使用 android 创建的字符串进行测试,支付页面正在启动,没有任何错误。

以下是创建请求正文的 Android 代码片段

val query = StringBuilder()
if (providerDataset != null) {
  for (providerData: ProviderData in providerDataset) {
      val key = providerData.key
      var value: String? = ""
      try {
           if (providerData.value != null)
               value = URLEncoder.encode(providerData.value, StandardCharsets.UTF_8.toString())
      } catch (e: UnsupportedEncodingException) {
           e.printStackTrace()
      }
      val str = "$key=$value"
      query.append(str).append("&")
  }
}
return query.deleteCharAt(query.length - 1).toString()

我们在 iOS 中是否有一种编码方法与上述代码中的 Android 工作相同?

挣扎了很多天才弄明白。任何帮助都是非常可观的

4

1 回答 1

0

您将查询参数放在httpBody. 相反,您需要将它们添加到URL.

为此,我使用Paw生成的以下代码:

protocol URLQueryParameterStringConvertible {
    var queryParameters: String {get}
}

extension Dictionary : URLQueryParameterStringConvertible {
    /**
     This computed property returns a query parameters string from the given NSDictionary. For
     example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
     string will be @"day=Tuesday&month=January".
     @return The computed parameters string.
    */
    var queryParameters: String {
        var parts: [String] = []
        for (key, value) in self {
            let part = String(format: "%@=%@",
                String(describing: key).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,
                String(describing: value).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            parts.append(part as String)
        }
        return parts.joined(separator: "&")
    }
    
}

extension URL {
    /**
     Creates a new URL by adding the given query parameters.
     @param parametersDictionary The query parameter dictionary to add.
     @return A new URL.
    */
    func appendingQueryParameters(_ parametersDictionary : Dictionary<String, String>) -> URL {
        let URLString : String = String(format: "%@?%@", self.absoluteString, parametersDictionary.queryParameters)
        return URL(string: URLString)!
    }
}

用法

let url = URL(string: "https://google.com/")!
    .appendingQueryParameters([
        "key1": "val1",
        "key2": "val2",
    ])
let request = URLRequest(url: url)
// run request
于 2021-08-29T05:17:24.067 回答