Saturday, November 24, 2018

Invoke an HTTP POST method using Php with RESTlet

This is a guide on how to use an HTTP POST method using PHP with RESTlet to save a customer record. The request data is a json string included in the context parameter of the file_get_contents function. Note that "application/xml" is not a supported content type.

RESTlet Code

function saveCustomer(request){
    if(request != null && request != ""){
        var record = nlapiCreateRecord('customer');

        record.setFieldValue('isperson',request.isperson);
record.setFieldValue('companyname',request.companyname);

        var id = nlapiSubmitRecord(record);
        return id;
    }
}

Sample PHP code

 

/**Host is the external URL found in the RESTlet deployment page */
$host ="https://rest.netsuite.com/app/site/hosting/restlet.nl?script=167&deploy=1";
$context = makeContext();

$response = file_get_contents($host, false, $context);

if (!$response) 
echo "An error occured while trying to save record.";  
else
echo "Customer record saved (ID: " . $response .")";

/** Returns a stream context with the Authorization Header and Content set */
function makeContext(){    
$data = array('companyname' => "My Sample Company", 'isperson' => "F");
$json_string =  json_encode($data);

$options = array(
'http'=>array(
'header'=> makeHeaderString(),
'method'=>"POST",
'timeout'=>300,
'content' => $json_string
)
);
     return stream_context_create($options);
}

 
function makeHeaderString(){
$account  = "TSTDRV123456";
$email  = "me@email.com";
$pass = "password";
$role_id = "3";
$content_type = "application/json"; //other possible value: "text/plain" ;

return  "Authorization: NLAuth nlauth_account=". $account . ", " .
"nlauth_email=" . $email . ", " .
"nlauth_signature=" . $pass . ", " .
"nlauth_role=" . $role_id . "\r\n".
"Host: rest.netsuite.com \r\n" .
"Content-Type:" . $content_type;  
}

 

No comments:

Post a Comment