Google spreadsheet, how to protect Cell? - php

I create excel file and proteced some field in this file. In Office excel all fine my some cell locked for edit, begin I upload my excel file in google drive with convert - true (Whether to convert this file to the corresponding Google Docs format. (Default: false)) But in google spread sheet I can edit locked cell, how to locked in google spread sheet some cell ?
create excel file
$phpExcel = new \PHPExcel();
$ews = $phpExcel->getSheet(0);
$ews->setTitle(Reports::LIST_AOG);
$ews->getProtection()->setSheet(true);
$ews
->getStyle('E6:F36')
->getProtection()->setLocked(
\PHPExcel_Style_Protection::PROTECTION_UNPROTECTED
);
and now I can edit only E6:F36 cell in my file in computer, then upload in google drive
$insertArray = [
'mimeType' => $fileUpload->getMimeType(),
'uploadType' => 'media',
'data' => file_get_contents($fileUpload),
'convert' => true
];
$service = new \Google_Service_Drive($client->getGoogleClient());
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($nameFile);
$file->setMimeType($fileUpload->getMimeType());
try {
$createdFile = $service->files->insert($file, $insertArray);
$spreadsheetId = $createdFile->getId();
} catch (\Exception $e) {
$view = $this->view((array)GoogleDriveController::ERROR_OCCURRED . $e->getMessage(), 400);
return $this->handleView($view);
}
I fing for google spreadsheet api bundle asimlqt/php-google-spreadsheet-client but not find how to protected
$serviceRequest = new DefaultServiceRequest($arrayAccessTokenClient['access_token']);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new SpreadsheetService();
$spreadsheet = $spreadsheetService->getSpreadsheetById($spreadsheetId);
$worksheetFeed = $spreadsheet->getWorksheets();
$cellFeed = $worksheet->getCellFeed();
$cellFeed->editCell(1, 1, 'developer');
$cellFeed->editCell(1, 2, 'hors');
$cellFeed->editCell(10, 2, 'sum');
or how to protected cell with asimlqt/php-google-spreadsheet-client ?
and In google spread sheet I can any edit any cell (((( Who knows hot to protected cell in google spreat sheet ?
UPDATE
I read Google Sheets API and try create request, this I have
$arrayAccessTokenClient = json_decode($client->getGoogleClient()->getAccessToken(), true);
$serviceRequest = new DefaultServiceRequest($arrayAccessTokenClient['access_token']);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new SpreadsheetService();
$spreadsheet = $spreadsheetService->getSpreadsheetById($spreadsheetId);
$worksheetFeed = $spreadsheet->getWorksheets();
$worksheet = $worksheetFeed->getByTitle(Reports::LIST_AOG);
$addProtectedRange['addProtectedRange'] = [
'protectedRange' => [
'range' => [
'sheetId' => $worksheet->getGid(),
'startRowIndex' => 3,
'endRowIndex' => 4,
'startColumnIndex' => 0,
'endColumnIndex' => 5,
],
'description' => "Protecting total row",
'warningOnly' => true
]
];
$guzzle = new Client();
$putTeam = $guzzle
->post('https://sheets.googleapis.com/v4/spreadsheets/'.$spreadsheetId.':batchUpdate?key='.$arrayAccessTokenClient['access_token'],
[],
json_encode($addProtectedRange)
)
->send()
->getBody(true);
$answer = json_decode($putTeam, true);
But have
Client error response
[status code] 401
[reason phrase] Unauthorized
[url] https://sheets.googleapis.com/v4/spreadsheets/1M_NFvKMZ7Rzbj9ww86AJRMto1UesIy71840r2sxbD5Y:batchUpdate?key=myAccessToken
Early I have Google Api Clien with access token and I can change cell and update with google spread sheet and work fine but https://sheets.googleapis.com/v4/spreadsheets/'.$spreadsheetId.':batchUpdate?key='.$arrayAccessTokenClient['access_token'],
return 401 and I not understand why and how to correct. Help

I think google spreadsheets allow the editing of protected MSExcel sheets the moment they become Google docs. The rules for MSExcel doesn't always apply to Google Sheets. Reading from Adding Named or Protected Ranges:
The following spreadsheets.batchUpdate request contains two request
objects. The first gives the range A1:E3 the name "Counts". The second
provides a warning-level protection to the range A4:E4. This level
protection still allows cells within the range to be edited, but
prompts a warning prior to making the change.
This thread also shares the same view.
However, if it's a google spreadsheet file you want to protect, check this guide.

I read documentation and
$addProtectedRange['requests'] = [
'addProtectedRange' => [
'protectedRange' => [
'range' => [
'sheetId' => $worksheetGid,
'startRowIndex' => $startRowIndex,
'endRowIndex' => $endRowIndex,
'startColumnIndex' => $startColumnIndex,
'endColumnIndex' => $endColumnIndex,
],
'description' => "Protecting total row",
'warningOnly' => false,
'editors' => [
'users' => [
"shuba.ivan.vikt#gmail.com"
]
]
],
]
];
This file_get_contents variant, because Guzzle not returned json response from google, like this:
{
"protectedRangeId": number,
"range": {
object(GridRange)
},
"namedRangeId": string,
"description": string,
"warningOnly": boolean,
"requestingUserCanEdit": boolean,
"unprotectedRanges": [
{
object(GridRange)
}
],
"editors": {
object(Editors)
},
}
I create new question for this for Guzzle reasponse
This is variant for update protected edit cell
$addProtectedRangeJson = json_encode($addProtectedRange);
$url = 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetId . ':batchUpdate';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n" .
"Authorization: Bearer $arrayAccessTokenClient\r\n",
'content' => $addProtectedRangeJson
)
);
$context = stream_context_create($opts);
$response = file_get_contents($url, FALSE, $context);
$answer = json_decode($response, TRUE);
$addProtectedRangeUpdate['requests'] = [
'updateProtectedRange' => [
'protectedRange' => [
'protectedRangeId' => $protectedRangeId,
'warningOnly' => false,
'editors' => [
'users' => [
"shuba.ivan.vikt#gmail.com"
]
]
],
'fields' => "namedRangeId,warningOnly,editors"
]
];
$addProtectedRangeUpdateJson = json_encode($addProtectedRangeUpdate);
$optsUpdate = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n" .
"Authorization: Bearer $arrayAccessTokenClient\r\n",
'content' => $addProtectedRangeUpdateJson
)
);
$contextUpdate = stream_context_create($optsUpdate);
$responseUpdate = file_get_contents($url, FALSE, $contextUpdate);
$answerUpdate = json_decode($responseUpdate, TRUE);
and this is Guzzle, but Guzzle without google json response this is bad I wait maybe who know what is it problem, because standard php function file_get_contents work very well and I have json google response. But without response this variant work normal, cell protected in spread sheet
$guzzle = new Client();
$postCell = $guzzle
->post('https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetId . ':batchUpdate',
[],
$addProtectedRangeJson
)
->addHeader('Authorization', 'Bearer ' . $arrayAccessTokenClient)
->addHeader('Content-type', 'application/json')
;
$postCell
->send()
->getBody(true)
;
$contents = (string) $postCell->getBody();// get body that I post -> my request, not response
$contents = $postCell->getBody()->getContents();// not find getContents, ask me did you mean to call getContentMd5
$answer = json_decode($postCell->getResponse()->getBody(), true);

