文章目录
-
- 对接吐槽
- 代码展示
- 小结
对接吐槽
建行对接过于逆天
代码展示
订单推送类
public function order_send($data,$type)
{
try {
$url = 'https://yunbusiness.ccb.com/tp_service/txCtrl/server?txcode='.$type;
$cnt = base64_encode((new Tools())->encrypt($data));
$mac = strtoupper(md5(json_encode($data) . (new Tools())->privateKey));
$body = [
'cnt' => $cnt,
'mac' => $mac,
'svcid' => '',
];
$client = new \GuzzleHttp\Client();
$res = $client->post($url, [
'headers' => [
"Accept" => 'application/json',
"Content-type" => 'application/json'
],
'json' => $body
]);
$content = $res->getBody()->getContents();
$res = json_decode($content, true);
$cnt = $res['cnt'] ?? '';
return json_decode((new Tools())->decrypt(base64_decode($cnt)), true);
} catch (\Exception $exception) {
dump($exception->getMessage());
}
}
工具类
protected $publicKey = null;
public $privateKey = null;
public function __construct()
{
$this->publicKey = '公钥';
$this->privateKey = "私钥";
}
protected function getPublicKey()
{
return "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($this->publicKey, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
}
protected function getPrivateKey()
{
$search = [
"-----BEGIN RSA PRIVATE KEY-----",
"-----END RSA PRIVATE KEY-----",
"\n",
"\r",
"\r\n"
];
$privateKey = str_replace($search, "", $this->privateKey);
return $search[0] . PHP_EOL . wordwrap($privateKey, 64, "\n", true) . PHP_EOL . $search[1];
}
/**
* 公钥加密
* @throws \Exception
*/
public function encrypt($data): string
{
$publicKey = openssl_pkey_get_public($this->getPublicKey());
if (!$publicKey) {
throw new \Exception("公钥不可用");
}
// data为数组的时候转成json
if (!is_string($data)) {
$data = json_encode($data);
}
$crypto = '';
foreach (str_split($data, 117) as $chunk) {
openssl_public_encrypt($chunk, $encryptData, $publicKey);
$crypto .= $encryptData;
}
return base64_encode($crypto);
}
/**
* 私钥解密
* @throws \Exception
*/
public function decrypt($encryptedData)
{
$privateKey = openssl_pkey_get_private($this->getPrivateKey());
if (!$privateKey) {
throw new \Exception("无法从Base64编码的字符串中获取私钥");
}
// 分段解密
$decryptedData = '';
$chunkSize = ceil(openssl_pkey_get_details($privateKey)['bits'] / 8); // 计算分块大小
$encryptedData = base64_decode($encryptedData);
$offset = 0;
while ($offset < strlen($encryptedData)) {
$chunkSizeActual = min($chunkSize, strlen($encryptedData) - $offset);
$chunk = substr($encryptedData, $offset, $chunkSizeActual);
$decryptedChunk = '';
openssl_private_decrypt($chunk, $decryptedChunk, $privateKey);
$decryptedData .= $decryptedChunk;
$offset += $chunkSizeActual;
}
// 假设解密后的数据是UTF-8编码的
return mb_convert_encoding($decryptedData, 'UTF-8', 'UTF-8');
}
小结
还是要吐槽一句建行文档过于逆天