Request to RingCentral API - php

I am trying to send a request to RingCentral API. The link to documentation is https://developers.ringcentral.com/api-reference/Fax/createFaxMessage If I don't specify faxResolution or coverIndex everything goes well, fax could be sent. But if I add faxResolution param like in the code below, I receive error "Parameter [faxResolution] value is invalid", "errorCode" : "CMN-101". The same thing with coverIndex param. My client is GuzzleHttp 6.3
$token = $this->ringcentral->platform()->auth()->data()['access_token'];
$a = array();
foreach ($destination_numbers as $number) {
$a[] = [
'name' => 'to',
'contents' => $number,
'headers' => ['Content-Type' => 'multipart/form-data']
];
}
$a[] = [
'name' => 'faxResolution',
'contents' => 'High',
'headers' => ['Content-Type' => 'multipart/form-data']
];
foreach ($attachments as $attachment) {
$file_pointer = fopen($attachment, 'r');
$mime = mime_content_type($attachment);
$a[] = [
'name' => 'attachment',
'contents' => $file_pointer,
'headers' => ['Content-Type' => $mime]
];
}
$client = new Client();
try {
$response = $client->request('POST', url(config('services.ringcentral.app_url')) . '/restapi/v1.0/account/~/extension/~/fax', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
],
'multipart' => $a
]);
$response = json_decode($response->getBody(), true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
echo($e->getResponse()->getBody()->getContents());
}

Here's what RingCentral suggests when using PHP. I included all of what they suggested, but just look at the part about faxResolution (2/3 of the way down)
<?php
// https://developers.ringcentral.com/my-account.html#/applications
// Find your credentials at the above url, set them as environment variables, or enter them below
// PATH PARAMETERS
$accountId = '<ENTER VALUE>';
$extensionId = '<ENTER VALUE>';
$recipient = '<ENTER VALUE>';
require('vendor/autoload.php');
$rcsdk = new RingCentral\SDK\SDK(getenv('clientId'), getenv('clientSecret'), getenv('serverURL'));
$platform = $rcsdk->platform();
$platform->login(getenv('username'), getenv('extension'), getenv('password'));
$request = $rcsdk->createMultipartBuilder()
->setBody(array(
'to' => array(array('phoneNumber' => $recipient)),
'faxResolution' => 'High',
))
->add(fopen('fax.jpg', 'r'))
->request("/restapi/v1.0/account/{$accountId}/extension/{$extensionId}/fax");
$r = $platform->sendRequest($request);
?>

Related

make the variable as string in laravel

