I am using php to upload files automatically to Google drive using API/Token, but I discovered that the Token expired after certain of time.
I always get new token from Oauth play ground Page
https://developers.google.com/oauthplayground/
So, how to refresh it automatically using Refresh Code Token
Here is the full code:-
global $GAPIS;
$GAPIS = 'https://www.googleapis.com/';
$name = $name;
$file = $zip_file_name;
$mime_type = 'application/zip';
$access_token = 'token';
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch1, CURLOPT_URL, $GAPIS . 'upload/drive/v3/files?uploadType=media');
curl_setopt($ch1, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, file_get_contents($file));
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: '.$mime_type, 'Content-Length: ' . filesize($file), 'Authorization: Bearer ' . $access_token) );
$response=curl_exec($ch1);
if($response === false){
$output = 'ERROR: '.curl_error($ch1);
} else{
$output = $response;
}
curl_close($ch1);
$this_response_arr = json_decode($response, true);
if(isset($this_response_arr['id'])){
$this_file_id = $this_response_arr['id'];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch2, CURLOPT_URL, $GAPIS . 'drive/v3/files/'.$this_file_id);
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PATCH');
$post_fields = array();
$this_file_name = explode('.', $name);
$post_fields['name']=$this_file_name[0];
curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response=curl_exec($ch2);
if($response === false){
$output = 'ERROR: '.curl_error($ch2);
} else{
$output = $response;
}
curl_close($ch2);
$print = json_decode($output, true);
if ($this_file_name[0] = $print['name']) {
echo "file uploaded successfully and ";
}
}
unlink ($file);die("Zip file removed");
return $output;
EDIT: Solution:-
Thanks a lot for Ronak Dhoot about his solution and here is the CURL code to get the refresh token automatically
$client_id = 'client_id';
$client_secret = 'client_secret';
$refresh_token = 'refresh_token';
$url = 'https://www.googleapis.com/oauth2/v4/token';
$fields = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'refresh_token' => $refresh_token,
'grant_type' => 'refresh_token'
];
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$access_result = json_decode($result, true);
$access_token = $access_result['access_token'];
echo $access_token;
in Step 1 when Click “Authorize APIs” and allow access to your account when prompted. There will be a few warning prompts, just proceed.
When you get to step 2, check “Auto-refresh the token before it expires” and click “Exchange authorization code for tokens”.
When you get to step 3, click on step 2 again and you should see your refresh token.
Now, All you need to do is a post request like below :-
POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json
{
"client_id": <client_id>,
"client_secret": <client_secret>,
"refresh_token": <refresh_token>,
"grant_type": "refresh_token"
}
Related
My requirement is to upload a file to my google drive using Php cURL and then rename the upload file and move the file to a specific folder.
For this, I have done oAuth and successfully uploaded a file from my website to google drive using the below code.
$image = "../../../".$name;
$apiURL = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
$mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
$folder_id = "1WBkQQ6y0TPt2gmFR3PKCzSip_aAuuNEa";
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $apiURL);
curl_setopt($ch1, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, file_get_contents($image));
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: '.$mime_type, 'Authorization: Bearer ' . $access_token) );
// execute cURL request
$response=curl_exec($ch1);
if($response === false){
$output = 'ERROR: '.curl_error($ch1);
} else{
$output = $response;
}
// close first request handler
curl_close($ch1);
$this_response_arr = json_decode($response, true);
The file is uploaded as Untitled and I used the below code to rename it to a proper filename as per my requirement.
if(isset($this_response_arr['id'])){
$this_file_id = $this_response_arr['id'];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_file_id);
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PATCH');
$post_fields = array();
$this_file_name = explode('.', $name);
$post_fields['name'] = $this_file_name[0];
curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response2 = curl_exec($ch2);
if($response2 === false){
$output2 = 'ERROR: '.curl_error($ch2);
} else{
$output2 = $response2;
}
curl_close($ch2);
$this_response2 = json_decode($response2, true);
}
Now I want to move this uploaded file in the Google drive root folder to a specific folder. I tried adding the “Parents” , “addParents”, “removeParents” parameters in post body along with "Name" parameter and and also as a separate cURL Patch request but none of them is working.
if($this_response2['id']){
$this_f_id = $this_response2['id'];
$ch3 = curl_init();
curl_setopt($ch3, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_f_id);
curl_setopt($ch3, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch3, CURLOPT_POST, 1);
$post_fields1 = array();
$post_fields1['addParents'] = $folder_id;
$post_fields1['removeParents'] = "root";
curl_setopt($ch3, CURLOPT_POSTFIELDS, json_encode($post_fields1));
curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch3, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response3 = curl_exec($ch3);
if($response3 === false){
$output3 = 'ERROR: '.curl_error($ch3);
} else{
$output3 = $response3;
}
curl_close($ch3);
}
Any help would be appreciated.
Documentation for uploading,renaming and moving the file in gdrive is not properly documented for Php cURL and there are not much examples available too.
There is no need to send an additional cURL request for moving the file to a specific folder. This can be done in the second cURL request itself.
The mistake in your code is, you are sending the addParents and removeParents in Request Body instead of sending this as query parameters.
You can modify the second cURL as below to update the name of uploaded file and for moving the file inside a specific folder.
if(isset($this_response_arr['id'])){
$this_file_id = $this_response_arr['id'];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_file_id.'?addParents='.$folder_id.'&removeParents=root');
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PATCH');
$post_fields = array();
$this_file_name = explode('.', $name);
$post_fields['name'] = $this_file_name[0];
curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response2 = curl_exec($ch2);
if($response2 === false){
$output2 = 'ERROR: '.curl_error($ch2);
} else{
$output2 = $response2;
}
curl_close($ch2);
$this_response2 = json_decode($response2, true);
}
Let me know if this works.
I want to change profile image another application curl request i am trying below code can anyone help me please
$viewer = Engine_Api::_()->user()->getViewer();
$apiData = array(
"email" => $viewer->email,
"profile_image_file" => $_FILES['Filedata']['name'],
);
$apiHost = "https://tenant.thetenantsnet.co.uk/api/api/save_profile_image";
$response = $this->callRiseAPI2($apiData,$apiHost);
private function callRiseAPI2($apiData,$apiHost){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, count($apiData));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$jsonData = curl_exec($ch);
if (false === $jsonData) {
throw new \Exception("Error: _makeOAuthCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
//return the API response
return json_decode($jsonData);
}
As Anoxy said, you need to put in the header the Content-Type :
$viewer = Engine_Api::_()->user()->getViewer();
$apiData = array(
"email" => $viewer->email,
"profile_image_file" => $_FILES['Filedata']['name'],
);
$apiHost = "https://tenant.thetenantsnet.co.uk/api/api/save_profile_image";
$response = $this->callRiseAPI2($apiData,$apiHost);
private function callRiseAPI2($apiData,$apiHost){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, count($apiData));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: multipart/form-data');
$jsonData = curl_exec($ch);
if (false === $jsonData) {
throw new \Exception("Error: _makeOAuthCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
//return the API response
return json_decode($jsonData);
}
I am trying to add attachment url in crm. I am flowing this documentation . But i got error !
This is my code :
$zoho_url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$post['attachmentUrl'] = $url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_URL,$zoho_url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
$headers = array();
$headers[] = "Authorization: ".$authtoken;
$headers[] = "Content-Type: multipart/form-data";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$err = curl_errno($ch);
curl_close ($ch);
if ($err) {
$result = $err;
} else {
$result = $response;
}
print_r($result);
This is response :
{"code":"INVALID_REQUEST","details":{},"message":"unable to process your request. please verify whether you have entered proper method name, parameter and parameter values.","status":"error"}
I made this code for attach a file in a zoho record.
//Get the oauth Token
$accessToken=getCurrentAccessToken();
// files to upload
$tmpfile;
$filename;
$type;
foreach($files as $file){
$tmpfile = $file['tmp_name'];
$filename = basename($file['name']);
$type = $file['type'];
}
$cfile = new CURLFile(realpath($tmpfile),$type,$filename);
$post_data = array (
'file' => $cfile
);
$url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$headers = array(
'Content-Type: multipart/form-data',
sprintf('Authorization: Zoho-oauthtoken %s', $accessToken)
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
return $response;
I have been trying to create a lead from SalesForce's REST API for the past several days but I can't for the life of me get it working. I am able to get the access token no problem but from there on as far as creating a lead I am having absolutely no luck at all.
I keep seeing in all of the documentation this:
curl https://na1.salesforce.com/services/data/v20.0/sobjects/Account/ -H "Authorization: Bearer token -H "Content-Type: application/json" -d #newaccount.json"
How would I do this in PHP's curl though? I have tried and tried but had no luck at all.
Here is how I have got the access token:
$ch = curl_init();
// set URL options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=".CONSUMER_KEY."&client_secret=".CONSUMER_SECRET."&username=".USERNAME."&password=".USERPASS.SECURITY_TOKEN);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// grab HTML
$data = curl_exec($ch);
$data = json_decode($data, true);
$code = $data['access_token'];
curl_close($ch);
I have tried doing something like this after this code, however I have had no luck.
$token_url = LOGIN_BASE_URL.'/services/oauth2/token';
$post_fields = array(
'code' => $code,
'grant_type' => 'authorization_code',
'client_id' => CONSUMER_KEY,
'client_secret' => CONSUMER_SECRET,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$token_request_body = curl_exec($ch)
I just need to figure out how to create leads in SalesForce, I have no idea where to go from here. Any help would be greatly appreciated as I cannot find decent documentation anywhere that helps me.
create account demo, should get you started:
function create_account($name, $instance_url, $access_token) {
$url = "$instance_url/services/data/v20.0/sobjects/Account/";
$content = json_encode(array("Name" => $name));
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Authorization: OAuth $access_token",
"Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
echo "HTTP status $status creating account<br/><br/>";
curl_close($curl);
$response = json_decode($json_response, true);
$id = $response["id"];
echo "New record id $id<br/><br/>";
return $id;
}
I'm using Drupal 7 and the services module and I'm trying to update a user profile using PHP & Curl.
Do I always have to login before sending a "PUT/update" ?
This is my code so far :
<?php
// REST Server URL
$request_url = 'http://mywebsite/end/user/login';
// User data
$user_data = array(
'username' => 'user2',
'password' => 'pass1',
);
// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
print $response;
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check if login was successful
if ($http_code == 200) {
// Convert json response as array
$logged_user = json_decode($response);
}
else {
// Get error msg
$http_message = curl_error($curl);
die($http_message);
}
print_r($logged_user);
// REST Server URL
$request_url = 'http://mywebsite.com/end/user/8&XDEBUG_SESSION_START=netbeans-xdebug';
$user_data = array('current_pass' => 'pass1', 'pass' => 'pass2');
// Define cookie session
$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;
// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json',
'Content-type: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_PUT, TRUE);
curl_setopt($curl, CURLOPT_HEADER, TRUE); // FALSE); // Ask to not return Header
curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved session
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
// Emulate file.
$serialize_args = json_encode($user_data);
$putData = fopen('php://temp', 'rw+');
fwrite($putData, $serialize_args);
fseek($putData, 0);
curl_setopt($curl, CURLOPT_INFILE, $putData);
curl_setopt($curl, CURLOPT_INFILESIZE, drupal_strlen($serialize_args));
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check if login was successful
$ret;
if ($http_code == 200) {
// Convert json response as array
$ret = json_decode($response);
}
else {
// Get error msg
$http_message = curl_error($curl);
die($http_message);
}
print_r($ret);
curl_close($curl);
}
?>
What am I missing here?
Nothing happens to my profile.
Any answer is welcomed!
Hope this can help u.
$service_url = 'http://mywebsite/end/user/login'; // .xml asks for xml data in response
$post_data = array(
'username' => 'user2',
'password' => 'pass1',
);
$post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // have curl_exec return a string
curl_setopt($curl, CURLOPT_POST, true); // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
// parse the response
$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name .'='. $xml->sessid;
if(empty($xml->session_name) && empty($xml->sessid)){
echo 'Wrong';exit;
}
$service_url = 'http://mywebsite/end/user/token'; // .xml asks for xml data in response
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_POST, true); // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // have curl_exec return a string
curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$csrf_token = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($csrf_token);
$csrf_token = $xml->token;
$csrf_header = 'X-CSRF-Token: ' . $csrf_token;
// REST Server URL
$request_url = 'http://mywebsite/end/user/8&XDEBUG_SESSION_START=netbeans-xdebug';
$user_data = array('current_pass' => 'pass1', 'pass' => 'testing');
// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json',
'Content-type: application/json',$csrf_header)); // Accept JSON response
curl_setopt($curl, CURLOPT_PUT, TRUE);
//curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, TRUE); // FALSE); // Ask to not return Header
curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
// Emulate file.
$serialize_args = json_encode($user_data);
$putData = fopen('php://temp', 'rw+');
fwrite($putData, $serialize_args);
fseek($putData, 0);
curl_setopt($curl, CURLOPT_INFILE, $putData);
curl_setopt($curl, CURLOPT_INFILESIZE, strlen($serialize_args));
$response = curl_exec($curl);
curl_close($curl);
You can achieve this by using "CURLOPT_COOKIEJAR" for writing and preserving cookies but you also need to set "CURLOPT_COOKIEFILE" for reading. More info can be found at http://php.net/manual/en/function.curl-setopt.php
define('COOKIE_FILE', "/tmp/sess" . time() . $user_data['username']);
curl_setopt ($curl, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($curl, CURLOPT_COOKIEFILE, COOKIE_FILE);