How to update Magento order status and state using REST API and PHP

Here’s a snippet on how to update your Magento order status (or/and state) using Magento’s REST API and PHP via cURL.


function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);

$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);

$secret = implode('&', [$consumerSecret, $tokenSecret]);

return base64_encode(hash_hmac('sha1', $data, $secret, true));
}

function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}

// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = 'xxxxivkgfrn3ntb0t2zmtjdnbzduq2i4';
$consumerSecret = 'xxxqy25bj73k2gtk2nwes6dhxx5awqs8';
$accessToken = 'xxx1iskiuuqnxciv3ydbxb0d2i4bfua2';
$accessTokenSecret = 'xxxko3fvmrc3pbjqdpbyx5pm2viirpv2';

$method = 'POST';
$url = [REPLACE WITH YOUR STORE URL] . '/index.php/rest/V1/orders';

// GENERATE OAUTH TOKEN function
$data = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0',
];

$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);

// UPDATE ORDER STATUS
$entity_id = 1; // replace with your entity_id
$increment_id = 1; // replace with your increment_id. You must have this so as not to increment this value
$state = "pending"; //complete, pending, etc..
$status = "pending"; //complete, pending, etc..

$request_url= [REPLACE WITH YOUR STORE URL] . '/index.php/rest/V1/orders';
$data_json = [
"entity"=> [
"entity_id" => $entity_id,
"increment_id" => $increment_id,
"state" => $state,
"status" => $status
]
];

$data_string = json_encode($data_json);
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string) .'',
'Authorization: OAuth ' . http_build_query($data, '', ','))
);
$response = curl_exec($ch);
$response = json_decode($response);
print_r($response);
curl_close($ch);

OAuth authentication function by rafaelstz.