I'm trying to authentificate by OAuth token but i didn't find the way to get it without Google prompt and url redirection.
I'm using php and google/apiclient:"^2.7" library
I try to get token with it but I didn't find the way to get it.
If it's not possible to perform it without a google prompt, how I can authenticate my request to the https://logging.googleapis.com/v2/entries:list?
Thanks in advance for your help.
I tried with the following method
public function init()
{
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $this->container->getParameter('service-account-authentification-file'));
$scopes = [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloud-platform.read-only',
'https://www.googleapis.com/auth/logging.admin',
'https://www.googleapis.com/auth/logging.read',
'https://www.googleapis.com/auth/logging.write'
];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://logging.googleapis.com/',
'auth' => 'google_auth'
]);
$httpClient = $client->authorize();
$data = [
"resourceNames" => ["xxxx"],
"filter" => "xxxxxx",
];
$response = $httpClient->post('https://logging.googleapis.com/v2/entries:list', [
'body' => json_encode($data)
]);
}
I also tried with this other method provided by the https://github.com/googleapis/google-cloud-php & https://github.com/googleapis/google-cloud-php-logging
$logging = new LoggingClient([
'keyFilePath' => $this->container->getParameter('service-account-authentification-file')
]
);
$entries = $logging->entries([
'filter' => 'logName = projects/****logs/stdout'
]);
foreach ($entries as $entry) {
echo $entry->info()['textPayload'] . "\n";
}
Response is always the same
"error": {
"code": 403,
"message": "The caller does not have permission",
"status": "PERMISSION_DENIED"
}
I tried to use Curl
curl --request POST \
'https://logging.googleapis.com/v2/entries:list?key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{}' \
--compressed
but i have such error too
{
"error": {
"code": 400,
"message": "The API Key and the authentication credential are from different projects.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developer console API key",
"url": "https://console.developers.google.com/project/******/apiui/credential"
}
]
},
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CONSUMER_INVALID",
"domain": "googleapis.com",
"metadata": {
"consumer": "projects/******",
"service": "logging.googleapis.com"
}
}
]
}
}
Related
I have this cURL command that I need to convert to PHP using Guzzle 7. I've have been researching this for a few (well, more than a few) days and getting nowhere fast. The cURL command uses the Simpli.fi api to create an organization under the parent org.
curl -i -X POST -H "X-App-Key: xxxx-xx-xx-xx-xxxxxx" -H "X-User-Key: xxxx-xx-xx-xx-xxxxxx" \
-H "Content-Type: application/json" \
-d '{
"organization": {
"name": "My New Organization",
"parent_id": "5786",
"custom_id": "<Put your organization identifier here or omit this optional field>"
}
}' \
"https://app.simpli.fi/api/organizations"
I was able to convert it using this website but it doesn't use Guzzle: https://onlinedevtools.in/curl
Here's what it gave me:
include('vendor/rmccue/requests/library/Requests.php');
Requests::register_autoloader();
$headers = array(
'X-App-Key' => 'xxxx-xx-xx-xx-xxxxxx',
'X-User-Key' => 'xxxx-xx-xx-xx-xxxxxx',
'Content-Type' => 'application/json'
);
$data = '{\n "organization": {\n "name": "My New Organization",\n "parent_id": "5786",\n "custom_id": "<Put your organization identifier here or omit this optional field>"\n }\n }';
$response = Requests::post('https://app.simpli.fi/api/organizations', $headers, $data);
Here's what I've tried so far aside from the converted code above:
public static function createOrganization()
{
self::init();
$client = new Client(['debug' => true]);
$request = $client->request('POST',
self::$baseUrl.'/organizations', [
'multipart' => [
[
'name' => 'data',
'contents' => "{'organization':{'name':'Pete's Pet Pagoda','parent_id':'1052385'}}",
],
],
'headers' => [
'x-app-key' => self::$appKey,
'x-user-key' => self::$userKey,
'Content-Type' => 'application/json',
]
]);
dd($response = $request->getStatusCode());
}
I'm getting quite a few different errors however this is the latest:
curl_setopt_array(): cannot represent a stream of type Output as a STDIO FILE*
Can anyone tell me what I'm doing wrong? Is there something missing?
UPDATE: After further research into this issue and chatting with a developer on the Laracast Slack channel, I've come to learn that this is a bug with the ['debug' => true] option when running on a Windows system and is described on this GITHUB page: https://github.com/guzzle/guzzle/issues/1413
I'm running on a Windows 10 Pro system. I corrected it on my end by changing the debug option to use fopen() like this:
'debug' => fopen('php://stderr', 'w'),
I use PHPStorm. It suggested using the 'wb' to make it binary safe. After changing it, the post requests worked fine.
You need to use body, not multipart. You can also use json.
$request = $client->request('POST',
self::$baseUrl.'/organizations', [
'headers' => [
'x-app-key' => self::$appKey,
'x-user-key' => self::$userKey,
'Content-Type' => 'application/json',
],
'body' => [
'{"organization":
[
{
"name":"Pete`s Pet Pagoda",
"parent_id":"1052385"
}
]
}',
],
]);
method 2
You can pass array to the json request option and it will convert it to json when sending the guzzle request. No need to use header as application/json as it applies internally.
$client->request('POST',
self::$baseUrl.'/organizations', [
'headers' => [
'x-app-key' => self::$appKey,
'x-user-key' => self::$userKey,
'Content-Type' => 'application/json',
],
'json' => [
"organization" => [
[
"name" => "Pete`s Pet Pagoda"
"parent_id" => "1052385"
]
]
],
]);
I hope this will help you. For further debugging use Middleware::tap(find more help here middleware+json+request)
try{
$client = new Client();
$response = $client->request('POST', self::$baseUrl.'/organizations',
[
'headers' => [
'x-app-key' => self::$appKey,
'x-user-key' => self::$userKey,
'Content-Type' => 'application/json',
],
'json' => [
'organization' =>
[
"name" => "some_name_value",
"parent_id" => "id_here",
"custom_id" => "custom id here"
]
]
]);
$_response = json_decode($response->getBody()->getContents(), true);
}
catch(BadResponseException $e){
$response = $e->getResponse();
$errorArray = json_decode($response->getBody()->getContents(), true);
//echo "<pre>";
//print_r($errorArray);
//return some message from errorarray;
}
I've got this CURL that I'm executing on the command line and it successfully creates content in my CMS (Drupal 9).
curl \
--user username:9aqW72MUbFQR4EYh \
--header 'Accept: application/vnd.api+json' \
--header 'Content-type: application/vnd.api+json' \
--request POST http://www.domain.drupal/jsonapi/node/article \
--data-binary #payload.json
and the JSON file as:
{
"data": {
"type": "node--article",
"attributes": {
"title": "My custom title",
"body": {
"value": "Custom value",
"format": "plain_text"
}
}
}
}
Working like a charm and data is being created.
I've been trying to do this in GuzzleHttp but couldn't get it working.
Get is working:
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$url = 'http://www.domain.drupal';
$content_client = new GuzzleHttp\Client([
'base_uri' => $url,
'timeout' => 20.0,
]);
$res = $content_client->request('GET', '/jsonapi/node/article/71adf560-044c-49e0-9461-af593bad0746');
For POST, I've got probably around 10 versions trial and error but nothing worked.
How can I POST my JSON/Content to Drupal or how can I correctly implement the CURL in Guzzle?
If you want a simple post request to send json body with your headers you can do it simply without using Psr7 Request. Guzzle utilizes PSR-7 as the HTTP message interface.
use GuzzleHttp\Client;
$url = 'http://www.domain.drupal';
$content_client = new Client([
'base_uri' => $url,
'timeout' => 20.0,
]);
$headers = [
'Content-type' => 'application/vnd.api+json',
'Accept' => 'application/vnd.api+json'
];
$payload['data'] = [
'type' => 'node--article',
'attributes' => [
"title" => "My custom title",
"body" => [
"value" => "Custom value",
"format" => "plain_text"
]
]
];
$guzzleResponse = $content_client->post('/jsonapi/node/article/71adf560-044c-49e0-9461-af593bad0746', [
'json' => json_encode($payload),
'headers' => $headers
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody());
}
You can write it in try catch block with using RequestException (see this Catching exceptions from Guzzle to know more about it.)
I am trying to create a PHP script which shares posts on LinkedIn automatically with the help of zoonman/linkedin-api-php-client SDK https://github.com/zoonman/linkedin-api-php-client. I could share a post without any media and it is visible on my LinkedIn wall. When trying to share a post with an image, the API response returned true with an id urn:li:share:6605357601301553152, but the post is not visible on my wall. I am providing my code for posting media below.
public function postMedia($data,$accessToken){
try{
$mediareturn = $this->client->post(
'assets?action=registerUpload',
[
"registerUploadRequest"=>[
"recipes"=> [
"urn:li:digitalmediaRecipe:feedshare-image"
],
"owner"=> "urn:li:person:**********",
"serviceRelationships"=> [
[
"relationshipType"=> "OWNER",
"identifier"=> "urn:li:userGeneratedContent"
]
]
]
]
);
$uploadUrl = $mediareturn['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'];
$filepath = $this->root_url.'assets/uploads/'.$data['attachment'];
$shell = shell_exec('curl -i --upload-file '.$filepath.' --header "Authorization: Bearer "'.$accessToken.' '.$uploadUrl);
$share = $this->client->post(
'ugcPosts',
[
"author"=> "urn:li:person:**********",
"lifecycleState"=> "PUBLISHED",
"specificContent"=> [
"com.linkedin.ugc.ShareContent"=> [
"shareCommentary"=> [
"text"=> $data['content']
],
"shareMediaCategory"=> 'IMAGE',
"media"=> [
[
"status"=> "READY",
"description"=> [
"text"=> "Center stage!"
],
"media"=> $mediareturn['value']['asset'],
"title"=> [
"text"=> "Test posting"
],
"thumbnails"=> [],
]
]
]
],
"visibility"=> [
"com.linkedin.ugc.MemberNetworkVisibility"=> "PUBLIC"
]
]
);
return $share;
}catch(Exception $e){
throw $e;
}
}
The above code was written referring the official document https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin.
Any and all help would be greatly appreciated.
I am trying to use guzzle to do a post request to an open API. I am also sending the post data as follows. For some reason i am getting a 400 bad request
$req = $client->request('POST',$this->base_url.'nutrients?app_id='.$this->app_id.'&app_key='.$this->api_key,[
'headers' => [
'Content-Type' => 'application/json'
],
\GuzzleHttp\RequestOptions::JSON => [
"yield" => $portions,
"ingredients" => [
"quantity" => $portions,
"measureURI" => "\"$f_uri\"",
"foodURI" => "\"$m_uri\""
]
]
]);
$response = $client->send($req);
$decoded = json_decode($response->getBody());
dd($decoded);
The api documentation shows the method in curl as follows:
curl call:
curl -d #food.json -H "Content-Type: application/json" "https://api.edamam.com/api/food-database/nutrients?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
food.json:
{
"yield": 1,
"ingredients": [
{
"quantity": 1,
"measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_unit",
"foodURI": "http://www.edamam.com/ontologies/edamam.owl#Food_11529"
}
]
}
My links for measureURI and foodURI are generated correctly.
You don't need to do ->send() after the ->request(), it already returns an instance of ResponseInterface.
So just
$response = $client->request('POST', $this->base_url.'nutrients?app_id='.$this->app_id.'&app_key='.$this->api_key, [
// ...
]
]);
$decoded = json_decode($response->getBody()->getContents());
I'm trying to covert a curl to guzzle request, here is the curl request.
curl https://{subdomain}.zendesk.com/api/v2/tickets.json \
-d '{"ticket": {"subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \
-H "Content-Type: application/json" -v -u {email_address}:{password} -X POST
here is the JSON portion:
{
"ticket": {
"requester": {
"name": "The Customer",
"email": "thecustomer#domain.com"
},
"subject": "My printer is on fire!",
"comment": {
"body": "The smoke is very colorful."
}
}
}
Here is my broken PHP code.
$client = new GuzzleHttp\Client();
$res = $client->post('https://midnetworkshelp.zendesk.com/api/v2/tickets/tickets.json', [
'query' => [
'ticket' => ['subject' => 'My print is on Fire'], [
'comment' => [
'body' => 'The smoke is very colorful'] ], 'auth' => ['email', 'Password']]);
echo $res->getBody();
I keep getting access unauthorized for the user, however when I fire the curl command it works fine.
Any idea on what I'm possibly missing here?
Thank you
Ref:
http://curl.haxx.se/docs/manpage.html
http://guzzle.readthedocs.org/en/latest/clients.html
https://github.com/guzzle/log-subscriber
http://guzzle.readthedocs.org/en/latest/clients.html#json
Your biggest issue is that you are not converting your curl request properly.
-d = data that is being posted. In other words this is the body of your request.
-u = the username:pw that is being used to authenticate your request.
-H = extra headers that you want to use within your request.
-v = verbose output.
-X = specifies the request method.
I would recommend instanciating your client as follows:
$client = new GuzzleHttp\Client([
'base_url' => ['https://{subdomain}.zendesk.com/api/{version}/', [
'subdomain' => '<some subdomain name>',
'version' => 'v2',
],
'defaults' => [
'auth' => [ $username, $password],
'headers' => ['Content-Type' => 'application/json'], //only if all requests will be with json
],
'debug' => true, // only for debugging purposes
]);
This will:
Ensure that multiple subsequent requests made to the api will have the authentication information. Saving you from having to add it to each and every request.
Ensure that multipl subsequent (actually all) requests made with this client will contain the specified header. Saving you from having to add it to each and every request.
Provides some degree of future proofing (moving subdomain and api version into editable fields).
If you choose to log your request and response objects you can also do:
// You can use any PSR3 compliant logger in space of "null".
// Log the full request and response messages using echo() calls.
$client->getEmitter()->attach(new GuzzleHttp\Subscriber\Log\LogSubscriber(null, GuzzleHttp\Subscriber\Log\Formatter::DEBUG);
Your request will then simply become:
$json = '{"ticket": {"subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}';
$url = 'tickets/tickets.json';
$request = $client->createRequest('POST', $url, [
'body' => $json,
]);
$response = $client->send($request);
or
$json = '{"ticket": {"subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}';
$url = 'tickets/tickets.json';
$result = $client->post(, [
'body' => $json,
]);
Edit:
After futher reading Ref 4 more thouroughly it should be possible to do the following:
$url = 'tickets/tickets.json';
$client = new GuzzleHttp\Client([
'base_url' => ['https://{subdomain}.zendesk.com/api/{version}/', [
'subdomain' => '<some subdomain name>',
'version' => 'v2',
],
'defaults' => [
'auth' => [ $username, $password],
],
'debug' => true, // only for debugging purposes
]);
$result = $client->post($url, [
'json' => $json, // Any PHP type that can be operated on by PHP’s json_encode() function.
]);
You shouldn't be using the query parameter, as you need to send the raw json as the body of the request (Not in parameters like you are doing.) Check here for information on how to accomplish this. Also, be sure to try to enable debugging to figure out why a request isn't posting like you want. (You can compare both curl and guzzles debug output to verify they match).