Create an Image Share over LinkedIn API V2 not working - linkedin

I use the api version 2.0 and want to create an image share.
LinkedIn describes your image binary file upload process here:
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context#create-a-text-share
If you follow the instructions you will get a 400 HTTP error.
I add the Content-Type in the header and get a 201 HTTP status with the X-RestLi-Id in the header. So far so good!
If I want to show my created post on LinkedIn (https://www.linkedin.com/in/me/detail/recent-activity/) I can't find the post with image.
How to fix it? Anybody got an idea?
PHP code:
$imageRequestData = array(
"registerUploadRequest" => array(
"recipes" => array(
"urn:li:digitalmediaRecipe:feedshare-image"
),
"owner" => $urn, // Person URN === urn:li:person:XXXX
"serviceRelationships" => array(
array(
"relationshipType" => "OWNER",
"identifier" => "urn:li:userGeneratedContent"
)
)
)
);
$image_request = $this->post('v2/assets?action=registerUpload', $imageRequestData);
$headers = array();
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$headers[] = 'Content-Type: ' . mime_content_type($image_path); //ex. image/png
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $image_request['message']['value']['uploadMechanism']
['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POSTFIELDS => array("upload-file" => new CURLFile($image_path))
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$content = array(
'author' => $urn, // Person URN === urn:li:person:XXX
'lifecycleState' => 'PUBLISHED',
'specificContent' => array(
"com.linkedin.ugc.ShareContent" => array(
'shareCommentary' => array(
"text" => $comment,
),
'shareMediaCategory' => 'IMAGE',
// NONE - The share does not contain any media, only text.
// ARTICLE - The share contains a URL.
// IMAGE - The Share contains an image.
'media' => array(
"status" => "READY",
"media" => $image_request['message']['value']['asset']
)
)
),
"visibility" => array(
"com.linkedin.ugc.MemberNetworkVisibility" => "PUBLIC"
)
);
$postfields = json_encode($content);
$headers = array();
$headers[] = 'x-li-format: json';
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' . strlen($postfields);
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://api.linkedin.com/v2/ugcPosts',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POSTFIELDS => $postfields
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);

You need to change your request to PUT and keep default for SSL VerifyPeer:
$headers = array();
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$headers[] = 'Content-Type: multipart/form-data';
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'PUT', //need to set custom request to PUT instead of post
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $image_request['message']['value']['uploadMechanism']
['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
CURLOPT_HTTPHEADER => $headers,
// CURLOPT_SSL_VERIFYPEER => false, //keep default options
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_POSTFIELDS => array("upload-file" => new CURLFile($image_path))
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Or use GuzzleHttp\Client to simplify the upload:
$client =new \GuzzleHttp\Client();
$client->request('PUT',
$image_request['message']['value']['uploadMechanism'] // ↵
['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
[
'headers' => [
'Authorization' => 'Bearer ' . $this->accessToken
],
'body' => fopen($image_path, 'r'),
]

Related

COntact form 7 API Integration

<?php
// // accept all post data and make array
$data = json_decode(file_get_contents('php://input'), true);
// // get the data from the array
$deal_name = "test";
// $deal_source = isset($data['deal_source']) ? $data['deal_source'] : "";
$contact_first_name = isset($data['yrnamr']) ? $data['yrname'] : "";
// $contact_last_name = isset($data['contact_last_name']) ? $data['contact_last_name'] : "";
$contact_email = isset($data['yremail']) ? $data['yremail'] : "";
$contact_phone = isset($data['telephone']) ? $data['telephone'] : "";
$contact_message = isset($data['yrmessage']) ? $data['yrmessage'] : "";
$data_string = json_encode(array(
"custom_fields" => array(),
"email" => $contact_email,
"first_name" => $contact_first_name,
"last_name" => "WA",
"is_public" => true,
"phone" => $contact_phone
));
$api_key = "d7c85d208c924e489f36ae69e1550570";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://app.teamwave.com/api/crm/deals?api_key='.$api_key,
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 =>'{
"custom_fields": {
"27806": {
"$key": 27806,
"field_type": "select",
"key": "source",
"name": "Source",
"options": null,
"position": 1,
"value": "test"
}
},
"currency": 1876589,
"pipeline": 29270,
"stage": 155081,
"title": "Deal Name Dynamic Test 4"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
$deal_id = $response['id'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://app.teamwave.com/api/crm/deals/'.$deal_id.'/link-contact?api_key='.$api_key,
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 =>$data_string,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;`
I use this code to integrate my contactform7 fields with teamwave crm.The code creates a deal and links it with a contact in the CRM. but the data is not being sent on form submission.
I suspect something is wrong where the contact form 7 fields are dynamically fetched. I am not sure what is wrong...............

Remove content-length header from wp_remote_post

I am having big issues doing a POST request from wordpress backend.
This is the request I try to make. The AppsSCript is a doPost() endpoint echo-ing the request. It gives me a 400 error.
$body = array(
'firstName' => 'WhyWontYouWork'
);
$args = array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
//'httpversion' => '1.0',
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => $body
);
$request = wp_remote_post ($url, $args);
$response = wp_remote_retrieve_body( $request );
I found out with insomnia, that having a content-length header in the POST request is making Apps Script go crazy. If I remove it, all works.
Hope this helps,
$url = 'https://example.com/api/endpoint';
$args = array(
'method' => 'POST',
'timeout' => 30,
'headers' => array(
'Content-Type' => 'application/json',
),
'body' => json_encode( array( 'data' => 'value' ) ),
);
// Remove the Content-Length header
unset( $args['headers']['Content-Length'] );
// Or Change it
$args['headers']['Content-Length'] = 20166 // in decimal bytes
// Make the remote post request
$response = wp_remote_post( $url, $args );
// Check for errors
if ( is_wp_error( $response ) ) {
// Handle error
} else {
// Handle success
}

How to integrate custom api (cURL call) into WordPress child theme

How can I integrate third-party API to wordpress theme. Is there any pre-build wordpress function for cURL calls?
Here is code with the parameters:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => {{API_URL}},
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"host: {{API_HOST}}"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);

knpsnappy bundle symfony2 cannot add headers and footers on multiple pages

Below is my code to add headers and footers to generate pdf, I don't know here I'm doing it wrong.Please help!
$html = $this->renderView('CoreBundle:PdfGenerator:generate.html.twig', array(
'userId' => $userId,
));
$snappy = $this->get('knp_snappy.pdf');
$snappy->setOption('header-html', $this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/header.html'));
$snappy->setOption('footer-html', $this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/footer.html'));
//echo $request->getHost().$this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/header.html'); die();
echo $html; die();
return new Response(
$snappy->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
http://www.michaelperrin.fr/2016/02/17/generating-pdf-files-with-symfony/
Follow this, I got my stuff working
$header = $this->renderView('FamilyHealthDischargeSummaryBundle:ExportPdf:header.html.twig');
$body = $this->renderView('FamilyHealthDischargeSummaryBundle:ExportPdf:body.html.twig', $data);
$snappy = $this->get('knp_snappy.pdf');
$snappy->setOption('header-html', $header);
return new Response(
$snappy->getOutputFromHtml($body), 200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename=' . $file2 . '.pdf',
]
);
}

drupal email problem

Below is my contactus module,
am trying to send email, guess email not sending successfully,
is there any mistake in my snippet
<?php
function contactus_menu() {
$items['contactus/reachus'] = array(
'title' => 'Contact US',
'page callback' => 'contactus_description',
'access callback' => TRUE,
'expanded' => TRUE,
);
return $items;
}
function contactus_description(){
return drupal_get_form('contactus_form');
}
function contactus_form() {
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['fullname'] = array(
'#type' => 'textfield',
'#title' => t('Enter your full name'),
'#description' => t('Please enter your name here'),
'#required' => TRUE,
);
$form['emailid'] = array(
'#type' => 'textfield',
'#title' => t('Enter your Email-ID'),
'#description' => t('Please enter your Email-ID'),
'#required' => TRUE,
);
$form['message'] = array(
'#type' => 'textarea',
'#title' => t('Enter your message'),
'#default_value' => variable_get('Please enter your message', ''),
'#cols' => 60,
'#rows' => 5,
'#description' => t('Please write your mssage'),
);
$form['file_upload'] = array(
'#title' => t('Upload file'),
'#required' => TRUE,
'#type' => 'file',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Reach Me '),
);
return $form;
}
function contactus_form_submit($form_id, $form_values) {
$message = 'You have submitted the ' . $form_id . ' form which contains the following data:<pre>' . print_r($form_values,true) . '</pre>';
$fullname = $form_values['values']['fullname'];
$emailid = $form_values['values']['emailid'];
$email_flag = valid_email_address($emailid);
$message = $form_values['values']['message'];
$message = $fullname . "\n" .$emailid. "\n" .$message;
$validators = array();
$dest = 'file';
$file = file_save_upload('file_upload', $validators, $dest);
//$file will be 0 if the upload doesn't exist, or the $dest directory
//isn't writable
if ($file != 0) {
$dest_path = 'contactus';
$result = file_copy($file, $dest_path, FILE_EXISTS_RENAME);
if ($result == 1) {
//Success, $file object will contain a different (renamed)
//filename and filepath if the destination existed
$file_msg = "successfully uploaded\n";
}
else {
//Failure
$file_msg = "failed uploaded\n";
}
}
else {
form_set_error('myform', t("Failed to save the file."));
}
$message = $fullname."\n".$emailid." ---$email_flag ----\n".$message."\n".$file_msg;
$to = 'bharanikumariyerphp#gmail.com';
$from = 'bharanikumariyerphp#gmail.com';
$subject = st('New Drupal site created!');
drupal_mail('university-profile', $to, $subject, $message, $from);
}
?>
You're calling drupal_mail with the wrong parameters. The correct way to send mail in Drupal requires you to implement the hook_mail hook where, based on a key and some parameters sent by drupal_mail you return the title and the subject of the email.
Take a look here for a simple example: http://api.lullabot.com/drupal_mail
If, however, you want to skip drupal_mail you can use this:
<?php
$message = array(
'to' => 'example#mailinator.com',
'subject' => t('Example subject'),
'body' => t('Example body'),
'headers' => array('From' => 'example#mailinator.com'),
);
drupal_mail_send($message);
Make sure you pass all text through t() since drupal_mail_send doesn't take care of localisation.

Resources