Related

Telegram sendPhoto with multipart/form-data not working?

Hi I am trying to send an image. The documentation states that I can send a file using multipart/form-data.
Here is my code:
// I checked it, there really is a file.
$file = File::get(Storage::disk('local')->path('test.jpeg')) // it's the same as file_get_contents();
// Here I use the longman/telegram-bot library.
$serverResponse = Request::sendPhoto([
'chat_id' => $this->tg_user_chat_id,
'photo' => $file
]);
// Here I use Guzzle because I thought that there might be an
// error due to the longman/telegram-bot library.
$client = new Client();
$response = $client->post("https://api.telegram.org/$telegram->botToken/sendPhoto", [
'multipart' => [
[
'name' => 'photo',
'contents' => $file
],
[
'name' => 'chat_id',
'contents' => $this->tg_user_chat_id
]
]
]);
Log::info('_response', ['_' => $response->getBody()]);
Log::info(env('APP_URL') . "/storage/$url");
Log::info('response:', ['_' => $serverResponse->getResult()]);
Log::info('ok:', ['_' => $serverResponse->getOk()]);
Log::info('error_code:', ['_' => $serverResponse->getErrorCode()]);
Log::info('raw_data:', ['_' => $serverResponse->getRawData()]);
In both cases, I get this response:
{\"ok\":false,\"error_code\":400,\"description\":\"Bad Request: invalid file HTTP URL specified: Wrong URL host\"}
Other download methods (by ID and by link) work. Can anyone please point me in the right direction?
Using the php-telegram-bot
library, sendPhoto can be used like so:
<?php
require __DIR__ . '/vendor/autoload.php';
use Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Request;
// File
$file = Request::encodeFile('/tmp/image.jpeg');
// Bot
$key = '859163076:something';
$telegram = new Telegram($key);
// sendPhoto
$chatId = 000001;
$serverResponse = Request::sendPhoto([
'chat_id' => $chatId,
'photo' => $file
]);
The trick is to use Request::encodeFile to read the local image.

Cannot hide gridlines Google Spreadsheet API PHP

I am trying to hide all gridlines from a file I just created with Google Sheets API, I am using the following code:
$service = $this->GoogleServiceSheets();
$sheetID = null;
$worksheetSheets = $service->spreadsheets->get($fileID)->sheets;
foreach($worksheetSheets as $sheet){
$sheetID = $sheet->properties['sheetId'];
break;
}
$service = $this->GoogleServiceSheets();
$requests = [
new \Google_Service_Sheets_Request([
'updateDimensionProperties' => [
'range'=> new \Google_Service_Sheets_DimensionRange([
'sheetId' => $sheetID,
'dimension' => 'COLUMNS',
'startIndex' => 0,
'endIndex' => 1000
]),
'properties'=> new Google_Service_Sheets_DimensionProperties([
"hideGridlines"=> True,
]),
'fields' => 'hideGridlines'
]
])
];
$batchUpdateRequest = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest(['requests' => $requests]);
$service->spreadsheets->batchUpdate($fileID, $batchUpdateRequest);
But does not hide, instead gives me an error.
What I am doing wrong?
In order to hide the grid line of the Google Spreadsheet with Sheets API, UpdateSheetPropertiesRequest of batchUpdate is used. Unfortunately, updateDimensionProperties cannot achieve this. I think that this is the reason of your issue. In order to achieve your goal, when your script is modified, it becomes as follows.
Modified script:
In this modification, your $requests is modified as follows.
$requests = [
new \Google_Service_Sheets_Request([
'updateSheetProperties' => [
'properties' => [
'sheetId' => $sheetID,
'gridProperties' => [
'hideGridlines' => true
],
],
'fields' => 'gridProperties.hideGridlines'
],
])
];
Note:
In this modification, it supposes that your $service = $this->GoogleServiceSheets(); and $sheetID are valid values. And also, it supposes that you have already been able to get and put values for Google Spreadsheet using Sheets API. Please be careful this.
Reference:
UpdateSheetPropertiesRequest

Firebase Update Multiple Items

How can I update multiple items on firebase with just one request?
I can not let my system wait to complete multiple requests, so I need to update them with just one.
Current Firebase Data:
PHP Code:
$data = [
'mydata-1' => [
'position' => 1,
],
'mydata-2' => [
'position' => 2,
],
];
$client = new \GuzzleHttp\Client();
$response = $client->put(FIREBASE_ENDPOINT . '/data', [
'json' => $data,
]);
Expected Firebase Data:
Problem:
The request subscribe all my data and I lose the title field.
I also tried PATCH request, but I got the same response.
Based on Frank van Puffelen comment:
$data = [
'mydata-1/position' => 1,
'mydata-2/position' => 2,
];
$client = new \GuzzleHttp\Client();
$response = $client->patch(FIREBASE_ENDPOINT . '/data', [
'json' => $data,
]);
Documentation:
https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html

Upload file using Guzzle 6 to API endpoint

I am able to upload a file to an API endpoint using Postman.
I am trying to translate that into uploading a file from a form, uploading it using Laravel and posting to the endpoint using Guzzle 6.
Screenshot of how it looks in Postman (I purposely left out the POST URL)
Below is the text it generates when you click the "Generate Code" link in POSTMAN:
POST /api/file-submissions HTTP/1.1
Host: strippedhostname.com
Authorization: Basic 340r9iu34ontoeioir
Cache-Control: no-cache
Postman-Token: 6e0c3123-c07c-ce54-8ba1-0a1a402b53f1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="FileContents"; filename=""
Content-Type:
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="FileInfo"
{ "name": "_aaaa.txt", "clientNumber": "102425", "type": "Writeoff" }
----WebKitFormBoundary7MA4YWxkTrZu0gW
Below is controller function for saving the file and other info. The file uploads correctly, I am able to get the file info.
I think the problem I am having is setting the multipart and headers array with the correct data.
public function fileUploadPost(Request $request)
{
$data_posted = $request->input();
$endpoint = "/file-submissions";
$response = array();
$file = $request->file('filename');
$name = time() . '_' . $file->getClientOriginalName();
$path = base_path() .'/public_html/documents/';
$resource = fopen($file,"r") or die("File upload Problems");
$file->move($path, $name);
// { "name": "test_upload.txt", "clientNumber": "102425", "type": "Writeoff" }
$fileinfo = array(
'name' => $name,
'clientNumber' => "102425",
'type' => 'Writeoff',
);
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', $this->base_api . $endpoint, [
'auth' => [env('API_USERNAME'), env('API_PASSWORD')],
'multipart' => [
[
'name' => $name,
'FileContents' => fopen($path . $name, 'r'),
'contents' => fopen($path . $name, 'r'),
'FileInfo' => json_encode($fileinfo),
'headers' => [
'Content-Type' => 'text/plain',
'Content-Disposition' => 'form-data; name="FileContents"; filename="'. $name .'"',
],
// 'contents' => $resource,
]
],
]);
if($res->getStatusCode() != 200) exit("Something happened, could not retrieve data");
$response = json_decode($res->getBody());
var_dump($response);
exit();
}
The error I am receiving, screenshot of how it displays using Laravel's debugging view:
The way you are POSTing data is wrong, hence received data is malformed.
Guzzle docs:
The value of multipart is an array of associative arrays, each
containing the following key value pairs:
name: (string, required) the form field name
contents:(StreamInterface/resource/string, required) The data to use in the
form element.
headers: (array) Optional associative array of custom headers to use with the form element.
filename: (string) Optional
string to send as the filename in the part.
Using keys out of above list and setting unnecessary headers without separating each field into one array will result in making a bad request.
$res = $client->request('POST', $this->base_api . $endpoint, [
'auth' => [ env('API_USERNAME'), env('API_PASSWORD') ],
'multipart' => [
[
'name' => 'FileContents',
'contents' => file_get_contents($path . $name),
'filename' => $name
],
[
'name' => 'FileInfo',
'contents' => json_encode($fileinfo)
]
],
]);
$body = fopen('/path/to/file', 'r');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=file
In Laravel 8 with guzzle I am using this:
The idea is that you are reading the file with fread or file_get_content, then you can use the Laravel getPathname() which points to the file in /tmp
$response = $this
->apiClient
->setUserKey($userToken)
->post(
'/some/url/to/api',
[
'multipart' => [
'name' => 'avatar',
'contents' => file_get_contents($request->file('avatar')->getPathname()),
'filename' => 'avata.' . $request->file('avatar')->getClientOriginalExtension()
]
]
);