how are you ?
I'm using Guzzle to send post method but when i tried to send the post method with variable getting error so i tried to convert it to sting but still same
this is my current code
if $ mobile value is 55454545445 , them the 'numbers' => "{$mobile}" will be different not "55454545445"
$user = Auth::user();
$mobile = $user->mobile;
$client = new Client();
$booking = Booking::where('id', '=', e($id))->first();
if($booking)
{
$booking->booking_status_id = 3;
$booking->save();
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$data = array('userName' => "test",
'apiKey' => "1",
'numbers' => "{$mobile}",
'userSender' => "sender",
'msg' =>'msg',
'msgEncoding' => "UTF8",);
$dataJson = json_encode($data);
$response = $client->post('https://www.test.test',
['body' => $dataJson]
);
i used this
"0{$mobile}"
instead of
"{$mobile}"
and its work

In Laravel How to create subscriber in mailchimp using Guzzle HTTP

I am using guzzle HTTP to send the request and I am getting this error
Client error: POST https://us17.api.mailchimp.com/3.0/batches resulted in a 401 Unauthorized response:
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"API Key Missing","statu (truncated...)
$userArray = [];
$operations = [];
//used to get the patient that need to sync mailchimp
$getPatientToSync = Patient::select('NameFirst', 'NameLast' , 'Email')
->where([['flag_name' , '=', '1'], ['mailchimp_synced' ,'=' , '0']])->get();
if($getPatientToSync->isEmpty()){
return true;
}
foreach ($getPatientToSync as $patient){
$data = array(
"apikey" => config('mailchimp.api_key'),
"email_address" => $patient->Email,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $patient->NameFirst,
'LNAME' => $patient->NameLast,
)
);
$userArray[] = json_encode($data);
}
foreach ($userArray as $userArr){
$temp = array(
"method" => "POST",
"path" => "/lists/".config('mailchimp.list_id')."/members/",
"body" => $userArr
);
$operations['operations'][] =$temp;
}
$json_post = json_encode($operations);
$auth = base64_encode( 'user:'.config('mailchimp.api_key') );
//API URL
$urll="https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
$headers = array('Content-Type: application/json', 'Authorization: Basic
'.$auth , $userlist);
$client = new Client();
$response = $client->request('POST', $urll , $headers,json_post );
dd($response);
First of all, you use Guzzle's request() method in a wrong way. The right way is:
$client->request('POST', $urll, [
'headers' => $headers,
'json' => $operations
]);
Try it and then pay attention to the error message (it'a also useful).

PHP Azure OCR - use local file

I'm using the Azure OCR Service to get the text of an image back (
https://learn.microsoft.com/de-de/azure/cognitive-services/Computer-vision/QuickStarts/PHP).
So far everything is up and running, but now I would like to use a local file instead of an already uploaded one.
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
// Request body
$request->setBody("{body}"); // Replace with the body, for example, "{"url": "http://www.example.com/images/image.jpg"}
Unfortunately I don't know how to pass the raw binary as the body of my POST request in PHP.
At first, when we refer local file, we should use 'Content-Type': 'application/octet-stream' in a header, then we can send requests that use a stream resource as the body.
Here's my working code using Guzzle for your reference:
<?php
require 'vendor/autoload.php';
$resource = fopen('./Shaki_waterfall.jpg', 'r');
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze', [
'query' => [
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en'
],
'headers' => [
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>'
],
'body' => $resource
]);
echo $res->getBody();
Using HTTP_Request2:
<?php
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze');
$url = $request->getUrl();
$headers = array(
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>',
);
$request->setHeader($headers);
$parameters = array(
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en',
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setBody(fopen('./Shaki_waterfall.jpg', 'r'));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}

(Updated) Laravel PUT Method Not Working

updated - the JSON file would return but it will not change the billing date at all.
Reference 1: The official documentation about changing the billing date.
Reference2: their sample code in detail:
<?php
$request = new HttpRequest();
$request->setUrl('https://domain.chargify.com/subscriptions/$subscriptionId.json');
$request->setMethod(HTTP_METH_PUT);
$request->setHeaders(array(
'authorization' => 'Basic YXBpa2V5Og==',
'content-type' => 'application/json'
));
$request->setBody('{"subscription":{"next_billing_at":"2028-12-15"}}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
My code in detail:
public function changeYearlySubscriptionBillingDate(Request $request)
{
$user = $request->user();
$subscriptionId = $user->subscription->subscription_id;
$nextBilling = Carbon::now()->addYear();
$hostname = env('CHARGIFY_HOSTNAME');
$headers = [
'authorization' => 'Basic ANIDIANDIAJIJCQ',
'content-type' => 'application/json'
];
$body = ["subscription" => ["next_billing_at" =>[ $nextBilling ]]];
$config = [
'headers' => $headers,
'form_param' => $body
];
$client = new Client($config);
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json",
["json" => [
[ "subscription" =>
[ "next_billing_at" => $nextBilling ]
]
]
]);
echo $res->getBody();
}
The url you are building is incorrect. There shouldn't be a / between $subscription and .json
Change
$res = $client->put("https://$hostname/subscriptions/$subscriptionId/.json",
to
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json",
EDIT
Try changing the logic to make Guzzle call like this.
$headers = [
'authorization' => 'Basic ANIDIANDIAJIJCQ',
'content-type' => 'application/json'
];
$body = ["subscription" => ["next_billing_at" =>[ $nextBilling ]]];
$client = new Client();
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json",
[
'headers' => $headers,
'body' => json_encode($body)
]
);
echo $res->getBody()->getContents();
thanks everyone so much for helping me out.
I've been working on this problem for 2 days and it was supposed to be right to me. Eventually, it is their API that misled me.
the only thing we need to do, is simply change
'body' => "{\"subscription\":{\"next_billing_at\":\"$nextBilling\"}}"
added a few '\' s inside.
Thanks everyone for helping me out, have a good day!

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