PHP json_decode 关键词不被解析的处理方法

如果 JSON 数据中包含了 PHP 的关键字,如 true、false 或者 null,则 json_decode() 函数将无法成功解析该数据。

因此可以使用单独判断的方式

 $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        $v = $v === null ? 'null' : $v;

sha256 demo

<?php

function sign($accessKey, $timestamp, $secretKey, $body)
{
    $obj_json = $body ? json_decode($body, true) : array();
    $obj_json['timestamp'] = $timestamp;
    $obj_json['accessKey'] = $accessKey;
    unset($obj_json['sign']);
    ksort($obj_json);
    array_walk($obj_json, function (&$v, $k) {
        $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        $v = $v === null ? 'null' : $v;
        $v = is_array($v) ? ("$k=" . json_encode($v)) : "$k=$v";
    });
    $obj_str = implode("&", $obj_json) . $secretKey;
    var_dump($obj_str);
    return hash('sha256', $obj_str);
}


$accessKey = '11111111';
$secretKey = '22222222';
$body = "{\"deliveryWarehouse\":\"CESHI\",\"isSubmit\":false,\"planningNo\":\"20230612-test\",\"trackType\":\"101102\",\"bolNo\":\"123\",\"landCarrier\":\"fedex\",\"landEta\":\"2023-07-23\",\"details\":[{\"goodsNum\":10,\"goodsCode\":\"2020\"}]}";

$timestamp = '1682494538291';

$sign = sign($accessKey, $timestamp, $secretKey, $body);
echo $sign;

posted @ 2023-06-12 14:05  vx_guanchaoguo0  阅读(66)  评论(0编辑  收藏  举报