LinkedIn Share API 'ugcPosts' response 504 gateway timeout from PHP(Wordpress) - php

I'm using wordpress to shared my post into linkedIn. For this i'm using https://api.linkedin.com/v2/ugcPosts API. But this API response return 504 gateway timeout.
In previous step when i called another API to get access token, its easily got the access token. But when I wanted to create a share using ucPosts POST api request it providing gateway time out.
My requested code here.
Please any one help me.
Tried from localhost apache server(PHP, wordpress)
$params = '{
"author" : "urn:li:person:'.$linkedInAppCredentials->get_user_URN().'",
"lifecycleState" : "PUBLISHED",
"specificContent" : {
"com.linkedin.ugc.ShareContent" : {
"shareCommentary" : {
"text" : "'.$message.'"
},
"shareMediaCategory" : "NONE"
}},
"visibility" :"PUBLIC"
}';
$headers = '{
"Content-Type": "application/json",
"X-Restli-Protocol-Version": "2.0.0",
"x-li-format": "json",
"Connection": "Keep-Alive",
"Authorization": "Bearer '.$linkedInAppCredentials->getAccessToken().'"
}';
$requestedUrl = "https://api.linkedin.com/v2/ugcPosts?oauth2_access_token=".$this->getAccessToken();
$requestBody = array(
'headers' => $header,
'timeout' => 3600,
'body' => $params
);
$result = wp_remote_post($requestedUrl, $requestBody);
Response:
[body] => {"message":"Request timed out","status":504}
[response] => Array
(
[code] => 504
[message] => Gateway Timeout
)

Request timeout may be happening because LinkedIn is not able to parse the request body. So it might be a good idea to convert the requestBody to a JSON string. Giving a proper JSON input worked for me I was having the same problem.
As was happening with another person:
https://stackoverflow.com/a/56786205/12578136

Related

How to authorize API endpoint through header using wp_remote_get()?

I am testing API Football on my WP site and facing a difficulty in authentication. I have tested endpoint on postman and everything works fine but as soon as I test it on WP it gives me following response with error:
{ "get": "status", "parameters": [], "errors": { "token": "Error/Missing application key. Go to https://www.api-football.com/documentation-v3 to learn how to get your API application key." }, "results": 0, "paging": { "current": 1, "total": 1 }, "response": [] }
My WP code is:
$response = wp_remote_get( 'https://v3.football.api-sports.io/status', array(
'headers' => array(
'x-apisports-key' => $this->api_key
)
) );
$response_body = wp_remote_retrieve_body( $response );
return json_decode( $response_body );
I have tried php curl too but still getting same problem. For some reason I don't want to try it on rapidapi.
I have tried php cURL too but still getting same error. For some reasons I don't want to use rapidapi.

Validate GET status of a url for mailchimp

I have created a function that creates a batch webhook in mailchimp so that a callback will be submitted once the batch operations is finished. like following:
// register mailchimp batch webhook
$responseWH = wp_remote_post( 'https://' . substr($mcApi,strpos($mcApi,'-')+1) . '.api.mailchimp.com/3.0/batch-webhooks' ,array(
'headers' => array(
'method' => 'POST',
'Authorization' => 'Basic ' . base64_encode( 'user:'. $mcApi )
),
'body' => json_encode(array(
'url' => 'http://90660d72b8be.ngrok.io/wp-json/lubuvna/v2/batch/2810471250791421617231098394447326550803'
))
));
above code means, when a batch operation is finished MC should call this url:
http://90660d72b8be.ngrok.io/wp-json/lubuvna/v2/batch/2810471250791421617231098394447326550803
If this url is called, then a script will run and notify me that the operation is done und update the the post in wordpress.
but since the header status code is 404, mailchimp is not adding the url to the batch webhook.. instead i get following error:
{
"type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title": "Invalid Resource",
"status": 400,
"detail": "The resource submitted could not be validated. For field-specific details, see the 'errors' array.",
"instance": "05a4430f-c68f-46a5-82af-3b95332d6fe83",
"errors": [
{
"field": "url",
"message": "We couldn't verify the URL is working. Please double check and try again. HTTP Code: 500"
}
]
}
How can i return a 200 status in the header when Mailchimp is trying to make a GET request to the specified URL, while adding the batch webhook? they need a valid url. mailchimp batch webhook
I am using ngrok for connection within localhost which works when i add a URL like http://90660d72b8be.ngrok.io/wp-content/plugins/my-plugin/inc/batch/import.php, because the file actually exist in the plugin directory
but when adding the URL http://90660d72b8be.ngrok.io/wp-json/lubuvna/v2/batch/2810471250791421617231098394447326550803
I can see that mailchimp makes a get request and the code status is 404 like in the screenshot
I hav ended up using follwoing:
function myplugin_registered_rest_routes() {
// batch operation finished
register_rest_route('myplugin/v2', '/batch/(?P<id>\d+)',
array(
array('methods' => ['POST', 'GET'],
'callback' => 'my_awesome_func'
)
)
);
}
add_action( 'rest_api_init', 'myplugin_registered_rest_routes' );
another option of array like #04FS answer:
register_rest_route('myplugin/v2', '/batch/(?P<id>\d+)',
array(
array('methods' => 'GET',
'callback' => 'my_awesome_func',
),
array('methods' => 'POST',
'callback' => 'my_awesome_func'
)
)
);
Another option parsing the url request. Not common when using wordpress API:
add_action('parse_request', 'register_endpoint', 0);
function register_endpoint() {
global $wp;
if ($wp->request == 'wp-json/myplugin/v2/batch/2810471250791421617231098394447326550803') {
header("HTTP/1.1 200 OK");
exit;
}
}

