¿How can i consume a SOAP webservice with PHP? - php

I think there are some methods:
Screenshot of Wizdler
Well i try to login using nusoap, curl and SoapClient but no luck.
My WSDL knowledge is as poor as my english so please i need some help to deal with this.
$baseurl='https://dcs.honda.com.ar/WCF/Service.svc?wsdl';
My best try with cURL:
$curl = curl_init();
$url = $this->baseurl;
$payload = '<Envelope xmlns="http://www.w3.org/2003/05/soap-envelope">
<Header>
<client_id xmlns="http://tempuri.org/">' . $clientId . '</client_id>
<cliente_secret xmlns="http://tempuri.org/">' . $clientSecret . ']</cliente_secret>
</Header>
<Body>
<AuthRequest xmlns="http://tempuri.org/"/>
</Body>
</Envelope>';
$headers = [
"Content-type: application/soap+xml;charset=\"utf-8\"",
'Accept: application/soap+xml',
'Cache-Control: no-cache',
'Pragma: no-cache',
'Content-length: ' . strlen($payload),
];
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$response = curl_exec($curl);
var_dump($response);
die();
Response =>
string(576) "http://www.w3.org/2005/08/addressing/soap/faults:Sendera:InvalidSecurityAn error occurred when verifying security for the message."
SoapClient try:
<?php
ini_set('default_socket_timeout', 600);
function WebServices($function, $parameters)
{
$username = 'ausername';
$password = 'apassword';
$url = 'https://dcs.honda.com.ar/WCF_Test/Service.svc?wsdl';
$service_url = 'https://dcs.honda.com.ar/WCF_Test/Service.svc';
$client = new SoapClient($url, [
'soap_version' => SOAP_1_2,
'Username' => $username,
'Password' => $password,
'SOAPAction' => "http://tempuri.org/IService/$function",
'cache_wsdl' => WSDL_CACHE_NONE, // WSDL_CACHE_MEMORY
'trace' => 1,
'exception' => 1,
'keep_alive' => false,
'connection_timeout' => 500000,
]);
$action = new \SoapHeader(
'http://www.w3.org/2005/08/addressing',
'Action',
"http://tempuri.org/IService/$function"
);
$to = new \SoapHeader(
'http://www.w3.org/2005/08/addressing',
'To',
$service_url
);
$security = generateWSSecurityHeader('PasswordText', $password);
//var_dump($security);
//die();
$client->__setSoapHeaders([$action, $to, $security]);
try {
return $client->__soapCall($function, $parameters);
} catch (SoapFault $e) {
return $e->getMessage();
}
}
function generateWSSecurityHeader($passwordType = 'PasswordText', $password)
{
$username = 'ausername';
$password = 'apassword';
$nonce = mt_rand();
$OASIS = 'http://docs.oasis-open.org/wss/2004/01';
$timestamp = gmdate('Y-m-d\TH:i:s\Z');
if ($passwordType === 'PasswordText') {
$password = $password;
$nonce = sha1(mt_rand());
} else {
return '';
}
$xml =
'
<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="' .
$OASIS .
'/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>' .
$username .
'</wsse:Username>
<wsse:Password Type="' .
$OASIS .
'/oasis-200401-wss-username-token-profile-1.0#' .
$passwordType .
'">' .
$password .
'</wsse:Password>
<wsse:Nonce EncodingType="' .
$OASIS .
'/oasis-200401-wss-soap-message-security-1.0#Base64Binary">' .
$nonce .
'</wsse:Nonce>';
if ($passwordType === 'PasswordDigest') {
$xml .=
"\n\t" .
'<wsu:Created xmlns:wsu="' .
$OASIS .
'/oasis-200401-wss-wssecurity-utility-1.0.xsd">' .
$timestamp .
'</wsu:Created>';
}
$xml .= '
</wsse:UsernameToken>
</wsse:Security>';
return new SoapHeader(
$OASIS . '/oasis-200401-wss-wssecurity-secext-1.0.xsd',
'Security',
new SoapVar($xml, XSD_ANYXML),
true
);
}
$params = [
'client_id' => 'ausername',
'cliente_secret' => 'apassword',
];
var_dump(WebServices('getAccess', $params));
Response => object(SoapHeader)#4 (4) { ["namespace"]=> string(81) "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" ["name"]=> string(8) "Security" ["data"]=> object(SoapVar)#5 (2) { ["enc_type"]=> int(147) ["enc_value"]=> string(619) " alongrandomalphanumericcharactersstring... " } ["mustUnderstand"]=> bool(true) }
Im lost and don't know how to proceed. Apreciate so much any kind of help.
Thanks in advance!

