如何在Magento 2中使用自定义REST API返回JSON对象?


14

我正在编写一个自定义的REST API演示;现在它可以在演示中返回数字和字符串,但是我希望它像其他REST API一样返回JSON对象。

在我的演示中,我使用curl 调用了Magento 2 API(即,获取客户信息:http://localhost/index.php/rest/V1/customers/1),它返回一个JSON字符串:

“ {\” id \“:1,\” group_id \“:1,\” default_billing \“:\” 1 \“,\” created_at \“:\” 2016-12-13 14:57:30 \“ ,\“ updated_at \”:\“ 2016-12-13 15:20:19 \”,\“ created_in \”:\“默认商店视图\”,\“电子邮件\”:\“ 75358050@qq.com \ “,\”名字\“:\” azol \“,\”姓氏\“:\”年轻\“,\” store_id \“:1,\”网站ID \“:1,\”地址\“:[{ \“ id \”:1,\“ customer_id \”:1,\“ region \”:{\“ region_code \”:\“ AR \”,\“ region \”:\“ Arad \”,\“ region_id \“:279},\” region_id \“:279,\” country_id \“:\” RO \“,\” street \“:[\” abc \“],\”电话\“:\” 111 \ “,\”邮政编码\“:\”1111 \“,\” city \“:\” def \“,\”名字\“:\” azol \“,\”姓氏“:\”年轻\“,\” default_billing \“:true}], \“ disable_auto_group_change \”:0}“

响应是一个JSON字符串,但是所有键中都包含一个斜杠。我知道我可以用删除斜线str_replace,但这是一种愚蠢的方法。还有其他方法可以在键中不带斜杠的情况下返回JSON对象吗?

************更新2016.12.27 ************

我在这里粘贴了测试代码:

   $method = 'GET';
    $url = 'http://localhost/index.php/rest/V1/customers/1';

    $data = [
        'oauth_consumer_key' => $this::consumerKey,
        'oauth_nonce' => md5(uniqid(rand(), true)),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_timestamp' => time(),
        'oauth_token' => $this::accessToken,
        'oauth_version' => '1.0',
    ];

    $data['oauth_signature'] = $this->sign($method, $url, $data, $this::consumerSecret, $this::accessTokenSecret);

    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => [
            'Authorization: OAuth ' . http_build_query($data, '', ','),
            'Content-Type: application/json'
        ], 
    ]);

    $result = curl_exec($curl);
    curl_close($curl);

    // this code has slash still
    //return stripslashes("hi i\" azol"); 

    // has slashes still
    //return stripcslashes("{\"id\":1,\"group_id\":1,\"default_billing\":\"1\",\"created_at\":\"2016-12-13 14:57:30\",\"updated_at\":\"2016-12-13 15:20:19\",\"created_in\":\"Default Store View\",\"email\":\"75358050@qq.com\",\"firstname\":\"azol\",\"lastname\":\"young\",\"store_id\":1,\"website_id\":1,\"addresses\":[{\"id\":1,\"customer_id\":1,\"region\":{\"region_code\":\"AR\",\"region\":\"Arad\",\"region_id\":279},\"region_id\":279,\"country_id\":\"RO\",\"street\":[\"abc\"],\"telephone\":\"111\",\"postcode\":\"1111\",\"city\":\"def\",\"firstname\":\"azol\",\"lastname\":\"young\",\"default_billing\":true}],\"disable_auto_group_change\":0}");

    // has slashes still
    //return json_encode(json_decode($result), JSON_UNESCAPED_SLASHES);

    // this code will throw and expcetion:
    // Undefined property: *****\*****\Model\Mycustom::$_response
    //return  $this->_response->representJson(json_encode($data));

    return $result;

你试试return json_encode($result, JSON_UNESCAPED_SLASHES);吗?
Khoa TruongDinh

是的,我已经尝试过,它将引发异常,因为$ result是一个字符串
azol.young,2016年

请尝试另一种方式:$json_string = stripslashes($result)return json_decode($json_string, true);
Khoa TruongDinh

Answers:


