B2W REST / JSON API -failed to open stream: HTTP request failed! HTTP / 1.1 401 Unauthorized

0

I'm starting an integration with B2W, they use a REST / JSON API, I am not finding where it is wrong in my code, it is something relative to the header, as I test with the chrome dhc complement and register the change correctly:

Mycode:

$url='https://api-sandbox.bonmarketplace.com.br/sku/10205_SKU1/price';$data=json_encode(array("sellPrice"=> "400.00",
            "listPrice"=> "400.00"
            )
    );  
//echo "<br>".$usuario = base64_encode("$username:");
//Content-Type:application/json;charset=utf-8;

$options = array(
    "http" => array(
        "method" => "PUT",
        "header" => "Content-Type: [application/json; charset=UTF-8; Authorization: Basic NjU5NjdGQkZBMDEzNjUwMTkyNzc1OTQ5MDI2NjUzNEU6",
        "content" => $data
));
print_r($options);
$context = stream_context_create($options);
print_r($context);
// make the request
$response = file_get_contents($url, false, $context);

Unauthorized 401 error

    
asked by anonymous 08.08.2015 / 16:23

1 answer

1

I'm not experienced in PHP, but as URL calls I only know how to do with cURL, here is an example that does not return any error

<?php
    $url = 'http://api-sandbox.bonmarketplace.com.br/sku/10205_SKU1/price';
    $data = json_encode(
               array(
                  "sellPrice"=> "400.00",
                  "listPrice"=> "550.00"
               ));  
?>
<?php
    // usando cURL
    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "PUT",
      CURLOPT_POSTFIELDS => $data,
      CURLOPT_HTTPHEADER => array(
        "authorization: Basic NjU5NjdGQkZBMDEzNjUwMTkyNzc1OTQ5MDI2NjUzNEU6",
        "content-type: application/json;charset=UTF-8"
      ),
    ));

    $chleadresult = curl_exec($curl);
    $chleadapierr = curl_errno($curl);
    $chleaderrmsg = curl_error($curl);
    curl_close($chlead);
?>
<hr>
<h2>$chleadresult</h2>
<pre><?php echo $chleadresult ?></pre>
<h2>$chleadapierr</h2>
<pre><?php echo $chleadapierr ?></pre>
<h2>$chleaderrmsg</h2>
<pre><?php echo $chleaderrmsg ?></pre>

But I think the problem is even the validation of header , because in the code that shows it should be written as:

$options = array(
    "http" => array(
        "method" => "PUT",
        "header" => array(
            "Content-Type: application/json; charset=UTF-8",
            "Authorization: Basic NjU5NjdGQkZBMDEzNjUwMTkyNzc1OTQ5MDI2NjUzNEU6"
        ),
        "content" => $data
));

Now, if you use the Postman tool (free of charge), once you make a request , you have this request available in a variety of languages, including 3 versions of PHP:

    
12.08.2015 / 00:14