Related

Signature doesn't work when using spaces in url parameter

I want to use an endpoint that uses an url parameter with spaces in it.
I have a function that generates an signature.
function generateSignature($request, $timestamp, $nonce)
{
Global $consumerKey, $accessToken, $consumerSecret, $tokenSecret, $realm, $signatureMethod, $version, $limit;
$baseparams = "";
$baseurl = strtok($request['url'], "?");
$base = strtoupper($request['method']) . "&" . urlencode($baseurl) . "&";
if(strpos($request['url'], '?') !== false){
$url_components = parse_url($request['url']);
parse_str($url_components['query'], $params);
$paramnr = 0;
foreach($params as $param => $value){
$paramnr++;
if($paramnr > 1){
$baseparams .= "&".$param."=" . urlencode($value);
}
else{
$baseparams .= $param."=" . urlencode($value);
}
}
$trailingand = "&";
}
else{
$trailingand = "";
}
echo $baseparams .= $trailingand
. "oauth_consumer_key=" . urlencode($consumerKey)
. "&oauth_nonce=" . urlencode($nonce)
. "&oauth_signature_method=" . urlencode($signatureMethod)
. "&oauth_timestamp=" . urlencode($timestamp)
. "&oauth_token=" . urlencode($accessToken)
. "&oauth_version=" . urlencode($version);
$base = $base.urlencode($baseparams);
$key = urlencode($consumerSecret) . '&' . urlencode($tokenSecret);
$signature = hash_hmac('sha256', $base, $key, true);
$signature = urlencode(base64_encode($signature));
return $signature;
}
My execute function:
function execute($options = array()){
Global $consumerKey, $accessToken, $consumerSecret, $tokenSecret, $realm, $signatureMethod, $version;
$curl = curl_init();
echo $options['url'];
curl_setopt_array($curl, array(
CURLOPT_URL => $options['url'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
));
$timestamp = round(microtime(true));
$nonce = getNonce(11);
$signature = generateSignature($options, $timestamp, $nonce);
$authHeader = 'Authorization: OAuth realm="'.$realm.'",oauth_consumer_key="'.$consumerKey.'",oauth_token="'.$accessToken.'",oauth_signature_method="'.$signatureMethod.'",oauth_timestamp="'.$timestamp.'",oauth_nonce="'.$nonce.'",oauth_version="'.$version.'",oauth_signature="'.$signature.'"';
curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, strtoupper($options['method']) );
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
$authHeader
));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$response = curl_exec($curl);
$array = json_decode($response, true);
echo "<br/>".$responsecode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if(curl_errno($curl)){
return 'Curl error: ' . curl_error($curl);
}
else{
return $array;
}
curl_close($curl);
}
This works fine when I have an url like this:
https://website.com/api/customer?limit=10 - WORKS
But the API also supports this:
https://website.com/api/customer?q=partner+EQUALS+10 - DOESNT WORK
When I put this URL into my function, it doesn't work and I get an 400 error instead.
My guess is that the signature is incorrect due to the spaces inside the url parameter.
How can I make this work with an url parameter that has spaces in it?
I already tried to use urlencode but that didnt work as well.
If it helps you out: I'm using the NETSUITE REST API for this.
Can someone help me plz...
When you make a req use encoded url insted of spaces.
https://website.com/api/customer?q=partner+EQUALS+10
this type will works for you

Google Drive integration error php

I have to add file in Drive. I have tried following code but give an error.
Purpose :
I have to use an api to add file to google drive.
Code
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array (
'Content-Type: application/pdf', // todo: runtime detection?
'Authorization: Bearer [YOUR_AUTH_TOKEN]'
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ( '/path/to/file.pdf' ),
CURLOPT_RETURNTRANSFER => 1
) );
try {
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump($resp);
Error :
Notice: Undefined index: code in
/opt/lampp/htdocs/uploadtodrive/index.php on line 18
Fatal error: Uncaught RuntimeException: google api error: { "error": {
"errors": [ { "domain": "global", "reason": "authError", "message":
"Invalid Credentials", "locationType": "header", "location":
"Authorization" } ], "code": 401, "message": "Invalid Credentials" } }
in /opt/lampp/htdocs/uploadtodrive/index.php:19 Stack trace: #0 {main}
thrown in /opt/lampp/htdocs/uploadtodrive/index.php on line 19
You have create a webapplication and client ID ,Secrete as well as redirect URL. redirect URL is missing.
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-t19mhuuvq0nqtxxxxim8.apps.googleusercontent.com';
$CLIENT_SECRET = 'K8YxRshxxxx-5Sh3jKa';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'my_file.txt', 'vasim.txt');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';

