
本文详解如何在 php 中使用 json_encode() 构建符合托管支付页面(hpp)要求的嵌套 json 数据,重点解决 field_configuration 等多层嵌套对象的数组语法问题,避免因结构错误导致的解析失败或语法报错。
本文详解如何在 php 中使用 json_encode() 构建符合托管支付页面(hpp)要求的嵌套 json 数据,重点解决 field_configuration 等多层嵌套对象的数组语法问题,避免因结构错误导致的解析失败或语法报错。
在 PHP 中生成符合 HPP 接口规范的 JSON 数据时,关键在于严格对应 JSON 的数据类型语义:PHP 关联数组(['key' => 'value'])映射为 JSON 对象({}),而索引数组([])映射为 JSON 数组([])。尤其当涉及 field_configuration 这类深度嵌套结构时,任何层级的类型错用(如用关联数组代替索引数组表示列表)都会导致 json_encode() 输出异常,或服务端解析失败(常见错误如 Unexpected token ] 或 Expected \])。
以下是一个完整、可直接运行的示例,整合了原始 JSON 中的所有核心字段,并正确嵌套 field_configuration:
<?php
$encryptionKey = 'hpp_encryption_key';
// ✅ 正确构建嵌套 JSON 数据:使用关联数组表示对象,索引数组表示列表
$data = json_encode([
'id' => '11e8052891d6420cb7a5ca18',
'stylesheet_url' => 'https://127.0.0.1/css/payform.css',
'field_configuration' => [
'body' => [
'fields' => [
// ✅ 字段列表必须是索引数组(即使只有一个元素)
[
'id' => 'transaction_amount',
'label' => 'Amount',
'value' => '25.00'
],
// 可继续追加其他字段,例如:
// [
// 'id' => 'customer_email',
// 'label' => 'Email',
// 'value' => ''
// ]
]
]
],
'redirect_url_on_approve' => 'https://some.full.url',
'redirect_url_on_decline' => 'https://www.bing.com',
'redirect_url_delay' => '15',
'parent_send_message' => 0,
'hide_optional_fields' => 0,
'min_payment_amount' => '10',
'max_payment_amount' => '20'
]);
// 验证 JSON 格式是否合法(开发阶段强烈建议)
if ($data === false) {
throw new RuntimeException('JSON encoding failed: ' . json_last_error_msg());
}
// 后续加密逻辑(保持原样)
$salt = openssl_random_pseudo_bytes(8);
$salted = '';
$dx = '';
while (strlen($salted) < 48) {
$dx = md5($dx . $encryptionKey . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32, 16);
$encryptedString = openssl_encrypt($data, 'aes-256-cbc', $key, true, $iv);
$encodedEncryptedString = urlencode(base64_encode("Salted__" . $salt . $encryptedString));
echo "https://{{sandbox_url}}/hostedpaymentpage?id={{hosted_payment_page_id}}&data=$encodedEncryptedString\n";⚠️ 关键注意事项:
- fields 是一个 JSON 数组(即 PHP 索引数组),因此必须写作 [ [...] ],而非 ['fields' => [...]] —— 后者会错误地将整个字段列表当作单个关联项。
- 所有字符串值(包括 URL、ID、标签等)应使用单引号包裹,避免意外转义;若值中含单引号,需转义或改用双引号。
- 建议在 json_encode() 后调用 json_last_error() 检查编码结果,及时捕获结构错误(如未闭合括号、非法字符等)。
- 实际部署前,请确保 $encryptionKey 与 HPP 平台配置的密钥完全一致,且 openssl_encrypt() 所需的 OpenSSL 扩展已启用。
通过遵循“对象→关联数组,数组→索引数组”的映射原则,并结合结构化验证,即可稳定生成合规的加密 payload,顺利对接托管支付页面。
立即学习“PHP免费学习笔记(深入)”;



