API return PNG image with Guzzle

I'm sending an API request to Box.com to get the thumbnail of a PNG image. I'm using Laravel. When I'm using the following code I'm getting raw string data that I want to convert PNG image.
$client = new Client('https://api.box.com/{version}/files/{file_id}', [
'version' => '2.0',
'file_id' => $id,
'request.options' => [
'headers' => [
'Authorization' => 'Bearer ' . self::getAccessToken(),
]
]
]);
$request = $client->get('thumbnail.png?min_height=256&min_width=256');
try {
$response = $request->send();
dd($response->getBody(true));
Without returning the getBody() method string I don't get anything as Box.com will be returned with the contents of the thumbnail in the body.
Here's the example string I'm getting:
b"""
‰PNG\r\n
\x1A\n
\x00\x00\x00\rIHDR\x00\x00\x01\x00\x00\x00\x01\x00\x08\x06\x00\x00\x00\r¨f\x00\x00\x00\x06bKGD\x00ÿ\x00ÿ\x00ÿ ½§“\x00\x00\x00\tpHYs\x00\x00\x00H\x00\x00\x00H\x00FÉk>\x00\x00\x00\tvpAg\x00\x00\x01\x00\x00\x00\x01\x00\x00²gÜŠ\x00\x00€\x00IDATxÚÌýiŒ-[–߇ýö\x14Ã9™y3ï}ᄅޫªî®êê2%Ñ$[à \x19¶!Y&)\x1A”iC\x10`Ø0\x04I¶õÙ\x06,\x7F0­\x0F$a›0!Û0M‘¢\x04\x0E¦Dv³\x075ÙÕC©ç¡º»z¨ù½\x1AÞ|ç\x1CΉˆ=ùÃÚ\x11'ÎÉ“Ã}]2\x1C\x0Fùnæ\x19"vìØkí5ü×\x7F©Óó'\x19#)…RŠ˜\x13™ù‘Ñãoy眧ïí;²|ˆë\x0FÅö\x05óôÿ4~B©­qÌ?¹ýÕŒš>¿ÿÈ{Æ£”"ç<½7~\x7F¼¿Ý×wÏ“sFk½ýZÊ \x00\x12ÞwXcpÎñcÿäGøíßü5BPüþ—¾Ž±†\x14#\x19è;O×]\x00‰¾_ã½/3¤dš²"gEŒ\x11¥ÔtÍÍØ˳ș\x10#Zk¬5[ã\x1AŸWJ2»Z),š#ÆÇPÆž¶î{3G\t­\r0*•ëRÖÆZGJi\x1A_y\x13­\x15ÖT\fÞ“‰h5Η¡ª\x1CÚ\x18\x19óà‰1¢†\fYAUUÔuÍ0\f[ÏDk1\x1Ac\x1C9'B\x08TUÅb± gMí\x0Eù÷þÝÿ€ÿî\x7Fï_áÃ'ï¡ŒA;M&SåŒÒzöüT¹Ç²\UùㆵôÿoÇî3»êÏÈ<Úýg‚\x14eRµ ÕÖE\x00RJ{\x05cç4Üb8EP惓Co^$“IYm>ªæ\x0F-ï\x15ÎÛ>¼}“6\n
Õü~÷)»ËBRþVY\x16f\x1CÐ\x1A\x1E<xÈ_ùË\x7F™EÓÒwkÖë\x18#\x17\x17ç\x18c\x08>\x12Ä\x18I)\x10cœÎ•\x15¨œ\x01CJyKè'eE\x16¥“5Z+Œ¶“ ŒB©õ¶\n
•û1„\\x16~Ö#Þ{¯£°§,Š8\x15Á×J¡´"%EŒ‰œå»:Éx´QXeE¦væ\x162!\x04\x08ÊU4ÖÑ…\x04Q\x06\x14É\f\fh­EÉ”9Ù܇(¥ñ\x08Á³^­iÛ\x03ž>{Äßø›ÿ1_{ó+üÅÿÉÿ”>\U¶Š”\x1Dz6wj:›h€<{Äó¹Ø}Ö7­¥›>£§g÷9n\x12þ}r2Wƒä”ÉãDŒS¢.\vÿøûø`æ\vr÷çºÁlÞß\x7Fù¡Pä4\x1A\x14£ÕPVnÙùwÏ?*©ÛŒgßw÷Ýëí\x1F#"\x13\x08¡çøø˜¿ÿ÷ÿ.¿÷{¿‹ÖŽÓ§kúÁ£µ,ê¾ï\x19\x06Oˆ‘˜â´ÐSJò\x13#1&RÊh}yÞ)S!ceë}™¢Ë\x16€R\n
cŒì¶Jì-­äûƘÉJ˜Ïáø¤2²ãÇl\x08I\x11"(•€#Îò“ˆ$\x15‰9àCOïûÙcV[\x16L\x08\x01¥ÀY+c\x18Ç]þ‹1N?ãx¼÷Ó=Ž–R\x08‘~è9;\x7FJU+\x1E?y‡ÿìïü'üÌg\x7F†E]ã»\x0E•6s²µ.ÆŸG<^c¾á]wÌç÷ÆÏd™z]~H\x19•òô÷üGM?Yþ¥<¶2WE;_«M6ãß|È&5\x7F°y:±Ñ\n
ãì¥\t™Ÿì;e\x1EM¦×l‚.\v\x14h}…rØ£¡çç¹Í1í¶;nÍüïq\x11ì;¯ì\x142“!\x052"Ø'GGü½¿÷Ÿó³?û9¾÷{¿Ÿ\x0F\x1F< ÷žÞwX+\x06X\x08\x1E­\fÞ\x0FÄ\x14\x10‹xŸÂºäô\žƒ¸3æÙï£ÐUUEJi\x12<Hh£ÐFîËÚ†¾ï'ÛwŒ»°Œ(ô\x13Ï,\x08-®KR\t2h¥‘Ó)òÌÚ\x00è‡\x01¯\x03É(bH"ú9#L$£Š|¦òyKJ‰aÐ8[Íž]$„HΉõúŒÃ£CŽ\x0F\x0Fù+\x7FåÿÈK¯üUþù\x7Fñ¿Åã'OX.Ýf:)›Ëöln­Ÿ«\¿ùßÛ›ã~Ï÷*ËtRæ)m¹&›‘Ì­§2ð\x1D·y|?å<½µ»aoddöúÓ‹Çy\À(…¾”§›È»\x03Þ½»¼{C›kŒ\x0Fø*Óyòcaï.~ÝuPÛ\x13z\e\x05°ï3û\x1Eêh2ßÖ¯Úún\n
taÍÑbÉÃ\x07ïóïü;ÿK\x16Í]#\x11c “ñƒ‡œéûž¾\x1Fd×Lž\x10â4®4w\x03r"cQJO×\x11Aß\×\x1A‡RfÚ±Æç Ôæ>1Ôuµ–õz\rdb\x1CPJÏ”Ž™¬¹5tµ\v”PjÛ]J)cŒÞ|'\e(f<ˆ•1~?¥´eam”N\x002ιò¹éœÉ8SSW\vbô(•È$BJhmq®¢®\x174®Á\x0Fž”áoüÍ¿Å\v/Üålý”¦YÈwrBa‹BS›e¦Š\x1D|źÝ]só¿s¾z³š\x1Fzwy“E\x19Í]»\rgW!_z\x1ElÄä*¹Ø\x1AÃÎÝMÚcnY>\x00Ì\x17çü{»æøü³J)2Š´õ³çØØA“ðß4Žç\x19óüßçµnæ÷–RÂ\x02Ýê”ÿè/ý%â ‹»ëÖ¬V+Ö«5Cß³Z­\x08!L®À\èÈ\x19=úØåÖ·\x03•\x1A¥2"$QLp\x15ÑF¡t&\x13G\eqúŽµ\x16k\r©ëŠ¶mpÎaŒ#¥LUÕhm&!ݧ,÷í†9³ež‹{¡ËwÆu´\x11à]·qsÂm×M\\x05MŒ©Ä\x17Ƶ‚\x04\x0EÕÜòbº×\x18Å\x12\x18úu·¢®\x1DëÕ\x05ÿç¿úWyvzŠVfR®JAVâjŒëJ+0*£È¨œP)A”ŸÑ\x1CÏyg=çòy\x10{b\fHÏ~¶ærßòÞ±<ækr\x1Eó¹ÊÍÈ;nëÍk¸Ä\x00òü\v{LÏ­‹ßF\x1AJ`nôÓ®\vœMç\x1Fýݙ߹{ì¾~\eÿþºÏìúúû”ÓíŽmí\x1F\x06ÏñCþÊ_ù?ñæW¿ÆA}‡¾ëI)•\x1D¿g\x18\x06Bð\fÃÀ0øiל+J¥ÔF‚Ô¾lÉÆnR\n
RÊ[Šd¾«j­‹°\eŒ1²àË÷mp¶Áššº^Hl`Çú\x19M~­õôžµ¶ü¾]PJQUM±Fdg\x7Fn\ WLãìy¥K\x01ÉyÌ#çqGTEð7ë'F\t¤\x06ßs~q΋/ÞãÇ~ô\x1Fó\x0FÿÁ?äèè„uwQ\x02ŸvÚu·×Æ•ÃÛz\x06ã#Ú\x08½(\x10ÚñáE™èœÐÈç2iKñl6¶¼y>;\eÞMY·<›Ã›â\x169ƒV%\x12¨•BoìÅí%¶'ò\x7F­8Ì\x16Ý8˜]­µ+˜i.|W(šÍw/¿öQŽ}©¿yŠlþÞüõKãʱ<#Mß_prÒð\x13?úÃüê/\x7Fžû/½N7x\x06?L»d\x08Pv©\x10\x02>xB\f¨Ùœ¥Q9•hù|wÜÝiE\x10M\x11‚0\tÿ˜\x01\x18?\eBÀûHJ\n
"""
I got the success response for image as unique string values
$response = $this->client->request('GET', '/ap/generate-example/qr/image', [
'headers' => [
'Content-Type' => 'application/json',
'user_name' => 'user_name',
'password' => 'password',
'Authorization' => "Bearer assdadga",
'width' => '300',
'height' => '300',
'imgtype' => 'jpg'
],
// 'sink' => '/uploads/images'
]);
$body = $response->getBody();
$base64 = base64_encode($body);
$mime = "image/jpeg";
$img = ('data:' . $mime . ';base64,' . $base64);
dd($img);
Output:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/wAALCADcANwBAREA/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaE
let's view this with
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQA" />
I've figured it out myself using Guzzle3 on Laravel 5.1. Here's the relevant code which I hope you may find helpful in future:
In your model or if you prefer to use controller then it's fine:
/**
* Get download link from Box.com
*
* #param $id
* #return bool|int|string
*/
public static function getDownloadLink($id)
{
$client = new Client('https://api.box.com/{version}/files/{file_id}', [
'version' => '2.0',
'file_id' => $id,
'request.options' => [
'headers' => [
'Authorization' => 'Bearer ' . self::getAccessToken(),
]
]
]);
$request = $client->get('content');
try {
$response = $request->send();
$result = $response->getEffectiveUrl();
} catch (BadResponseException $e) {
$result = $e->getResponse()->getStatusCode();
if ($result === 401) {
self::regenerateAccessToken();
return self::getDownloadLink($id);
}
}
return count($result) ? $result : false;
}
In the above static method, I've sent a GET request to the Box.com API and the API returns with an effectiveUrl and that's the direct download file link we're looking for.

Categories