0

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

2 Answers 2

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
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.