Create a image share for linkedin api v2 by php - php

I write a code which share a post on linkedin account. My code is working fine for text post but facing issue in image post. I tried and search a lot but not find any success for now. Here is my code for image share in linkedin V2 api.
I follow this doc
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context
/*1.Register your image to be uploaded.*/
$imageData = array (
'registerUploadRequest' =>
array (
'recipes' =>
array (
0 => 'urn:li:digitalmediaRecipe:feedshare-image',
),
'owner' => 'urn:li:person:'.$data['identifier'],
'serviceRelationships' =>
array (
0 =>
array (
'relationshipType' => 'OWNER',
'identifier' => 'urn:li:userGeneratedContent',
),
),
),
);
$headers = [
'Content-Type' => 'application/json',
'x-li-format' => 'json',
'X-Restli-Protocol-Version' => '2.0.0',
];
$image_request = $adapter->apiRequest('assets?action=registerUpload', 'POST', $imagedata, $headers);
$image_request = json_decode(json_encode($image_request), True);
/*2.Upload your image to LinkedIn.*/
$media = $image_request['value']['asset'];
$image_path = '/var/www/domain.com/img/laptop-green-bg.jpg';
$postfield = array("upload-file" => $image_path );
$headers = array();
$headers[] = 'Authorization: Bearer '.$tokens['access_token'];// token generated above code
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$headers[] = 'Content-Type: data/binary';
$headers[] = 'Content-Length: 0';
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $image_request['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_SAFE_UPLOAD => false,
CURLOPT_POSTFIELDS => $postfield
);
curl_setopt_array($ch, $options);
$imgResponse = curl_exec($ch);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$assets = explode(":", $media);
$assetRequest = $adapter->apiRequest('assets/'.$assets[3], 'GET');
/*3. Create the image share.*/
$status = $this->imagePostArray($data, $media);
function imagePostArray($data, $media) {
$newData = array (
'author' => 'urn:li:person:'.$data['identifier'],
'lifecycleState' => 'PUBLISHED',
'specificContent' =>
array (
'com.linkedin.ugc.ShareContent' =>
array (
'shareCommentary' =>
array (
'text' => $data['introtext'],
),
'shareMediaCategory' => 'IMAGE',
'media' =>
array (
0 =>
array (
'status' => 'READY',
'description' =>
array (
'text' => $data['introtext'],
),
'media' => $media,
'title' =>
array (
'text' => $data['introtext'],
),
),
),
),
),
'visibility' =>
array (
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
),
);
return $newData;
}
$response = $adapter->apiRequest('ugcPosts', 'POST', $status, $headers);
print_r($response);
/*responsestdClass Object
(
[id] => urn:li:share:XX4665961029465XXXX
)*/
print_r($imgResponse);
/*HTTP/1.1 201 Created
Date: Tue Jun 18 08:15:02 UTC 2019
Server: Play
Set-Cookie: lang=v=2&lang=en-us; Path=/; Domain=api.linkedin.com
x-ambry-creation-time: Tue Jun 18 08:15:02 UTC 2019
access-control-allow-origin: https://www.linkedin.com
Content-Length: 0
X-Li-Fabric: prod-lor1
Connection: keep-alive
X-Li-Pop: prod-esv5
X-LI-Proto: http/1.1
X-LI-UUID: z1rSbeU8qRUA8kkBZSsXXX==
Set-Cookie: lidc="b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"
X-LI-Route-Key: "b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"*/
But still cannot see my post in linkedin. Please help to debug or provide some solution.