Uploaded file rename to untitled Google drive

I have done google api integration code as well as file is upload to a drive. I have issue regarding a uploaded file name is "Untitled". Please review code and guide me what is missing.
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-t19mhuuvq0nqtng5ogg8XXXXXX0im8.apps.googleusercontent.com';
$CLIENT_SECRET = 'XXXXXXXXKa';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
//$content = { title "mypdf.pdf", description = "mypdf.pdf", mimeType = "application/pdf" };
$contentArry = array('title' =>'veridoc' );
$contentArry = json_encode($contentArry);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$contentArry);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf','Content-Length:' . filesize($filename),'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'veridoc.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
`
going by the documentation at https://developers.google.com/drive/api/v3/reference/files/update , to rename a file, do a PATCH request to https://www.googleapis.com/drive/v3/files/<fileId> with the new name, in your case, i guess that would be
$postResult = curl_exec ( $ch );
$parsed = json_decode ( $postResult, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $postResult );
}
$id = $parsed ['id']; // ?? wait, is it id or fileId?
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
'name' => basename ( $filename )
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
curl_exec($ch);
ps, don't set the Content-Length header manually when using CURLOPT_POSTFIELDS, because curl will do it for you, and if you're using multipart/form-data, the length you set yourself is very likely to be wrong even (doesn't concern your code as you're not using multipart/form-data, but it's a good habit to learn nonetheless, get rid of it.)

Google Calendar API (v3) - PHP can write but not read?

I spent all day figuring out the Google Calendar API. I finally managed to insert an event in my Google Calendar but now I cannot seem to get the "list" command working.
The following code works:
<?php
$start = array(
"dateTime" => $date . "T" . $start_time . ":00",
"timeZone" => "Europe/Berlin"
);
$end = array(
"dateTime" => $date . "T" . $end_time . ":00",
"timeZone" => "Europe/Berlin"
);
$headerarray = array(
'Content-type: application/json',
'Authorization: Bearer ' . $access_token,
'X-JavaScript-User-Agent: Google APIs Explorer'
);
$post_data = array(
"start" => $start,
"end" => $end,
"summary" => $title,
"description" => $description,
"key" => $api_key
);
$post_data = json_encode($post_data);
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
?>
This piece of code creates a new event in my calendar, so I should have everything set up correctly, right?
However this code does not work:
<?php
$headerarray = array(
"Authorization: Bearer " . $access_token,
"X-JavaScript-User-Agent: Google APIs Explorer"
);
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events?key=' . $api_key;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
?>
In this case I get the following response: Access Not Configured. Please use Google Developers Console to activate the API for your project.
But that is not the case. I configured the access correctly, or else I would not be able to insert events into the calendar, right? Maybe I am not using cURL right?
This is the reference for the list function: https://developers.google.com/google-apps/calendar/v3/reference/events/list
What am I not seeing here? Any help is highly appreciated.
Try this one :
Go to : https://console.developers.google.com
select project
go to: APIs and auth
Activate calendar api
I spent my whole day to create the event , I'm able to fetch the event
here is my code to fetch data from google oauth and I am using the codeigniter framework.
<?php
// product_config
$config['google_id'] = '';
$config['google_secret'] = '';
// oauth file
function get_calendar_events(OAuth2_Token_Access $token){
try{
$max_results = 250;
$url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events?showDeleted=false&$orderBy=email&maxResults='.$max_results.'&alt=json&v=3.0&oauth_token='.$token->access_token;
$google_events = json_decode(file_get_contents($url), true);
return $google_events;
}catch (Exception $e) {
// Exception
}
}
/*** Controller ***/
function myCalendar() {
try {
$events = array();
$provider_name = 'google';
$provider = $this->oauth2->provider($provider_name, array(
'id' => $this->config->item($provider_name.'_id', 'product_config'),
'secret' => $this->config->item($provider_name.'_secret', 'product_config'),
'scopes' => array('https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly')
));
if (!$this->input->get('code')){ // access authorizing
// By sending no options it'll come back here
$provider->authorize();
}else{
// Get the Token
$token = $provider->access($this->input->get('code'));
$events = $provider->get_calendar_events($token);
}catch (Exception $e) {
// Exception
}
}
?>
public function create_calendar_event(OAuth2_Token_Access $token,$description, $leaveDate , $toLeaveDate,$title, $stime, $etime ){
try {
$title = $title;
//$start_time = '00:00'; $end_time = '23:59';
$start_time = $stime;
$end_time = $etime;
$timezone = 'Asia/Kolkata';
$start = array(
"dateTime" => $leaveDate . "T" . $start_time . ":00",
"timeZone" => $timezone
);
$end = array(
"dateTime" => $toLeaveDate . "T" . $end_time . ":00",
"timeZone" => $timezone
);
$headerarray = array(
'Content-type: application/json',
'Authorization: Bearer ' . $token->access_token,
'X-JavaScript-User-Agent: Google APIs Explorer'
);
$post_data = array(
"start" => $start,
"end" => $end,
"summary" => $title,
"description" => $description,
"key" => $this->api_key
);
$post_data = json_encode($post_data);
$calendar_id = 'primary';
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$result = $this->NewcurlRequest($url, $headerarray, $post_data);
}catch(Exception $e){
// Exception
}
}
public function NewcurlRequest($url,$headerarray,$post_data, $curl_call = true){
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, curlopt_post, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
} catch (Exception $e) {
return $e;
}
}

Webservice error 400 while using Docusign API in php

Hello friends I am using an HTTP server to access Doucsign. And I am getting server problem
That is server error 400 and errorCode.
INVALID_EMAIL_ADDRESS_FOR_RECIPIENT", "message": "The email address
for the recipient is invalid. The recipient Id follows.
My code is
<?php
// Input your info here:
$email = "****"; // your account email
$password = "*******"; // your account password
$integratorKey = "*********"; // your account integrator key, found on (Preferences -> API page)
$recipientName = "usa usa"; // provide a recipient (signer) name
$documentName = "proposal.pdf"; // copy document with same name into this directory!
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (to retrieve baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
$accountId = $response["loginAccounts"][0]["accountId"];
$baseUrl = $response["loginAccounts"][0]["baseUrl"];
curl_close($curl);
//--- display results
echo "\naccountId = " . $accountId . "\nbaseUrl = " . $baseUrl . "\n";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Create an envelope with one recipient, one tab, and one document and send
/////////////////////////////////////////////////////////////////////////////////////////////////
// the following request body will place 1 signature tab on the document you supply, located
// 100 pixels to the right and 100 pixels down from the top left of the document
$data = array (
"emailSubject" => "DocuSign API - Signature Request on Document",
"documents" => array( array( "documentId" => "1", "name" => $documentName)),
"recipients" => array( "signers" => array(
array( "email" => $email,
"name" => $recipientName,
"recipientId" => "1",
"tabs" => array(
"signHereTabs" => array(
array( "xPosition" => "100",
"yPosition" => "100",
"documentId" => "1",
"pageNumber" => "1" )
))
))
),
"status" => "sent"
);
$data_string = json_encode($data);
$file_contents = file_get_contents($documentName);
$requestBody = "\r\n"
."\r\n"
."--myboundary\r\n"
."Content-Type: application/json\r\n"
."Content-Disposition: form-data\r\n"
."\r\n"
."$data_string\r\n"
."--myboundary\r\n"
."Content-Type:application/pdf\r\n"
."Content-Disposition: file; filename=\"$documentName\"; documentid=1 \r\n"
."\r\n"
."$file_contents\r\n"
."--myboundary--\r\n"
."\r\n";
// *** append "/envelopes" to baseUrl and as signature request endpoint
$curl = curl_init($baseUrl . "/envelopes" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data;boundary=myboundary',
'Content-Length: ' . strlen($requestBody),
"X-DocuSign-Authentication: $header" )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
echo $status;
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status . "\nerror text is --> ";
print_r($json_response); echo "\n";
exit(-1);
}
$response = json_decode($json_response, true);
$envelopeId = $response["envelopeId"];
//--- display results
echo "Document is sent! Envelope ID = " . $envelopeId . "\n\n";
Can anyone help me? Thanks in advance.

Categories