magentomagento2magento-rest-api

I tried Magento API, but I got message "401 Authorization Required"


I want to use Magento API for my sites and I want "full headless commerce". I ran the following PHP code. I got "token". But I couldn't add customer. Why?

401 Authorization Required nginx/1.10.1

<?php
$userData = array("username" => "API_USER", "password" => "API_PATH");
$ch = curl_init("http://BASIC_AUTH_USER:BASIC_AUTH_PASSWORD@BASE_URL/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Length: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
$token=  json_decode($token);

$customerData = [
    'customer' => [
        'email' => "user@example.com",
        'firstname' => "John",
        'lastname' => "Doe",
        'storeId' => 1,
        'websiteId' => 1
    ],
    'password' => "Demo1234"
];

$ch = curl_init("http://BASIC_AUTH_USER:BASIC_AUTH_PASSWORD@BASE_URL/rest/V1/customers");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
curl_setopt($ch, CURLOPT_HTTPHEADER,
    array("Content-Type: application/json", "Authorization: Bearer ".$token)
);

$result = curl_exec($ch);
$result = json_decode($result);

Solution

  • I added basic authentication to the header. It moved!!