I've solved posting using Guzzle library of php. It's simple and straight forward.
First we need to upload the image using following code:
$linkedInClient = new GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);
$response = $linkedInClient->post(
'/media/upload', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer {accessToken}',
],
'multipart' => [
[
'name' => 'fileupload',
'contents' => fopen('image-path', 'r'),
],
],
]
);
After that we need to decode the json response the uploaded image to use in the post request as follow:
$contents = json_decode($response->getBody()->getContents());
Now, prepare the data for linkedin post:
$data = array (
'author' => 'author-id',
'lifecycleState' => 'PUBLISHED',
'specificContent' =>
array (
'com.linkedin.ugc.ShareContent' =>
array (
'media' =>
array (
0 =>
array (
'media' => $contents->location,
'status' => 'READY'
),
),
'shareCommentary' =>
array (
'attributes' => [],
'text' => 'Some Comments',
),
'shareMediaCategory' => 'IMAGE',
),
),
'visibility' =>
array (
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
),
);
Next, we can use this data to post in linkedin as below:
$linkedInClient->post("/ugcPosts", $data);
I hope this helps. We can see the post in the linkedin. However, in my case the post will be visible but the image only gets displayed after some time of upload. But you can see the image on popup after clicking the blank image block.
Thanks.

Work For Me
$curl = curl_init(); //CURL version: 7.29, PHP version: 7.4.26
$imageData = array (
'registerUploadRequest' =>
array (
'recipes' =>
array (
0 => 'urn:li:digitalmediaRecipe:feedshare-image',
),
'owner' => 'urn:li:person:'.$linkedin_id,
'serviceRelationships' =>
array (
0 =>
array (
'relationshipType' => 'OWNER',
'identifier' => 'urn:li:userGeneratedContent',
),
),
),
);
$image_request = json_encode($imageData);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.linkedin.com/v2/assets?action=registerUpload',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_TIMEOUT => 300,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $image_request,
CURLOPT_HTTPHEADER => array('content-type: application/json', "Accept: application/json",
"Authorization: Bearer ".$access_token)
));
$response = json_decode(curl_exec($curl),true);
echo "<pre>";
print_r($response);

Related

Passing params to an API in the body of a request using Curl

