2

所以我想做的是使用支付宝https://global.alipay.com/docs/ac/ams/api API进行一些 API 调用

我按照集成指南创建了 nessassary 私钥/公钥和客户端 ID。我还按照这里的生成签名指南:https ://global.alipay.com/docs/ac/ams/digital_signature#gNWs0

我还复制了支付宝开发者工具iTest的部分代码,所以实际上功能signWithSHA256RSA来自支付宝。

我知道我的私钥应该可以工作,因为我能够使用支付宝的开发者工具成功测试相同的请求。

// generate ISO 8601 date
$oDateTime = new \DateTime();
$sDate = $oDateTime->format('c');

$privatekey = '<private_key_removed>';

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, 'https://open-eu.alipay.com/ams/api/v1/payments/pay');

$reqBody = json_encode(array('productCode' => 'IN_STORE_PAYMENT'));

$headers = array();
$headers[] = "Content-Type:application/json; charset=UTF-8";
$headers[] = "Request-Time:".$sDate;
$headers[] = "client-id:<client_id_removed>";
$headers[] = "Signature:". "algorithm=RSA256,keyVersion=1,signature=".signWithSHA256RSA($sDate, $reqBody, $privatekey);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POST, true);

curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
$rspContent = curl_exec($curl);

function signWithSHA256RSA($timeString, $reqBody, $privateKey){

  $priKey = "-----BEGIN RSA PRIVATE KEY-----\n". 
            wordwrap($privateKey, 64, "\n", true).
            "\n-----END RSA PRIVATE KEY-----";

  $signContent = "POST /ams/api/v1/payments/pay"."\n<client_id_removed>".".".$timeString. ".".$reqBody;
  
  openssl_sign($signContent, $signValue, $priKey, OPENSSL_ALGO_SHA256);

  return base64_encode($signValue);
}

我得到的错误代码是:

{"result":
 {
  "resultCode":"PARAM_ILLEGAL",
  "resultMessage":"illegal parameter:OpenapiV2签名字段异常: algorithm=RSA256,keyVersion=1,signature=<signature_removed>",
"resultStatus":"F"}
}
4

1 回答 1

3

谷歌翻译出错:“签名字段异常”->“签名字段异常”

  1. 验证签名。替换$privateKey$publicKey来自你的秘密。
$data = 'POST ...';
$keyPair = openssl_pkey_new(
    [
        'private_key_bits' => 2048,
        'private_key_type' => OPENSSL_KEYTYPE_RSA,
    ]
);
openssl_pkey_export($keyPair, $privateKey);
$details = openssl_pkey_get_details($keyPair);
$publicKey = $details['key'];
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
var_dump($signature);
//verify signature
$isValidSignature = openssl_verify(
    $data,
    $signature, 
    $publicKey, 
    'sha256WithRSAEncryption'
);
var_dump($isValidSignature);
  1. 在文档中说 generatedSignature=base64UrlEncode(sha256withrsa(<Content_To_Be_Signed>), <privateKey>))

并提供了java示例

return URLEncoder.encode(new String(Base64.encodeBase64(signed), "UTF-8"), "UTF-8");

php等价于

urlencode(base64_encode($signature))

于 2022-01-10T01:02:05.877 回答