php7 自行实现支付宝普通公钥签名方式

时间:2020-05-01

上代码

/**
 * 获取支付宝签名
 * @param array $data 请求参数数组
 * @return string 签名的sign
 */
function getAlipaySign($data)
{
    if (!isset($data['sign_type'])) {
        $data['sign_type'] = 'RSA2';
    }
    // 排序
    ksort($data);
    // 拼接
    $str = '';
    foreach ($data as $k => $v) {
        if (empty($v) && ($v !== 0)) {
            continue;
        }
        if ($k === 'sign') {
            continue;
        }
        if (empty($str)) {
            $str = $k . '=' . $v;
        } else {
            $str .= '&' . $k . '=' . $v;
        }
    }
    $secret = config('alipay.secret');
    $res = '-----BEGIN RSA PRIVATE KEY-----' . PHP_EOL .
        wordwrap($secret, 64, "\n", true) . PHP_EOL .
        '-----END RSA PRIVATE KEY-----';
    if (openssl_sign($str, $signature, $res, 'SHA256')) {
        return base64_encode($signature);
    }
    return '';
}

config('alipay.secret')   是用支付宝开放平台开发助手生成的应用私钥的一段字符串!

测试代码

$data = [
            'a' => 12,
            'b' => 2323
        ];
echo getAlipaySign($data);
Ki7i2oIcgGxLsb29YsbC5r9/YYioyaNtp6KamCqdchRMQOQVdUj851bjd0GYdorQna8pDbCvnkmqdtr8VoG72ogZN8TMapRQBzcl6z+B6gCAaV0H/PDnJOBQGxI47c6g98Jen8IKMGyBEzKj4xeV3h5671VfJa594ZhMej6OPHzSIq3dxbRoaZCuakJny4mkMPglqvimuFN/ApdtC5i6cd1RUlRqsAYQ8nBwevsrrtnVS+LuLAL8gwWC3NI2CQceE/t8N7XBcOieR5gXUWvFvaRlFmei+YaVE4lrFihr3gYMDImhs2BKYQNi55CMr0TX9FqwYWbcJDNYCK9EjiC7Cw==

与支付宝开放平台开发助手生成的签名一致!