MS Graph authentication issue

My company has a WordPress-based intranet and we use Office365. I am hoping to hook into the graph as a global application (without explicit user consent) to grab data. I've gotten all of it working, but am having trouble with the /users/user_name/calendarview endpoint.
I can get valid access tokens using the following:
$auth_request_body = http_build_query( array(
'grant_type' => 'client_credentials',
'client_id' => CLIENT_ID,
'client_secret' => SECRET_KEY,
'resource' => 'https://graph.microsoft.com/'
) );
$response = wp_remote_post( $url, array(
'body' => $auth_request_body
) );
$body = json_decode( wp_remote_retrieve_body( $response ) );
$token_type = $body->token_type;
$access_token = $body->access_token;
and can make several successful calls, for example to the https://graph.microsoft.com/v1/users/user_name endpoint or to the https://graph.microsoft.com/v1/groups/group_id endpoint, however when attempting to reach the https://graph.microsoft.com/v1/users/user_id/calendarview endpoint I get the following response:
[body] => {
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again.",
"innerError": {
"request-id": request_id,
"date": "2018-08-08T21:57:50"
}
}
}
[response] => Array
(
[code] => 403
[message] => Forbidden
)
I am working on my local environment, and for testing purposes I have granted all application / delegated permissions to my local machine (I think .. I'm still not positive how to ensure that newly grated permissions take effect on my local machine).
Any thoughts here?
... Nevermind.
Apparently my newly delegated permissions simply hadn't taken effect yet. This method above DOES work for my scenario.
I think you should confirm whether to grant the appropriate permissions to the application.

Why Share on LinkedIn API return 400 Bad Request?

I'm trying to post a LinkedIn share update via its Share on LinkedIn API using a PHP library LinkedIn-Client API. I've successfully authorized the user and I got the access token returned from it. I use the token along with this share API call. Here is my code:
$linkedInOAuth = new Happyr\LinkedIn\LinkedIn(LINKEDIN_APP_ID, LINKEDIN_APP_SECRET);
if ($accessToken) { // assume that it is retrieved from session
$linkedInOAuth->setAccessToken($accessToken);
$postParams = array(
"content" => array(
'description' => "I'm so exciting to share a post using API."
),
"visibility" => array(
"code" => "connnections-only"
)
);
$result = $linkedInOAuth->api(
"v1/people/~/shares",
array("format" => "json"),
"POST",
$postParams
);
}
However I got 400 bad request error returned from this API call.
Fatal error: Uncaught GuzzleException: 400: Client error response [url] https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=xxxxxxx [status code] 400 [reason phrase] Bad Request thrown in ...\vendor\happyr\linkedin-api-client\src\Happyr\LinkedIn\Http\GuzzleRequest.php on line 26
What could be the problem?
[UPDATE on 2015-04-30 3:00 PM UTC]
LinkedIn-Client API uses Guzzle internally for HTTP requests. I tried to use GuzzleHttp directly without using Happyr\LinkedIn\LinkedIn->api(), but same error and no success.
if ($accessToken) {
$url = 'https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=' . $accessToken;
$client = new GuzzleHttp\Client();
$response = $client->post($url, array(
'headers' => array(
'Content-Type' => 'application/json',
'x-li-format' => 'json'
),
'json' => array(
'comment' => 'Check out developer.linkedin.com!',
'content' => array(
'description' => 'I\'m so exciting to share a post using API.'
),
'visibility' => array(
'code' => 'connections-only'
)
)
));
}
Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException'
with message 'Client error response [url]
https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=xxxxx
[status code] 400 [reason phrase] Bad Request' in
\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:89 Stack
trace: #0 \vendor\guzzlehttp\guzzle\src\Subscriber\HttpError.php(33):
GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Message\Request),
Object(GuzzleHttp\Message\Response)) #1
\vendor\guzzlehttp\guzzle\src\Event\Emitter.php(109):
GuzzleHttp\Subscriber\HttpError->onComplete(Object(GuzzleHttp\Event\CompleteEvent),
'complete') #2 \vendor\guzzlehttp\guzzle\src\RequestFsm.php(91):
GuzzleHttp\Event\Emitter->emit('complete', Object(Guz in
\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line
89
[UPDATE on 2015-05-05 9:40 AM UTC]
I copied and used both xml and json examples of Share on LinkedIn API page. This time, the error changed to Internal Server Error.
if ($accessToken) {
$format = 'xml';
$url = 'https://api.linkedin.com/v1/people/~/shares?format='.$format.'&oauth2_access_token=' . $connect->accessToken;
$postParams = array(
"xml" => "
<share>
<comment>Check out developer.linkedin.com!</comment>
<content>
<title>LinkedIn Developer Resources</title>
<description>Leverage LinkedIn's APIs to maximize engagement</description>
<submitted-url>https://developer.linkedin.com</submitted-url>
<submitted-image-url>https://example.com/logo.png</submitted-image-url>
</content>
<visibility>
<code>anyone</code>
</visibility>
</share>",
"json" => array(
"comment" => "Check out developer.linkedin.com!",
"content" => array(
"title" => "LinkedIn Developers Resources",
"description" => "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url" => "https://developer.linkedin.com",
"submitted-image-url" => "https://example.com/logo.png"
),
"visibility" => array(
"code" => "anyone"
)
)
);
$client = new GuzzleHttp\Client();
if ($format === 'xml') {
$response = $client->post($url, array(
'body' => $postParams['xml']
));
} else {
$response = $client->post($url, array(
'headers' => array(
'Content-Type' => 'application/json',
'x-li-format' => 'json'
),
'json' => $postParams['json']
));
}
}
Fatal error: Uncaught exception 'GuzzleHttp\Exception\ServerException'
with message 'Server error response [url]
https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=xxxx
[status code] 500 [reason phrase] Internal Server Error'
According to the Github issue of Happyr\LinkedIn-API-client, some updates have been made in 0.5.0 and it solved my problem. However, LinkedIn has unclear documentation about its Share API. The following information have to be noted:
The comment field is the sharing update content. The name comment leads confusing.
Using the field comment, URL is optional in the sharing update content.
The content field means snapshot about the content of the URL you are sharing. To describe more clearly, it reflects open graph meta tags;
content.title overrides <meta property="og:title" content="..." />
content.description overrides <meta property="description" content="..." />
content.title overrides <meta property="og:title" content="..." />
content.submitted-url overrides <meta property="og:url" content="..." />
content.submitted-image-url overrides <meta property="og:image" content="..." />
When the content field is used, the field submitted-url is required. The rest are optional. If it is missing, 400 Bad Request would return.
The URLs included in the example codes of LinkedIn Share API would cause 500 Internal Server Error. They should not be used for testing purpose.
The following is the correct usage of API using Happyr\LinkedIn-API-client.
(1) Happyr\LinkedIn - Using the field comment
$linkedInOAuth = new Happyr\LinkedIn\LinkedIn(LINKEDIN_APP_ID, LINKEDIN_APP_SECRET);
// retrieve $accessToken from db or session
$linkedInOAuth->setAccessToken($accessToken);
$postParams = array(
'json' => array(
"comment" => "PHPLucidFrame - The simple, lightweight and flexible web application development framework http://phplucidframe.sithukyaw.com",
"visibility" => array(
"code" => "anyone"
)
)
);
$result = $linkedInOAuth->post('v1/people/~/shares', $postParams);
(2) Happyr\LinkedIn - Using the field content
$linkedInOAuth = new Happyr\LinkedIn\LinkedIn(LINKEDIN_APP_ID, LINKEDIN_APP_SECRET);
// retrieve $accessToken from db or session
$linkedInOAuth->setAccessToken($accessToken);
$postParams = array(
'json' => array(
"content" => array(
"title" => "PHPLucidFrame",
"description" => "The simple, lightweight and flexible web application development framework",
"submitted-url" => "http://phplucidframe.sithukyaw.com"
),
"visibility" => array(
"code" => "anyone"
)
)
);
$result = $linkedInOAuth->post('v1/people/~/shares', $postParams);
The following is the correct usage of API using GuzzleHttp.
(3) GuzzleHttp - Using the field comment
// retrieve $accessToken from db or session
$url = 'https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=' . $accessToken;
$client = new GuzzleHttp\Client();
$response = $client->post($url, array(
"json" => array(
"comment" => "PHPLucidFrame - The simple, lightweight and flexible web application development framework http://phplucidframe.sithukyaw.com",
"visibility" => array(
"code" => "anyone"
)
)
));
(4) GuzzleHttp - Using the field content
// retrieve $accessToken from db or session
$url = 'https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token=' . $accessToken;
$client = new GuzzleHttp\Client();
$response = $client->post($url, array(
"json" => array(
"content" => array(
"title" => "PHPLucidFrame",
"description" => "The simple, lightweight and flexible web application development framework",
"submitted-url" => "http://phplucidframe.sithukyaw.com"
),
"visibility" => array(
"code" => "anyone"
)
)
));
The fields comment and content can also be used together.
Just a quick guess here but you might need to add json_encode to your $postParams before you send it to the API.
$result = $linkedInOAuth->api(
"v1/people/~/shares",
array("format" => "json"),
"POST",
json_encode($postParams),
);
ALTERNATIVELY
If that does not work I also notice the Linkedin Docs say the following. You could try adding these two headers (if you havent already).
By default, all API calls expect input in XML format, however if it is more covienent for your application to submit data in JSON format, you can inform the APIs that they will be receiving a JSON-formatted payload by including the following two HTTP header values in the call:
Content-Type: application/json
x-li-format: json
Your JSON post body needs to be corrected. Check:
https://developer.linkedin.com/docs/share-on-linkedin
You need to follow either one of these formats.
Share via a comment containing a URL
{
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
}
Share with specific values
{
"comment": "Check out developer.linkedin.com!",
"content": {
"title": "LinkedIn Developers Resources",
"description": "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url": "https://developer.linkedin.com",
"submitted-image-url": "https://example.com/logo.png"
},
"visibility": {
"code": "anyone"
}
}

Facebook PHP Graph API not returning complete data

I'm having an issue with Facebook's PHP SDK version 4.0.
I'm simply trying to retrieve the insights/page_fans_city metric via the Graph API:
$request = new FacebookRequest($session, 'GET',
'/{my object}/insights/page_fans_city',
array('period' => 'lifetime'));
$response = $request->execute();
$client_graph_object = $response->getGraphObject();
print_r($client_graph_object);
However, no data is returned:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[data] => Array
(
)
[paging] => stdClass Object
(
[previous] => https://graph.facebook.com/v2.0/...
[next] => https://graph.facebook.com/v2.0/...
)
)
)
I know that I have the Insights data that I'm requesting. I can make the exact same request via the Graph Explorer:
→ /v.2.0/{my object}/insights/page_fans_city?period=lifetime
{
"data": [
{
"id": "{my object}/insights/page_fans_city/lifetime",
"name": "page_fans_city",
"period": "lifetime",
"values": [
{
"value": {
...
},
"end_time": "2014-08-01T07:00:00+0000"
},
{
"value": {
...
},
"end_time": "2014-08-02T07:00:00+0000"
}
],
"title": "Lifetime Likes by City",
"description": "Lifetime: Aggregated Facebook location data, sorted by city, about the people who like your Page. (Unique Users)"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.0/...,
"next": "https://graph.facebook.com/v2.0/...
}
}
I should note that I am receiving data if I omit the page_fans_city segment. When it's omitted- I can view data for page_fans_country only. Therefore
$request = new FacebookRequest($session, 'GET',
'/{myobject}/insights/page_fans_country',
array('period' => 'lifetime'));
and
$request = new FacebookRequest($session, 'GET',
'/{myobject}/insights',
array('period' => 'lifetime'));
will work for me ...
I suspect it's my Access token- but I'm not sure why that would be the case. The app that I created only requires the read_insights permission.
Any thoughts or suggestions?
Thanks in advance,Mike
It was a permissions issue. If you ever see:
{
"data": [
],
...
}
It's likely your access token does not have sufficient privileges to access the data you're requesting (that or there's simply no data).
My problem was that even though I was the Developer of the app and it was approved by Facebook (with the manage_pages and read_insights permissions)- I could not use an app access token to retrieve the insights data.
I needed a user access token!
I easily generated the user access token by manually creating a login flow per Facebook's documentation. This stackoverflow thread was useful, too.
More info on Facebook tokens here.
Hope this helps anyone who stumbles across this thread!
-Mike

Categories