wordpress rest api Authorization - php

hi i use this code for upload image in wordpress with api
my code :
<?php
$file = $_FILES["RESULT_FileUpload-6"]["tmp_name"];
$url = 'http://tst.com/wp-json/wp/v2/media/';
$ch = curl_init();
$username = 'username';
$password = '123456';
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Disposition: form-data; filename="'.$_FILES["RESULT_FileUpload-6"]["name"].'"',
'Authorization: Basic ' . base64_encode( $username . ':' . $password ),
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );
?>
but when i use this code show error 401 "rest_cannot_create"
i use username and password correct (username and password for wordpress admin panel)
Is there another way for Authorization rest api wordpress??

try to add this in the htaccess file:
RewriteRule ^index\.php$ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

I have to upload pdf file. This will help you in any of you file uploading to custom directories
public function uploadFiles(WP_REST_Request $request)
{
if(checkloggedinuser()){
if ( ($request->get_file_params('file'))) {
$upload_dir = wp_upload_dir();
$user_id = checkloggedinuser();
$timestamp = time();
if ( ! empty( $upload_dir['basedir'] ) ) {
$user_dirname = $upload_dir['basedir'].'/customize-files';
if ( ! file_exists( $user_dirname ) ) {
wp_mkdir_p( $user_dirname );
}
$filename_maker = $user_id.'_'.$timestamp.'_'.$_FILES['file']['name'];
$filename = wp_unique_filename( $user_dirname, $filename_maker );
// return $filename_maker;
$check = move_uploaded_file($_FILES['file']['tmp_name'], $user_dirname .'/'. $filename);
// save into database $upload_dir['baseurl'].'/product-images/'.$filename;
if($check){
$path = $upload_dir['baseurl'].'/customize-files/'.$filename_maker;
return array(
'success' => true,
'responsecode' => 200,
"message" => "File Uploaded Successfully",
"data" => [
"path" => $path,
],
);
}
}
}else{
return array(
'success' => false,
'responsecode' => 403,
"message" => "Please Provide File",
"data" => [],
);
}
}else{
return array(
'success' => false,
'responsecode' => 403,
"message" => "Please Logged In to get Data",
"data" => [],
);
}
}

Related

Wordpress api post image raw data without being blank in media library

So, to get to the heart of the matter, I want to post an image on a worpress site with the api (v2).
First part of the problem is that I don't have a url or file path, I just have the raw data of the image in a variable that I get from an export done before.
The second part of the problem is that once posted (well normally), the image appears blank in the media library in the admin.
Here is my code :
if (isset($product['priority_web_image'])) {
$image_name = $product['priority_web_image']['filename'];
$data = $product['priority_web_image']['data'];
$ext = substr($image_name, strpos($image_name, ".") + 1);
if ($ext == 'jpg') {
$ext = 'jpeg';
}
$mime_type = 'image/'.$ext;
$headers = [
'Authorization' => 'Bearer '.$result_auth->access_token,
"cache-control" => "no-cache",
"Content-Type" => $mime_type,
"Content-Disposition" => "attachement;filename=".$image_name,
];
$body = [
"source_url" => $data,
"slug" => "image_test_pimcore",
"status" => "future",
"title" => $image_name,
"media_type" => "image",
"mime_type" => $mime_type
];
$options = [
"headers" => $headers,
"form_params" => $body,
];
$result = $this->WPApi->request("POST", "media", $options);
$bodyAry = json_decode($result->getBody());
//echo print_r($bodyAry);
return $bodyAry;
}
I use Guzzle for make the request.
If anyone knows what I'm missing, I'll take it :-).
I found a solution !
file_put_contents($filepath, base64_decode($data));
// Make sure the image exist
if (!file_exists($filepath)){return;}
// Load the image
$file = file_get_contents($filepath);
// Get the filename
$filename = $image_name? $image_name : basename($filepath);
// Initiate curl.
$ch = curl_init();
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_URL, $url .'/wp-json/wp/v2/media/' );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
"Content-Disposition: form-data; filename=\"$filename\"",
'Authorization: Bearer ' .$result_auth->access_token,
] );
$result = curl_exec( $ch );
curl_close( $ch );
// Decode the response
$api_response = json_decode($result);
return $api_response;

