Skip to content

How to generate oauth 1 “oauth/token/request” in magento 2?

I am trying to generate oauth 1 oauth/token/request for magento 2, I am using the below code

$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';

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

        $dateTime = new DateTime();


        $oauthConsumerKey = $authData['oauth_consumer_key'];
        $oauthVerifier = $authData['oauth_verifier'];
        $oauthConsumerSecret = $authData['oauth_consumer_secret'];
        $storeBaseUrl = $authData['store_base_url'];
        $outhTimestamp = $dateTime->format('U');
        $oauthNonce = $nonce;
        $storeBaseUrl = $authData['store_base_url'];
         
        $base = 'POST&'.$storeBaseUrl.'&'
        ."oauth_consumer_key=".$oauthConsumerKey
        .'&oauth_nonce='.$oauthNonce
        .'&oauth_signature_method=HMAC-SHA256'
        .'&oauth_timestamp='.$outhTimestamp
        .'&oauth_version='.'1.0';

        $signature = rawurlencode(base64_encode(hash_hmac("sha1", $base, rawurlencode($oauthConsumerSecret), true)));

In above code I have oauth_consumer_key, oauth_verifier, oauth_consumer_secret, these all I am getting in the callback URL which I passed while creating Integration in magento admin panel.

My HTTP request is below

$headers = [
            'Content-Type' => 'application/json',
            'Authorization' => 'OAuth oauth_consumer_key="'.$oauthConsumerKey.'",oauth_signature_method="HMAC-SHA256",oauth_timestamp="'.$outhTimestamp.'",oauth_nonce="'.$oauthNonce.'",oauth_verifier="'.$oauthVerifier.'",oauth_signature="'.$signature.'"',
        ];


        $response = Http::withHeaders($headers)->post('https://magento.dev/oauth/token/request');

Below are the variables values which I am passing in the HTTP request

oauthConsumerKey
5zgrXXXXXXa48z4gvjlik0
oauthVerifier
vi9e9cfzXXXXfrz9uu66exk833r
outhTimestamp
1676558767
oauthNonce
YrA0cTizdSi1iWFaAwMvLQ26QVWDDVUF
$signature
C0ED4Lfpj%2B7xRHOWYPpJn7%2F6fn0%3D 

I am getting below response
oauth_problem=The+signature+is+invalid.+Verify+and+try+again.

Below is the Postman request which return the access token and access token secret

$client = new Client();
$headers = [
  'Content-Type' => 'application/json',
  'Authorization' => 'OAuth oauth_consumer_key="5zgr9g5mXXXXXp7a48z4gvjlik0",oauth_signature_method="HMAC-SHA256",oauth_timestamp="1676558288",oauth_nonce="fCIN21MqTei",oauth_verifier="uq2ttix8gpjlniXXXX1msdu029",oauth_signature="CNbMzhVuEDkXXXX8R2H1KY8Binhvg5PGw1%2FE%3D"',
];
$request = new Request('POST', 'https://magento.dev/oauth/token/request', $headers);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();

Let me what I am doing wrong, any reference code or example much appreciated!!
Thanks