Im posting data from a form to a 2 diferents APIS. The first one its working well but this one its does not.
This is what im sending, theres a conection to the API but the parameters are not arriving, support says i have to send the data in the body of the request but im not sure how to do it.
$chThree= curl_init();
// values API 3
$dataApiThree = array(
'cid' => '199',
'uid' => $_POST['uid'],
'f_3_firstname' => $_POST['firstname'],
'f_4_lastname' => $_POST['lastname'],
'f_1_email' => $_POST['email'],
'f_11_postcode' => $_POST['meta_Zip'],
'f_12_phone1' => $_POST['mobile_phone'],
'f_135_nombre_empresa' => $_POST['meta_empresa'],
'f_134_cantidad_vehiculos' => $_POST['meta_cantidadVehiculos'],
'f_133_tipo_servicio ' => $_POST['meta_Gestion']
);
$optsThree = array(
CURLOPT_URL => 'https://leadtowin.databowl.com/api/v1/lead',
CURLOPT_HTTPHEADER => 'Content-Type: application/x-www-form-urlencoded',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $dataApiThree,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_REFERER => $_SERVER['HTTP_REFERER']
);
//end API 3
//curl API3
curl_setopt_array($chThree, $optsThree);
$responseThree = curl_exec($chThree);
$responseThree = json_decode($responseThree);
curl_close($chThree);
I have find the answer, this was the code who works.
<?php
$post_array = array(
"cid" => "199",
"sid" => "2",
"uid" => $_POST['uid'],
"optin_email" => $_POST['optin_email'],
"optin_email_timestamp" => $_POST['optin_email_timestamp'],
"optin_phone" => $_POST['optin_phone'],
"optin_phone_timestamp" => $_POST['optin_phone_timestamp'],
"optin_sms" => $_POST['optin_sms'],
"optin_sms_timestamp" => $_POST['optin_sms_timestamp'],
"optin_postal" => $_POST['optin_postal'],
"optin_postal_timestamp" => $_POST['optin_postal_timestamp'],
"f_1_email" => $_POST['f_1_email'],
"f_3_firstname" => $_POST['f_3_firstname'],
"f_4_lastname" => $_POST['f_4_lastname'],
"f_11_postcode" => $_POST['f_11_postcode'],
"f_12_phone1" => $_POST['f_12_phone1'],
"f_135_nombre_empresa" => $_POST['f_135_nombre_empresa'],
"f_134_cantidad_vehiculos" => $_POST['f_134_cantidad_vehiculos'],
"f_133_tipo_servicio" => $_POST['f_133_tipo_servicio']
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://leadtowin.databowl.com/api/v1/lead",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($post_array),
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"Accept-Encoding: UTF-8",
"Content-Type: application/x-www-form-urlencoded",
"Cookie: PHPSESSID=d053646c7953d9116849a8aa4717ab81"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>

PHP Post Request (CURL, JSON) not Working

I come humbly before great developers with this issue of mine. Sending a post request in JSON format to Firebase. Here's my code
$token = $_SESSION['token'];
$data = array(
'id' => 156,
'quizName' => $quizName,
'numberOfQuestions' => $numberOfQuestions,
'isTimed' => true,
'numberOfMinutesToComplete' => $numberOfMinutesToComplete,
'targetedClass' => 'Js One',
'subject' => $subject_name,
'schoolLevel' => $schoolLevel,
'questions' => array('question' => $question, 'questionMark' => $marks,
'options' => array('option' => 'A', 'answer'=> $optionA, 'option' => 'B', 'answer'=> $optionB, 'option' => 'C', 'answer' => $optionC, 'option' => 'D', 'answer' => $optionD, 'option' => 'E', 'answer' => $optionE),
'hasImage' => true,
'images' => array('images-1' => 'image-1', 'images-2' => 'image-2'),
'correctionOption' => $correct_option
),
'totalValidMarks' => $totalValidMarks,
'validUntil' => $validUntil
);
// API URL
$url = ' ';
// Create a new cURL resource
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('x-access-token:'.$token, 'Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result.</pre>";
But I'm receiving an error:
"details":[{"message":"\"id\" is required","path":["id"],"type":"any.required","context":{"label":"id","key":"id"}}]}
Please try sending like this:
$params = $myDataArray;
$data_string = json_encode($params);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $toEndPoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => array(
"x-access-token: $token",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
exit;
#godlovesme, to answer for your latest comment:
I don't really like using While loops as they can easily let you fall in an endless loop, but you get what you ask for:
$i = 0;
$questionsArrFormatted = [];
while ($i < count($questionsArr)) {
$hasImage = count($questionsArr[$i]['question']) ? true : false;
$questionsArrFormatted[$i] = [
'question' => $questionsArr[$i]['question'],
'questionMark' => $questionsArr[$i]['marks'],
'options' => $questionsArr[$i]['options'], // options should be an array formatted like in your question
'hasImage' => $hasImage,
'images' => $questionsArr[$i]['images'],
'correctionOption' => $questionsArr[$i]['correct_answer']
];
$i++;
}
$data = array(
'id' => 156,
'quizName' => $quizName,
'numberOfQuestions' => $numberOfQuestions,
'isTimed' => true,
'numberOfMinutesToComplete' => $numberOfMinutesToComplete,
'targetedClass' => 'Js One',
'subject' => $subject_name,
'schoolLevel' => $schoolLevel,
'questions' => $questionsArrFormatted,
'totalValidMarks' => $totalValidMarks,
'validUntil' => $validUntil
);

HTTP 400 error when trying to do a PayPal payment request. (file_get_contents)

Trying to make a test cURL-less Paypal payment request but getting an error.
I am using the Sample request from the paypal Payment API docs.
$data = array (
0 =>
array (
'op' => 'replace',
'path' => '/transactions/0/amount',
'value' =>
array (
'total' => '18.37',
'currency' => 'EUR',
'details' =>
array (
'subtotal' => '13.37',
'shipping' => '5.00',
),
),
),
1 =>
array (
'op' => 'add',
'path' => '/transactions/0/item_list/shipping_address',
'value' =>
array (
'recipient_name' => 'Anna Gruneberg',
'line1' => 'Kathwarinenhof 1',
'city' => 'Flensburg',
'postal_code' => '24939',
'country_code' => 'DE',
),
),
);
$url = 'https://api.sandbox.paypal.com/v1/payments/payment';
$options = array(
'http' => array(
'header' => array(
"Content-type: application/json",
"Authorization: Bearer $access_token"
),
'method' => 'POST',
'content' => http_build_query($data)
)
);
print_r($options);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
Return: Warning: file_get_contents(https://api.sandbox.paypal.com/v1/payments/payment): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /storage/ssd5/910/7954910/public_html/paypal.php on line 48
bool(false)
Add
'protocol_version' => '1.1'
to the 'http' => array().
e.g. Change the line
'method' => 'POST',
to
'protocol_version' => '1.1',
'method' => 'POST',
This changes the HTTP protocol used by file_get_contents() from HTTP/1.0 to HTTP/1.1, and HTTP/1.1 is required by the PayPal REST API server.

Rates not returning while creating a shipment using shippo

I am integrating shippo API so far it is working great but there is this problem that when I send the request to create shipment shipment is creating but there is nothing in the rate array but when I send the same request through postman I am getting those rates here is the request that I am sending.
// Receiver Information for making shipment.
$r_name = $result[0]->r_name;
$r_email = $result[0]->r_email;
$r_street = $result[0]->r_street;
$r_city = $result[0]->r_city;
$r_country = $result[0]->r_country;
$r_zip = $result[0]->r_zip;
$r_state = $result[0]->r_state;
// Sender Information for making Shipment.
$s_name = $result[0]->s_name;
$s_email = $result[0]->s_email;
$s_street = $result[0]->s_street;
$s_city = $result[0]->s_city;
$s_country = $result[0]->s_country;
$s_zip = $result[0]->s_zip;
$s_state = $result[0]->s_state;
// Parcel Information for making Shipment.
$p_qty = $result[0]->p_qty;
$p_name = $result[0]->p_name;
$p_price = $result[0]->p_price;
$p_weight = $result[0]->p_weight;
$p_unit = $result[0]->p_unit;
$shipment_array = array(
'address_to' => array(
'name' => $r_name,
'street1' => $r_street,
'city' => $r_city,
'state' => $r_state,
'zip' => $r_zip,
'country' => $r_country,
'phone' => '03212669686',
'email' => $r_email
),
'address_from' => array(
'name' => $s_name,
'street1' => $s_street,
'city' => $s_city,
'state' => $s_state,
'zip' => $s_zip,
'country' => $s_country,
'phone' => '03227577798',
'email' => $s_email
),
'parcels' => array(
array(
"length" => "10",
"width" => "15",
"height" => "10",
"distance_unit" => "in",
"weight" => $p_weight,
"mass_unit" => $p_unit
)
),
'async' => false
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.goshippo.com/shipments/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($shipment_array),
CURLOPT_HTTPHEADER => array(
"Authorization: ShippoToken shippo_test_742eabd1c83ece80052fbce9ee71163181eaee72",
"Cache-Control: no-cache",
"Content-Type: application/json",
"Postman-Token: 906233f7-ac66-3951-f96a-4f0f88c8d419"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Can anyone help me finding out what am I doing wrong here.

posting into WordPress with WP API "code issue"

I am trying to post into a WordPress site using the WP API. I have the code below but it does not seem to be working, am not getting any post in my site.
<?php
$options = array (
'http' =>
array (
'ignore_errors' => true,
'method' => 'POST',
'header' =>
array (
'Authorization' => 'Basic ' . base64_encode( 'user' . ':' . 'pass' ),
),
'content' =>
http_build_query( array (
'title' => 'Hello World',
'content' => 'Hello. I am a test post. I was created by the API',
'tags' => 'tests',
'categories' => 'API',
)),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'http://freeglobaljob.com/wp-json/posts/',
false,
$context
);
$response = json_decode( $response );
?>

Categories