How to get wiki titles from php?

How to get titles from wikipedia using api.php? Trying:
$opts = array('https' =>
array(
'user_agent' => 'MyBot/1.0 (https://example.com/)'
)
);
$context = stream_context_create($opts);
$url = 'https://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0';
dump(file_get_contents($url));
But it always returns false.
As per documentation you just need to pass format=json when you call API so you will get the response in JSON and based on JSON object you can access any value from a response.
<?php
$url = 'https://en.wikipedia.org/w/api.php?action=query&titles=Your_Highness&prop=revisions&rvprop=content&rvsection=0&format=json';
$context = stream_context_create(['http' => [
'ignore_errors' => true,
]]);
$body = file_get_contents($url, false, $context);
?>
Also, you can use curl for the same like this.
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $ch );
if ( $response === false) {
$curl_result = curl_error( $ch );
print_r( $curl_result );
} else {
print_r( json_decode($response) );
}
curl_close($ch);

Issues sending larger files via curl

Afternoon all,
Having some issues sending large files via curl, we can send the first one which is 5mb but the second test file is 34mb and is not sending. We have increased the post and max upload sizes on both the sending and receiving servers and still no joy.
This is the sending script:
function send_files($directory, $file, $dir_parts) {
$url = 'https://test.com/App_processing/transfer_videos';
$handle = fopen($directory."video.mp4", "r");
$stats = fstat($handle);
$data = stream_get_contents($handle);
$payload = array(
'file' => base64_encode($data),
'parts' => $dir_parts
);
$postfields = array( serialize( $payload ) );
$ssl = strstr($url, '://', true);
$port = ($ssl == 'https') ? 443 : 80;
$verify_ssl = false;
$ch = curl_init();
$curlConfig = array(
CURLOPT_PORT => $port,
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => $verify_ssl,
CURLOPT_FORBID_REUSE => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_FAILONERROR => false,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_POSTFIELDS => $postfields,
);
$headers = null;
$apikey = 'testAPIkey';
$headers = array(
"apikey: ".$apikey
);
$curlConfig[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array( $ch, $curlConfig );
$response = curl_exec( $ch );
}
Receiving script:
public function transfer_videos() {
$return_arr = array();
ini_set('max_execution_time', '999');
ini_set('memory_limit', '512M');
ini_set('post_max_size', '512M');
if(count($this->post_data) > 0) {
$image = $this->post_data['file'];
$file = base64_decode($image);
$filename = $this->post_data['parts'][2];
$return_arr = array();
$office_path = $this->config->item('_path') . '_videos/';
$path = $o_path.$this->post_data['parts'][0]."/".$this->post_data['parts'][1]."/";
$name = $filename;
if( !is_dir( $path ) ) {
mkdir( $path, 0750, true );
}
try {
$return_arr = file_put_contents($path.$name, $file);
} catch (Exception $e) {
$this->curl_helper->error($path.$name, "failed to upload file");
}
}
echo serialize($return_arr);
}
The current error we are getting is:
Recv failure: Connection reset by peer
What the hell are we doing wrong?

Create folder in root directiry of and upload file to that folder google drive api

I want to create folder in googledrive root directory using CURL. File is uploaded to drive but I need to create a folder and upload file to that folder.
As per #hanshenrik Code Create Folder is working Move file is not work
My Updated code :
$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,$folderId)
{
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('name' =>'veridoc', 'parents' => array('17dVe2GYpaHYFdFn1by5-TYKU1LXSAwkp'));
$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 RenameUploadedFile($id,$credentials,$filename)
{
$ch = curl_init();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode ( array (
'name' => $filename
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
curl_exec($ch);
curl_close($ch);
return true;
}
function CreateGDFolder($credentials,$foldername)
{
$curl = curl_init();
curl_setopt_array ( $curl, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files',
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode ( array (
// Earlier it was title changed to name
"name" => $foldername,
"mimeType" => "application/vnd.google-apps.folder"
) ),
// Earlier it was PATCH changed to post
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
$response = curl_exec($curl);
return json_decode($response, 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();
$folderresponse=CreateGDFolder($credentials,"veridoc");
$folderID= $folderresponse['id'];
$folder_id=$folderID;
$filename="veridoc".date('_Y_m_d_H_i_s').".pdf";
$result = uploadFile($credentials, 'veridoc.pdf', '',$folderID);
// File rename to original
$id=$result['id'];
$file_id=$id;
if(isset($folderID)){
//Upload a file
if(RenameUploadedFile($id,$credentials,$filename))
{
echo "We have uploaded ".$filename." to drive";
}
else{
echo "can't rename file";
}
}
try {
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files/' . urlencode ( $file_id ),
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode (array(
'addParents' => $folder_id,
'removeParents' => 'root',
'fields' => 'id, parents') ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/pdf',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
$resp = curl_exec ( $ch );
$parsed = json_decode ( $resp, true );
} finally{
curl_close ( $ch );
}
This is my working example:
To connect Google Driver:
public function connect(Request $request)
{
$user = Auth::user();
$client = new \Google_Client();
$client->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
$client->setClientId('xxxx');
$client->setClientSecret('xxxxxx');
$client->setRedirectUri(url('copywriter/connect'));
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setScopes(array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appfolder'));
if (isset($request->code)) {
$authCode = trim($request->code);
$accessToken = $client->authenticate($authCode);
$copywriter->gd_access_token=json_encode($accessToken, JSON_PRETTY_PRINT);
$copywriter->save();
} else {
$authUrl = $client->createAuthUrl();
return redirect($authUrl);
}
$found=$this->search_gd("files");
if (!isset($found['file_id'])) {
$found=$this->create_folder_gd("copify_files");
$copywriter->gd_folder_id=$found["file_id"];
$copywriter->save();
}
return redirect(route("copywriter.index"));
}
Send to Google Drive
public function send_to_gd($name)
{
$user = Auth::user();
$copywriter=Copywriter::where('user_id', $user->id)->first();
$folderId = $copywriter->gd_folder_id;
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => $name,'mimeType' => 'application/vnd.google-apps.document','parents' => array($folderId)));
$file = $service->files->create($fileMetadata, array(
'mimeType' => 'application/vnd.google-apps.document',
'uploadType' => 'multipart',
'fields' => 'id'));
return $file->id;
}
Client of Request:
public function getClient($user=null)
{
if ($user==null) {
$user = Auth::user();
}
$copywriter=Copywriter::where('user_id', $user->id)->first();
$client = new \Google_Client();
$client->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
$client->setClientId('xxxx');
$client->setClientSecret('xxxxx');
$client->setRedirectUri(url('copywriter/connect'));
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setScopes(array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appfolder'));
$data=json_decode($copywriter->gd_access_token, true);
$client->setAccessToken($data);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$oldAccessToken=$client->getAccessToken();
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$accessToken=$client->getAccessToken();
$accessToken['refresh_token']=$oldAccessToken['refresh_token'];
$copywriter->gd_access_token=json_encode($accessToken, JSON_PRETTY_PRINT);
$copywriter->save();
}
return $client;
}
Search in Google Drive
public function search_gd($name)
{
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$pageToken = null;
do {
$response = $service->files->listFiles(array(
'q' => "mimeType='application/vnd.google-apps.folder' and name='".$name."'",
'spaces' => 'drive',
'pageToken' => $pageToken,
'fields' => 'nextPageToken, files(id, name)',
));
foreach ($response->files as $file) {
return ['file_name'=>$file->name,'file_id'=>$file->id];
printf("Found file: %s (%s)\n", $file->name, $file->id);
}
if (isset($repsonse)) {
$pageToken = $repsonse->pageToken;
}
} while ($pageToken != null);
}
Create a folder on Google Drive
public function create_folder_gd($name)
{
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => $name,
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
return ['file_name'=>$name,'file_id'=>$file->id];
}
Create a document on Google Drive:
public function create_document($name, $content_id=null)
{
$user = Auth::user();
$copywriter=Copywriter::where('user_id', $user->id)->first();
$folderId = $copywriter->gd_folder_id;
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => $name,'mimeType' => 'application/vnd.google-apps.document','parents' => array($folderId)));
$file = $service->files->create($fileMetadata, array(
'mimeType' => 'application/vnd.google-apps.document',
'uploadType' => 'multipart',
'fields' => 'id'));
if ($content_id!=null) {
$content=Content::findOrFail($content_id);
$content->file_id=$file->id;
$content->save();
}
return ['file_name'=>$name,'file_id'=>$file->id];
}
My Models is Copywriter and Content replace it with your's.
going by the documentation on folders here https://developers.google.com/drive/api/v2/folder , seems like you create folders by uploading an empty "file" with the content-type set to application/vnd.google-apps.folder.
here is documentation on how to upload files, in a simple way: https://developers.google.com/drive/api/v2/simple-upload
problem with that upload method is the the created file (or folder, in this case) won't have a name, it will just be called untitled<whatever>, so finally, here's documentation on how to rename files: https://developers.google.com/drive/api/v3/reference/files/update (or in this case, a folder)
putting it all together, you'll probably end up with something like:
<?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/vnd.google-apps.folder',
'Authorization: Bearer '.getAccessToken ( $credentials )
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => '', // "empty file"
CURLOPT_RETURNTRANSFER => 1
) );
try {
// this will create the folder, with no name
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 );
}
$id = $parsed ['id'];
// now to give the folder a name:
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' => 'the_folders_name'
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
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 );
and finally, to move files inside this folder, send a PATCH request to https://www.googleapis.com/upload/drive/v3/files/<file_you_want_to_move_id> with the folder's id as the addParents parameter of the request body, eg something like:
<?php
try {
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files/' . urlencode ( $file_id ),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
'addParents' => $folder_id,
'removeParents'=> 'root',
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
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 );
}
This will help You:
https://developers.google.com/drive/api/v3/folder
Creating a folder:
In the Drive API, a folder is essentially a file — one identified by the special folder MIME type application/vnd.google-apps.folder. You can create a new folder by inserting a file with this MIME type and a folder title. Do not include an extension when setting a folder title.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Invoices',
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $driveService->files->create($fileMetadata, array(
'fields' => 'id'));
printf("Folder ID: %s\n", $file->id);
Inserting a file in a folder:
To insert a file in a particular folder, specify the correct ID in the parents property of the file, as shown:
$folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E';
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'photo.jpg',
'parents' => array($folderId)
));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
The parents property can be used when creating a folder as well to create a subfolder.
Moving files between folders:
To add or remove parents for an exiting file, use the addParents and removeParents query parameters on the files.update method.
Both parameters may be used to move a file from one folder to another, as shown:
$fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
$folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E';
$emptyFileMetadata = new Google_Service_Drive_DriveFile();
// Retrieve the existing parents to remove
$file = $driveService->files->get($fileId, array('fields' => 'parents'));
$previousParents = join(',', $file->parents);
// Move the file to the new folder
$file = $driveService->files->update($fileId, $emptyFileMetadata, array(
'addParents' => $folderId,
'removeParents' => $previousParents,
'fields' => 'id, parents'));
See this if it is working. I have made changes like "name" => "", CURLOPT_CUSTOMREQUEST => 'POST',
function CreateGDFolder($credentials)
{
$ch = curl_init();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
// Earlier it was title changed to name
"name" => "pets",
"mimeType" => "application/vnd.google-apps.folder"
) ),
// Earlier it was PATCH changed to post
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
$response=curl_exec($ch);
$response = json_decode($response, true);
print_r($response);
curl_close($ch);
}