1

我们可以用json_encodeJSON_UNESCAPED_SLASHES

json_encode($response, JSON_UNESCAPED_SLASHES);

嗨,是的,我已经在代码中做到了,但是仍然有斜线
azol.young,2016年

您是否尝试过stripslashes()功能或json_encode($str, JSON_UNESCAPED_SLASHES);
Khoa TruongDinh

阅读我的最新答案。
Khoa TruongDinh,2013年

1
尝试$ this-> _ response-> representJson(json_encode($ data));
Pratik

嗨,科阿,谢谢!我尝试过为您编码“ json_encode($ response,JSON_UNESCAPED_SLASHES);” 和stripslashes(“ hi i \” azol“);,它仍然带有斜线.......
azol.young

1

在magento 2的根目录中创建ws.php,并将以下代码粘贴到文件中:

<?php
    use Magento\Framework\App\Bootstrap;
    require __DIR__ . '/app/bootstrap.php';
    $params = $_SERVER;
    $bootstrap = Bootstrap::create(BP, $params);


    function sign($method, $url, $data, $consumerSecret, $tokenSecret)
    {
        $url = urlEncodeAsZend($url);
        $data = urlEncodeAsZend(http_build_query($data, '', '&'));
        $data = implode('&', [$method, $url, $data]);
        $secret = implode('&', [$consumerSecret, $tokenSecret]);
        return base64_encode(hash_hmac('sha1', $data, $secret, true));
    }

    function urlEncodeAsZend($value)
    {
        $encoded = rawurlencode($value);
        $encoded = str_replace('%7E', '~', $encoded);
        return $encoded;
    }

    // REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
    $consumerKey = 'YOUR_CONSUMER_KEY';
    $consumerSecret = 'YOUR_CONSUMER_SECRET';
    $accessToken = 'YOUR_ACCESS_TOKEN';
    $accessTokenSecret = 'YOUR_ACCESS_TOKEN_SECRET';

    $method = 'GET';
    $url = 'http://localhost/magento2/rest/V1/customers/1';

//
$data = [
    'oauth_consumer_key' => $consumerKey,
    'oauth_nonce' => md5(uniqid(rand(), true)),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_timestamp' => time(),
    'oauth_token' => $accessToken,
    'oauth_version' => '1.0',
];

$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url,
    CURLOPT_HTTPHEADER => [
        'Authorization: OAuth ' . http_build_query($data, '', ',')
    ]
]);

$result = curl_exec($curl);
curl_close($curl);

echo $result;

$response = \Zend_Json::decode($result);
echo "<pre>";
print_r($response);
echo "</pre>";

之后,使用浏览器中的http://localhost/magento2/ws.php之类的链接运行此文件,然后检查输出。


1

我尝试使用以下脚本来测试在相同的API响应中是否出现斜杠:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.test/rest/all/V1/customers/12408");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer oc34ouc8lvyvxcbn16llx7dfrjygdoh2', 'Accept: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// grab URL and pass it to the browser
$result = curl_exec($ch);

var_dump($result);

// close cURL resource, and free up system resources
curl_close($ch);

产生此响应(被PHP的var_dump函数截断):

$ php -f apitest2.php 
/var/www/html/dfl/htdocs/apitest2.php:14:
string(1120) "{"id":12408,"group_id":13,"default_billing":"544","default_shipping":"544","created_at":"2018-05-24 08:32:59","updated_at":"2018-05-24 08:32:59","created_in":"Default Store View","email":"...

如您所见,在我的回应中没有任何斜线。

因此,我建议您有两种选择:

  • 研究为什么您的cURL配置返回带有斜杠的响应。也许与使用oauth有关?看起来有些东西正在从cURL中获取原始响应,然后尝试做某事(例如将其输出),并在此过程中添加斜杠
  • 坚持寻找使用str_replace或类似方法去除斜线的方法。

获得无斜杠的响应后,可以使用以下一行代码来强制PHP将字符串转换为JSON对象:

$object = json_decode( $output, false, 512, JSON_FORCE_OBJECT);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.