Authenticate with PHP
Hi,
I need to write a PHP script to create a contact but first I have to authenticate. I'm having trouble and could use some help. This is for a server script, when an event happens, we need to create a contact so there'll be no user around to handle a pop up to grant permission. I set up a new app in the dev portal and set the flow to device.
I wrote this function to get a device id:
unction getAuthRequest($client_id) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://authz.constantcontact.com/oauth2/default/v1/device/authorize',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'client_id=' . urlencode($client_id) . '&scope=openid',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$decodedResponse = json_decode($response, true);
// Check if device_code exists in the response
if (isset($decodedResponse['device_code'])) {
return $decodedResponse['device_code'];
} else {
return null; // Or return some error message or handle this scenario as per your need.
}
}
Then I wrote this function to get an auth token;
function getRequestToken($client_id, $device_code) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://authz.constantcontact.com/oauth2/default/v1/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'client_id=' . $client_id . '&device_code=' . $device_code . '&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
I had a previous bug and it might have run correctly but now it says that there is a pending, please try again later.
I don't know if I am doing this right, did I select the proper OAuth2 flow, I don't know my approach in code is right either. And what do I do about the device authorization is pending?.
Any help is appreciated.
Thanks,
Brian
3 replies
Featured Discussions:
New to the community? Say hello and introduce your business.