How do I call CITRIX (LogMeIn) API via PHP to register new GotoWebinar attendee?

I am using the below code to register user to the webinar:
$headers = array(
'HTTP/1.1',
'Accept: application/json',
'Accept: application/vnd.citrix.g2wapi-v1.1+json',
'Content-Type: application/json',
'Authorization: OAuth oauth_token='.$access_token,
'Name_First:test',
'Name_Last:ank',
'Email:ankinfo#yahoo.com',
);
$gtw_url = "https://api.citrixonline.com/G2W/rest/organizers/{organizerkey}/webinars/{webinarkey}/registrants";
$curl = #curl_init();
#curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
#curl_setopt($curl, CURLOPT_URL, $gtw_url);
#curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#curl_exec($curl);
#curl_close($curl);
I have passed webinar key and organizer key. I am supposed to get the output like:
HTTP/1.1 201 OK Content-Type: application/json
{
"registrantKey":5678,
"joinUrl":"https://www1.gotomeeting.com/join/123456789/5678"
}
The problem is that when i run the file i got output
[
{
"registrantKey":106660361,
"firstName":"test",
"lastName":"1",
"email":"rohankapoor99#yahoo.com",
"status":"WAITING",
"registrationDate":"2012-06-29T21:07:10Z",
"joinUrl":"https://www1.gotomeeting.com/join/141654337/106660361",
"timeZone":"America/Denver"
}
]
I am using the create webinar URL, so why am I getting the info of the user that is already registered?
The question is 3 years old, but considering the present dismal state of the CITRIX (now LogMeIn) API documentation, I'm offering the following snippet as a possible solution:
Obviously, we'll need the Organizer Key and Access Token data for our account...
$organizer_key= '10000000000XXXXXXX';
$access_token = 'GwsiiPWaJbHIiaIiocxxxxxxxxxx';
Get the minimum required fields for a webinar (for example from an HTML form) and JSON encode the data...
$newRegFields = (object) array(
'firstName' => $_POST[ 'FirstName' ],
'lastName' => $_POST[ 'LastName' ],
'email' => $_POST[ 'Email' ],
);
$newRegistrantFields = json_encode( $newRegFields );
//echo '<br><br>' . $newRegistrantFields;
Get the Webinar...
$webinarID = preg_replace( "/[^0-9]/", "", $_POST[ "WebinarKey" ] );
Set the URL to the LogMeIn API (the resendConfirmation option is not required)...
$gtw_url = "https://api.citrixonline.com/G2W/rest/organizers/" . $organizer_key . "/webinars/" . $webinarID . "/registrants?resendConfirmation=false";
Format our POST headers...
$headers = array(
"HTTP/1.1",
"Accept: application/json",
"Content-Type: application/json",
"Authorization: OAuth oauth_token=$access_token",
"Content-Length: " . strlen( $newRegistrantFields )
);
Set our cURL options, ensuring we specify a POST with CURLOPT_POST, 1 ...
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $gtw_url );
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_POST, 1 );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $newRegistrantFields );
$newRegistrants = curl_exec( $curl );
curl_close( $curl );
Our cURL call has returned with JSON encoded data, whether it's a server error message or a confirmation of registration. Now let's turn the reply into a handy associative array...
$newRegistrantsArray = json_decode( $newRegistrants, true );
//echo '<br><br>' . $newRegistrants . '<br><br>';
//echo '<pre>'; print_r( $newRegistrantsArray ); echo '</pre>';
If the errorCode key was returned, then the registration bombed out. All I'm doing here is grabbing the actual error description from the server and loading it up to return to my calling HTML page, but this is totally optional...
if( array_key_exists( 'errorCode', $newRegistrantsArray )) {
$form_data[ 'status' ] = false;
$form_data[ 'code' ] = $newRegistrantsArray[ 'description' ];
$form_data[ 'error' ] = 'E200';
//echo json_encode( $form_data );
//exit;
}
Now, if a registration was successful, the server will return something like...
(
[registrantKey] => 2.5022062212198E+18
[joinUrl] => https://global.gotowebinar.com/join/6552167171182613761/103193261
)
...and so I'm just checking to see if those keys were returned, and if so, I know the registration was good.
if( array_key_exists( 'registrantKey', $newRegistrantsArray ) && array_key_exists( 'joinUrl', $newRegistrantsArray ) ) {
$form_data[ 'status' ] = true;
$form_data[ 'code' ] = $_POST[ 'Email' ] . ' successfully registered with webinar';
$form_data[ 'error' ] = 'E300';
//echo json_encode( $form_data );
//exit;
}

Categories