1

We cannot integrate with 3rd Systems like ERP with Callback URL or Identity URL in some cases.

The git repository available can be used to call Oauth request from PHP https://github.com/daviddesberg/PHPoAuthLib

But in case of calling Magento2 Oauth is tricky.

Need PHP Script to demonstrate Oauth call with signature generation process.

1

3 Answers 3

1

You can still use the bearer token authentication method but it is not considered secure anymore. To do so, you need to enable a config flag: Allow OAuth Access Tokens to be used as standalone Bearer tokens

see screenshot below enter image description here

2
  • I agree, but, Magento now recommends to use O-Auth over Standalone bearer token.
    – Sachin
    Aug 30, 2022 at 9:41
  • 1
    Full agreeing with you @sachin. my answer is only a solution for you to move on but you are right, we need to have the OAuth1.0 fully sorted Aug 30, 2022 at 9:49
1

Update: I have 2 options for you.

Option 1: Improved version of Magento's OAuth demo scripts

I have created a demo OAuth 1.0a application which can receive tokens from Magento 2.x: https://github.com/jeroenvermeulen/magento2_oauth_example

Option 2: Laravel example

I managed to get real OAuth working using: https://github.com/justbetter/laravel-magento-client.

You need to install Laravel on a web hosting account running PHP 8.1 or newer. Beware of this security note about the Identity endpoint.

In SSH on the hosting account:

cd ~
composer create-project --prefer-dist laravel/laravel magento2oauth
cd magento2oauth
composer require justbetter/laravel-magento-client

Edit the file .env, add to bottom:

MAGENTO_BASE_URL=https://__YOUR_MAGENTO_DOMAIN__/
MAGENTO_AUTH_METHOD=oauth

Edit the file routes/web.php. add to bottom:

Route::get('/api-product', function () {
    return view('api-product');
});

Create the file resources/views/api-product.php with content:

<!DOCTYPE html>
<html><body><pre>
<?php
$magento = app(\JustBetter\MagentoClient\Client\Magento::class);
$search = \JustBetter\MagentoClient\Query\SearchCriteria::make()
            ->select('items')
            ->paginate(1, 50)
            ->get();
foreach ($magento->lazy('products', $search) as $product) {
    print json_encode($product, JSON_PRETTY_PRINT);
}
?></pre></body></html>

Execute:

ln -sfn ~/magento2oauth/public ~/httpdocs/m2oauth
  • In Magento 2.x go to: System > Integrations
  • Create an integration:
    • Callback URL: https://__LARAVEL_HOSTNAME__/m2oauth/magento/oauth/callback
    • Identity link URL: https://__LARAVEL_HOSTNAME__/m2oauth/magento/oauth/identity
    • Make sure you give rights to the Catalog/Inventory/Products using the API tab in the sidebar.
    • Save the Integration
  • Activate the Integration, this will call the Identity and Callback endpoints

When everything works you can view products on the URL: https://__LARAVEL_HOSTNAME__/m2oauth/api-product

0

Refer to PHP script below to call Magento 2 Oauth 1.0 with generated oauth_signature

<?php
//First of all, generate Integration Keys in Magento 2 Admin from
//system -> Integrations -> Add New Integration
// -> Fill in all details except Callback & identity URLs
$magentoBaseUrl  = 'http://your-site-url/';

/** START: GET REQUEST */
$apiURL          = "rest/V1/store/websites";
$method          = "GET";
$bodyParams      = [];
/** END: GET REQUEST */
/** START: POST REQUEST */
//Uncomment below lines for POST REQUEST
// $apiURL          = "rest/V1/customV2";
// $method          = "POST";
// $bodyParams      = [
//   "some_key" => [
//     "some_key1" => "1212q",
//     "some_key2"  => "1212q"
//   ]
// ];
/** END: POST REQUEST */

$url             = $magentoBaseUrl . $apiURL;
$consumerKey     = "<paste_consumer_key>";
$consumerSecret  = "<paste_consumer_secret>";
$tokenSecret     = "<paste_token_secret>";
$accessToken     = "<paste_access_token>";
$signatureMethod = "HMAC-SHA256";
$version         = "1.0";

function generateSignature($url, $parameters, $method, $consumerSecret, $tokenSecret)
{
    $uriParts = parse_url($url);
    $query = isset($uriParts['query']) ? $uriParts['query'] : '';
    parse_str($query, $queryStringData);
    foreach (array_merge($queryStringData, $parameters) as $key => $value) {
      $signatureData[rawurlencode($key)] = rawurlencode($value);
    }
    ksort($signatureData);
    $signatureString = '';
    $delimiter = '';
    foreach ($signatureData as $key => $value) {
        $signatureString .= $delimiter . $key . '=' . $value;
        $delimiter = '&';
    }
    $baseString = strtoupper($method) . '&';
    $baseString .= rawurlencode($url) . '&';
    $baseString .= rawurlencode($signatureString);
    $signingKey = rawurlencode($consumerSecret) . '&' . rawurlencode($tokenSecret);
    return base64_encode(hash_hmac('sha256', $baseString, $signingKey, true));;
}
function generateNonce($length = 32)
{
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';

    $nonce = '';
    $maxRand = strlen($characters)-1;
    for ($i = 0; $i < $length; $i++) {
        $nonce.= $characters[rand(0, $maxRand)];
    }

    return $nonce;
}
$dateTime = new \DateTime();
$parameters = [
  'oauth_consumer_key'     => $consumerKey,
  'oauth_nonce'            => generateNonce(),
  'oauth_signature_method' => $signatureMethod,
  'oauth_timestamp'        => $dateTime->format('U'),
  'oauth_version'          => $version,
  'oauth_token'            => $accessToken
];
$uriParts = parse_url($url);
$parameters['oauth_signature'] = generateSignature($url, $parameters, $method, $consumerSecret, $tokenSecret);

$authorizationHeader = 'OAuth ';
$delimiter = '';
foreach ($parameters as $key => $value) {
  $authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"';
  $delimiter = ', ';
}
$authorizationHeader = array(
  'Authorization' => $authorizationHeader
);
foreach ($authorizationHeader as $key => &$val) {
  $key = ucfirst(strtolower($key));
  $val = ucfirst(strtolower($key)) . ': ' . $val;
}

if ($method === 'POST' && is_array($bodyParams)) {
  $authorizationHeader['Content-Type'] = 'Content-Type: application/json';
}
$authorizationHeader['Host']       = 'Host: ' . $uriParts['host'];
$authorizationHeader['Connection'] = 'Connection: close';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

if ($method === 'POST' || $method === 'PUT') {
  if ($method === 'PUT') {
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  } else {
      curl_setopt($ch, CURLOPT_POST, true);
  }

  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($bodyParams));
} else {
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);

curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $authorizationHeader);

$response     = curl_exec($ch);
//var_dump($response);
$responseArray = json_decode($response);
echo "Response: " . print_r($responseArray, true);
echo "\n";
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//var_dump($responseCode);
echo "\n Response Code: " . $responseCode;
echo "\n";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.