Skip to content

Instantly share code, notes, and snippets.

@britbarn
Created July 25, 2020 20:51
Show Gist options
  • Save britbarn/cb8d2e6a27a54634418028d6c941c604 to your computer and use it in GitHub Desktop.
Save britbarn/cb8d2e6a27a54634418028d6c941c604 to your computer and use it in GitHub Desktop.
<?php
namespace App\NSClasses;
class OAuth
{
public function __construct()
{
$this->baseUrl = 'https://'.$YOUR_ACCOUNT_NUMBER.'suitetalk.api.netsuite.com/services/rest/record/v1';
$this->signatureMethod = 'HMAC-SHA256';
$this->nonce = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
$this->timestamp = time();
$this->version = '1.0';
$this->account = $YOUR_ACCOUNT_NUMBER;
$this->consumerKey = env('NETSUITE_CONSUMER_KEY');
$this->tokenId = env('NETSUITE_TOKEN_ID');
$this->consumerSecret = env('NETSUITE_CONSUMER_SECRET');
$this->tokenSecret = env('NETSUITE_TOKEN_SECRET');
}
public function makeRequest($httpMethod, $path)
{
$baseString = $httpMethod . '&' . rawurlencode($this->baseUrl . $path) . "&"
. rawurlencode("oauth_consumer_key=" . rawurlencode($this->consumerKey)
. "&oauth_nonce=" . rawurlencode($this->nonce)
. "&oauth_signature_method=" . rawurlencode($this->signatureMethod)
. "&oauth_timestamp=" . rawurlencode($this->timestamp)
. "&oauth_token=" . rawurlencode($this->tokenId)
. "&oauth_version=" . rawurlencode($this->version));
$key = rawurlencode($this->consumerSecret) . '&' . rawurlencode($this->tokenSecret);
$signature = base64_encode(hash_hmac('sha256', $baseString, $key, true));
$header = array(
"Authorization: OAuth
realm=\"$this->account\",oauth_consumer_key=\"$this->consumerKey\",oauth_token=\"$this->tokenId\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"$this->timestamp\",oauth_nonce=\"$this->nonce\",oauth_version=\"$this->version\",oauth_signature=\"$signature\"",
"Cookie: NS_ROUTING_VERSION=LAGGING",
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $this->baseUrl . $path,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $httpMethod,
CURLOPT_HTTPHEADER => $header,
));
$response = curl_exec($curl);
curl_close($curl);
var_dump($response);
}
}
@cjsinnbeck
Copy link

Thanks for this! I had forgotten the "true" parameter in the hash_hmac function (to make it return raw binary data). Your gist saved me after hours of going over the code. Much appreciated.

@mk-j
Copy link

mk-j commented Aug 1, 2022

NetSuite uses an 11 character nonce, so it should be:

$this->nonce = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 11);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment