I need to convert doc file in pdf format
for that I am following saaspose functions mentioned below
(http://api.saaspose.com/v1.0/words/help)
I am not getting an error and a garbage file is uploaded along with doc file but I need to upload pdf file with same doc contents.
private function convertDocToPdf($inputFileName,$outputFileName)
{
$doc = new WordDocument("");//Word document is a class to create new document
$result = $doc->ConvertLocalFile($inputFileName, $outputFileName,"pdf");
}
private function ConvertLocalFile($input_path, $output_path, $output_format) {
try {
$str_uri = "http://api.saaspose.com/v1.0/words/convert?format=" + $output_format;
$signed_uri = Sign($str_uri);
$responseStream = uploadFileBinary($signed_uri, $input_path, "xml");
$v_output = ValidateOutput($responseStream);
if ($v_output === "") {
if ($output_format == "html")
$save_format = "zip";
else
$save_format = $output_format;
saveFile($responseStream,$outputFilename);
return "";
}
else
return $v_output;
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
public static function saveFile($input, $fileName){
$fh = fopen($fileName, 'w') or die("can't open file");
fwrite($fh, $input);
fclose($fh);
}
public static function Sign($UrlToSign) {
// parse the url
$url = parse_url($UrlToSign);
if (isset($url['query']) == "")
$urlPartToSign = $url['path'] . "?appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa;
else
$urlPartToSign = $url['path'] . "?" . str_replace(" ","%20",$url["query"]) . "&appSID=" . SaasposeApp::$AppSID;
// Decode the private key into its binary format
$decodedKey = self::decodeBase64UrlSafe(87c027855aebf72e204b3bcd710de1c0);
// Create a signature using the private key and the URL-encoded
// string using HMAC SHA1. This signature will be binary.
$signature = hash_hmac("sha1", $urlPartToSign, $decodedKey, true);
$encodedSignature = self::encodeBase64UrlSafe($signature);
if (isset($url['query']) == "")
return $url["scheme"] . "://" . $url["host"] . str_replace(" ", "%20",$url["path"]) . "?appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa . "&signature=" . $encodedSignature;
else
return $url["scheme"] . "://" . $url["host"] . str_replace(" ", "%20",$url["path"]) . "?" . str_replace(" ","%20",$url["query"]) . "&appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa . "&signature=" . $encodedSignature;
}
public static function uploadFileBinary($url, $localfile, $headerType="XML") {
$headerType = strtoupper($headerType);
$fp = fopen($localfile, "r");
$session = curl_init();
curl_setopt($session, CURLOPT_VERBOSE, 1);
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_PUT, 1);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($session, CURLOPT_HEADER, false);
if ($headerType == "XML") {
curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
} else {
curl_setopt($session, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
}
curl_setopt($session, CURLOPT_INFILE, $fp);
curl_setopt($session, CURLOPT_INFILESIZE, filesize($localfile));
$result = curl_exec($session);
//$error = curl_error($session);
//$http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
curl_close($session);
fclose($fp);
return $result;
}
public static function ValidateOutput($result)
{
$string = (string)$result;
$validate = array("Unknown file format.", "Unable to read beyond the end of the stream",
"Index was out of range", "Cannot read that as a ZipFile", "Not a Microsoft PowerPoint 2007 presentation",
"Index was outside the bounds of the array", "An attempt was made to move the position before the beginning of the stream",
);
$invalid = 0;
foreach ($validate as $key => $value) {
$pos = strpos($string, $value);
if ($pos === 1)
{
$invalid = 1;
}
}
if($invalid == 1)
return $string;
else
return "";
}
Kindly provide me the solution because this error hampers my work terribly.
Related
I have been working on a clients WP site which lists deals from Groupon. I am using the Groupon's official XML feed, importing via WP All Import. This works without much hassle. Now the issue is Groupon doesn't update that feed frequently but some of their deals get sold out or off the market often. So to get this resolved what I am trying is using a CURL script to crawl the links and check if the deal is available or not then turn the unavailable deals to draft posts (Once a day only).
The custom script is working almost perfectly, only after the first 14/24 requests the server starts responding with 502/503 HTTP status codes. To overcome the issue I have used the below precautions -
Using the proper header (captured from the requests made by the browser)
Parsing cookies from response header and sending back.
Using proper referrer and user agent.
Using proxies.
Trying to send request after a set interval. PHP - sleep(5);
Unfortunately, none of this got me the solution I wanted. I am attaching my code and I would like to request your expert insights on the issue, please.
Thanks in advance for your time.
Shahriar
PHP SCRIPT - https://pastebin.com/FF2cNm5q
<?php
// Error supressing and extend maximum execution time
error_reporting(0);
ini_set('max_execution_time', 50000);
// Sitemap URL List
$all_activity_urls = array();
$sitemap_url = array(
'https://www.groupon.de/sitemaps/deals-local0.xml.gz'
);
$cookies = Array();
// looping through sitemap url for scraping activity urls
for ($u = 0; $u < count($sitemap_url); $u++)
{
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch1, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0');
curl_setopt($ch1, CURLOPT_REFERER, "https://www.groupon.de/");
curl_setopt($ch1, CURLOPT_TIMEOUT, 40);
// curl_setopt($ch1, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_URL, $sitemap_url[$u]);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
// Parsing Cookie from the response header
curl_setopt($ch1, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$activity_url_source = curl_exec($ch1);
$status_code = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
curl_close($ch1);
if ($status_code === 200)
{
// Parsing XML sitemap for activity urls
$activity_url_list = json_decode(json_encode(simplexml_load_string($activity_url_source)));
for ($a = 0; $a < count($activity_url_list->url); $a++)
{
array_push($all_activity_urls, $activity_url_list->url[$a]->loc);
}
}
}
if (count($all_activity_urls) > 0)
{
// URL Loop count
$loop_from = 0;
$loop_to = (count($all_activity_urls) > 0) ? 100 : 0;
// $loop_to = count($all_activity_urls);
$final_data = array();
echo 'script start - ' . date('h:i:s') . "<br>";
for ($u = $loop_from; $u < $loop_to; $u++)
{
//Pull source from webpage
$headers = array(
'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-language: en-US,en;q=0.9,bn-BD;q=0.8,bn;q=0.7,it;q=0.6',
'cache-control: max-age=0',
'cookie: ' . implode('; ', $cookies),
'upgrade-insecure-requests: 1',
'user-agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
);
$site = $all_activity_urls[$u];
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_REFERER, "https://www.groupon.de/");
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $site);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Parsing Cookie from the response header
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$data = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status_code === 200)
{
// Ready data for parsing
$document = new DOMDocument();
$document->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">' . $data);
$xpath = new DOMXpath($document);
$title = '';
$availability = '';
$price = '';
$base_price = '';
$link = '';
$image = '';
$link = $all_activity_urls[$u];
// Scraping Availability
$raw_availability = $xpath->query('//div[#data-bhw="DealHighlights"]/div[0]/div/div');
$availability = $raw_availability->item(0)->nodeValue;
// Scraping Title
$raw_title = $xpath->query('//h1[#id="deal-title"]');
$title = $raw_title->item(0)->nodeValue;
// Scraping Price
$raw_price = $xpath->query('//div[#class="price-discount-wrapper"]');
$price = trim(str_replace(array("$", "€", "US", " "), array("", "", "", ""), $raw_price->item(0)->nodeValue));
// Scraping Old Price
$raw_base_price = $xpath->query('//div[contains(#class, "value-source-wrapper")]');
$base_price = trim(str_replace(array("$", "€", "US", " "), array("", "", "", ""), $raw_base_price->item(0)->nodeValue));
// Creating Final Data Array
array_push($final_data, array(
'link' => $link,
'availability' => $availability,
'name' => $title,
'price' => $price,
'baseprice' => $base_price,
'img' => $image,
));
}
else
{
$link = $all_activity_urls[$u];
if ($status_code === 429)
{
$status_msg = ' - Too Many Requests';
}
else
{
$status_msg = '';
}
array_push($final_data, array(
'link' => $link,
'status' => $status_code . $status_msg,
));
}
echo 'before break - ' . date('h:i:s') . "<br>";
sleep(5);
echo 'after break - ' . date('h:i:s') . "<br>";
flush();
}
echo 'script end - ' . date('h:i:s') . "<br>";
// Converting data to XML
$activities = new SimpleXMLElement("<?xml version=\"1.0\"?><activities></activities>");
array_to_xml($final_data, $activities);
$xml_file = $activities->asXML('activities.xml');
if ($xml_file)
{
echo 'XML file have been generated successfully.';
}
else
{
echo 'XML file generation error.';
}
}
else
{
$activities = new SimpleXMLElement("<?xml version=\"1.0\"?><activities></activities>");
$activities->addChild("error", htmlspecialchars("No URL scraped from sitemap. Stoping script."));
$xml_file = $activities->asXML('activities.xml');
if ($xml_file)
{
echo 'XML file have been generated successfully.';
}
else
{
echo 'XML file generation error.';
}
}
// Recursive Function for creating XML Nodes
function array_to_xml($array, &$activities)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
if (!is_numeric($key))
{
$subnode = $activities->addChild("$key");
array_to_xml($value, $subnode);
}
else
{
$subnode = $activities->addChild("activity");
array_to_xml($value, $subnode);
}
}
else
{
$activities->addChild("$key", htmlspecialchars("$value"));
}
}
}
// Cookie Parsing Function
function curlResponseHeaderCallback($ch, $headerLine)
{
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
{
$cookies[] = $cookie[1];
}
return strlen($headerLine); // Needed by curl
}
There is a mess of cookies in your snippet. The callback function just appends cookies to the array regardingless of whether they already exist or not. Here is a new version which at least seems to work in this case since there are no semicolon-seperated multiple cookie definitions. Usually the cookie string should be even parsed. If you have installed the http extension you can use http_parse_cookie.
// Cookie Parsing Function
function curlResponseHeaderCallback($ch, $headerLine)
{
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]+)/mi', $headerLine, $match) == 1)
{
if(false !== ($p = strpos($match[1], '=')))
{
$replaced = false;
$cname = substr($match[1], 0, $p+1);
foreach ($cookies as &$cookie)
if(0 === strpos($cookie, $cname))
{
$cookie = $match[1];
$replaced = true;
break;
}
if(!$replaced)
$cookies[] = $match[1];
}
var_dump($cookies);
}
return strlen($headerLine); // Needed by curl
}
I use the following to convert a doc file to pdf in PHP:
function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message,$unique_filename)
{
try
{
$fileName = $unique_filename.".pdf";
$postdata = array('OutputFileName' => $fileName, 'ApiKey' => $apiKey, 'file'=>"#".$fileToConvert);
$ch = curl_init("http://do.convertapi.com/word2pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
$header=ParseHeader(substr($result,0,$headers["header_size"]));
$body=substr($result, $headers["header_size"]);
curl_close($ch);
if ( 0 < $headers['http_code'] && $headers['http_code'] < 400 )
{
// Check for Result = true
if (in_array('Result',array_keys($header)) ? !$header['Result']=="True" : true)
{
$message = "Something went wrong with request, did not reach ConvertApi service.<br />";
return false;
}
// Check content type
if ($headers['content_type']<>"application/pdf")
{
$message = "Exception Message : returned content is not PDF file.<br />";
return false;
}
$fp = fopen($pathToSaveOutputFile.$fileName, "wbx");
fwrite($fp, $body);
$message = "The conversion was successful! The word file $fileToConvert converted to PDF and saved at $pathToSaveOutputFile$fileName";
return true;
}
else
{
$message = "Exception Message : ".$result .".<br />Status Code :".$headers['http_code'].".<br />";
return false;
}
}
catch (Exception $e)
{
$message = "Exception Message :".$e.Message."</br>";
return false;
}
}
I now want to use the same to convert a ppt to pdf. For which I change
$ch = curl_init("http://do.convertapi.com/word2pdf");
to
$ch = curl_init("http://do.convertapi.com/PowerPoint2Pdf");
but I am not sure why it isnt converting the given input. Is there something that I may be missing?
It's due to PHP 5.6.
You need to add this line to your code as well
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
See:Backward incompatible changes (at the bottom).
I am trying to search (filter) for files in a Dropbox folder, but no files are being found when there are files that match the filter. I am not using the PHP library provided by Dropbox.
Here is an extract of the code:
class Dropbox {
private $headers = array();
private $authQueryString = "";
public $SubFolders = array();
public $Files = array();
function __construct() {
$this->headers = array('Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.DROPBOX_APP_KEY.'", oauth_token="'.DROPBOX_OAUTH_ACCESS_TOKEN.'", oauth_signature="'.DROPBOX_APP_SECRET.'&'.DROPBOX_OAUTH_ACCESS_SECRET.'"');
$this->authQueryString = "oauth_consumer_key=".DROPBOX_APP_KEY."&oauth_token=".DROPBOX_OAUTH_ACCESS_TOKEN."&oauth_signature_method=PLAINTEXT&oauth_signature=".DROPBOX_APP_SECRET."%26".DROPBOX_OAUTH_ACCESS_SECRET."&oauth_version=1.0";
}
public function GetFolder($folder, $fileFilter = "") {
//Add the required folder to the end of the base path for folder call
if ($fileFilter == "")
$subPath = "metadata/sandbox";
else
$subPath = "search/sandbox";
if (strlen($folder) > 1) {
$subPath .= (substr($folder, 0, 1) != "/" ? "/" : "")
.$folder;
}
//Set up the post parameters for the call
$params = null;
if ($fileFilter != "") {
$params = array(
"query" => $fileFilter
);
}
//Clear the sub folders and files logged
$this->SubFolders = array();
$this->Files = array();
//Make the call
$content = $this->doCall($subPath, $params);
//Log the files and folders
for ($i = 0; $i < sizeof($content->contents); $i++) {
$f = $content->contents[$i];
if ($f->is_dir == "1") {
array_push($this->SubFolders, $f->path);
} else {
array_push($this->Files, $f->path);
}
}
//Return the content
return $content;
}
private function doCall($urlSubPath, $params = null, $filePathName = null, $useAPIContentPath = false) {
//Create the full URL for the call
$url = "https://api".($useAPIContentPath ? "-content" : "").".dropbox.com/1/".$urlSubPath;
//Initialise the curl call
$ch = curl_init();
//Set up the curl call
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($params != null)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$fh = null;
if ($filePathName != null) {
$fh = fopen($filePathName, "rb");
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_INFILE, $fh);
curl_setopt($context, CURLOPT_INFILESIZE, filesize($filePathName));
}
//Excecute and get the response
$api_response = curl_exec($ch);
if ($fh != null)
fclose($fh);
//Process the response into an array
$json_response = json_decode($api_response);
//Has there been an error
if (isset($json_response->error )) {
throw new Exception($json_response["error"]);
}
//Send the response back
return $json_response;
}
}
I then call the GetFolder method of Dropbox as such:
$dbx = new Dropbox();
$filter = "MyFilter";
$dbx->GetFolder("MyFolder", $filter);
print "Num files: ".sizeof($dbx->Files);
As I am passing $filter into GetFolder, it uses the search/sandbox path and creates a parameter array ($params) with the required query parameter in it.
The process works fine if I don't provide the $fileFilter parameter to GetFolder and all files in the folder are returned (uses the metadata/sandbox path).
Other methods (that are not in the extract for brevity) of the Dropbox class use the $params feature and they to work fine.
I have been using the Dropbpox API reference for guidance (https://www.dropbox.com/developers/core/docs#search)
At first glance, it looks like you're making a GET request to /search but passing parameters via CURLOPT_POSTFIELDS. Try using a POST or encoding the search query as a query string parameter.
EDIT
Below is some code that works for me (usage: php search.php <term>). Note that I'm using OAuth 2 instead of OAuth 1, so my Authorization header looks different from yours.
<?php
$access_token = '<REDACTED>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.dropbox.com/1/search/auto');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:Bearer ' . $access_token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('query' => $argv[1]));
$api_response = curl_exec($ch);
echo "Matching files:\n\t" . join("\n\t",
array_map(function ($file) {
return $file['path'];
}, json_decode($api_response, true)))."\n";
?>
USPS suggests to send request XML to
secure.shippingapis.com/ShippingAPI.dll?API=MerchandiseReturnV4&XML=
I have tried with the example XML given at
https://www.usps.com/business/web-tools-apis/merchandise-return-service-labels-v10-2a.htm
$url="https://secure.shippingapis.com/ShippingAPI.dll";
$api="API=MerchandiseReturnV4&XML=";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
echo result;
but it is returning nothing.....
If the request is approaching the API then it would return the response which can be the proper expected response or the error code with some error detail.
The problem for not getting the proper response might be of the following here-
Wrong XML passed to the query string
Missed some required fields in the XML
Invalid Web Tools Credentials
In order to know the exact Error Code and Details you need to parse the returned XML from the API Server.
You can get the response stream and read the stream to the Stream Reader
string result = null;
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
However I implemented this in .Net MVC but it might help for a head start to find the exact problem.
I forget to put the answers after solving my problem.
Function for connect to usps :-
public function connectToUSPS($url, $api, $xml) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
if (empty($error)) {
return $result;
} else {
return false;
}
}
Function to generate USPS label :-
function create_UspsLabel($shipId, $userId) {
$row = 'contains user data';
$uspsUserName = 'a valid usps user name';
$uspsPassword = 'a valid usps user password';
$retailerName = 'retailer name';
$retailerAddress ='retailer address';
$permitNumber = 'a valid permit number';
$retailerState = 'retailer state;
$retailerCity = 'retailer city';
$retailerZip = 'retailer zip code';
$PDUPoBox = 'pdu box number';
$PDUCity = 'pdu city name';
$PDUState = 'pdu state name';
$PDUZip = 'pdu zip code';
$PDUZip2 = 'pdu zip code2';
$oid = 'order id';
$packageId = "KR" . str_pad(($oid + 1), 5, "0", STR_PAD_LEFT);
$state = 'state';
$xml = '<EMRSV4.0Request USERID="' . $uspsUserName . '" PASSWORD="' . $uspsPassword . '">
<Option>RIGHTWINDOW</Option>
<CustomerName>' . $row->name.' '.$row->lastName . '</CustomerName>
<CustomerAddress1>' . $row->suit . '</CustomerAddress1>';
$xml.=' <CustomerAddress2>' . $row->address1 . '</CustomerAddress2>
<CustomerCity>' . $row->city . '</CustomerCity>
<CustomerState>' . $state . '</CustomerState>
<CustomerZip5>' . $row->zipcode . '</CustomerZip5>
<CustomerZip4 />
<RetailerName>' . $retailerName . '</RetailerName>
<RetailerAddress>' . $retailerAddress . '</RetailerAddress>
<PermitNumber>' . $permitNumber . '</PermitNumber>
<PermitIssuingPOCity>' . $retailerCity . '</PermitIssuingPOCity>
<PermitIssuingPOState>' . $retailerState . '</PermitIssuingPOState>
<PermitIssuingPOZip5>' . $retailerZip . '</PermitIssuingPOZip5>
<PDUPOBox>' . $PDUPoBox . '</PDUPOBox>
<PDUCity>' . $PDUCity . '</PDUCity>
<PDUState>' . $PDUState . '</PDUState>
<PDUZip5>' . $PDUZip . '</PDUZip5>
<PDUZip4>' . $PDUZip2 . '</PDUZip4>
<ServiceType>Priority Mail</ServiceType>
<DeliveryConfirmation>False</DeliveryConfirmation>
<InsuranceValue />
<MailingAckPackageID>' . $packageId . '</MailingAckPackageID>
<WeightInPounds>0</WeightInPounds>
<WeightInOunces>10</WeightInOunces>
<RMA>RMA 123456</RMA>
<RMAPICFlag>False</RMAPICFlag>
<ImageType>TIF</ImageType>
<RMABarcode>False</RMABarcode>
<AllowNonCleansedDestAddr>False</AllowNonCleansedDestAddr>
</EMRSV4.0Request>';
$result = $this->connectToUSPS('https://secure.shippingapis.com/ShippingAPI.dll', 'API=MerchandiseReturnV4&XML=', $xml);
$xml = new SimpleXMLElement($result);
$string = base64_decode($xml->MerchandiseReturnLabel);
if ($string) {
$img_file = fopen(__USPSLABELIMAGE__ . "uspsLabel.tif", "w");
fwrite($img_file, $string);
fclose($img_file);
$imageMagickPath = "/usr/bin/convert";
$dest = __USPSLABELIMAGE__ . "uspsLabel.tif";
$filename = time() . ".png";
$pngDestPath = __USPSLABELIMAGE__ . $filename;
exec("$imageMagickPath -density 72 -channel RGBA -colorspace RGB -background none -fill none -dither None $dest $pngDestPath");
return $filename;
} else {
return "error";
}
}
I'm trying to do a very basic setup of LinkedIn - accessing public profile data about people.
I've tried several ways of accessing with oAuth over several hours. I'm not getting anywhere.
All the existing class structures et'al seem to help with accessing a user's account to post, or add friends, find a fish etc. I don't need any of that. I just want to get basic profile data.
Some code of latest attempts; but I don't get it past here:-
$consumer = new OAuthConsumer($apiKey, $apiSecret);
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$req_req = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $linkedInURL . "/uas/oauth/requestToken");
$req_req->sign_request($signature_method, $consumer, NULL);
$signed_url = $req_req->to_url();
That should gives me a signed request of:-
https://api.linkedin.com/uas/oauth/requestToken?oauth_consumer_key=xxx&oauth_nonce=xx&oauth_signature=xxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316530337&oauth_version=1.0
Obviously, that's not what I need to get data. But, just out of interest I checked the URL with the API data request, as such:-
http://api.linkedin.com/v1/people/url=http%3A%2F%2Fwww.linkedin.com%2Fin%2Fchrisvoss:public?oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316529463&oauth_version=1.0
And got :-
<error>
<status>401</status>
<timestamp>1316531835564</timestamp>
<request-id>L8A1M85MWN</request-id>
<error-code>0</error-code>
<message>
[unauthorized].OAU:tm6i3ke827xz|*01|*01|*01:1316529463:MSFHS3f4iaG9pg2gWYlf22W4NPo=
</message>
</error>
I'm just a bit clueless here. I know everyone says it's tears to implement oAuth and Linkedin. But, I don't need half of what most need, so how do I get to the basic data is only my question.
Thanks in advance for any help.
Try To Use the following code
session_start();
require_once("OAuth.php");
$domain = "https://api.linkedin.com/uas/oauth";
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer("DEHYU99peS88wDDAFOcSm3Af5VO1tdrdgq1xPu_fpSSjsqPcoeABUs_NCyY33WIH", "gZrZr2-7s80CEsGpAHqFgREMbRWkR3L8__tkje3j-oKtIDlmn5KCR6bXD8i0HFp1", NULL);
$callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?action=getaccesstoken";
# First time through, get a request token from LinkedIn.
if (!isset($_GET['action'])) {
$req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "POST", $domain . "/requestToken");
$req_req->set_parameter("oauth_callback", $callback); # part of OAuth 1.0a - callback now in requestToken
$req_req->sign_request($sig_method, $test_consumer, NULL);
$ch = curl_init();
// make sure we submit this as a post
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$req_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/requestToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
curl_close($ch);
//print_r($req_req); //<---- add this line
//print("$output\n"); //<---- add this line
parse_str($output, $oauth);
# pop these in the session for now - there's probably a more secure way of doing this! We'll need them when the callback is called.
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Redirect the user to the authentication/authorisation page. This will authorise the token in LinkedIn
Header('Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']);
#print 'Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']; // <---- add this line
} else {
# this is called when the callback is invoked. At this stage, the user has authorised the token.
# Now use this token to get a real session token!
//print "oauth_token = [[".$_REQUEST['oauth_token']."]]\n";echo "<br/><br/>";
$req_token = new OAuthConsumer($_REQUEST['oauth_token'], $_SESSION['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "POST", $domain . '/accessToken');
$acc_req->set_parameter("oauth_verifier", $_REQUEST['oauth_verifier']); # need the verifier too!
$acc_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$acc_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/accessToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 1: ' . curl_error($ch);
}
curl_close($ch);
parse_str($output, $oauth);
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Now you have a session token and secret. Store these for future use. When the token fails, repeat the above process.
//$endpoint = "http://in.linkedin.com/in/intercom"; # need a + symbol here.
$endpoint = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,industry,educations,site-standard-profile-request)";
//$req_token = new OAuthConsumer($oauth['oauth_token'], $oauth['oauth_token_secret'], 1);
$req_token = new OAuthConsumer($oauth['oauth_token'],$oauth['oauth_token_secret'], 1);
//$profile_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "GET", $endpoint, array("name" => "intercom")); # but no + symbol here!
$profile_req = OAuthRequest::from_consumer_and_token($test_consumer,$req_token, "GET", $endpoint, array());
$profile_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$profile_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $endpoint);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 2: ' . curl_error($ch);
}
curl_close($ch);
//header ("Content-Type:text/xml");
//print $output;
$myFile = $_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
//$stringData = "Bobby Bopper\n";
fwrite($fh, $output);
fclose($fh);
//Initialize the XML parser
global $currentTag;
global $profileArray;
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
$element_name = strtolower($element_name);
global $currentTag;
$currentTag = $element_name;
/*switch($element_name) {
case "person":
$currentTag = $element_name;
break;
case "headline":
echo "headline: ";
break;
case "school-name":
echo "school-name: ";
break;
case "degree":
echo "degree: ";
break;
case "field-of-study":
echo "field-of-study: ";
}*/
}
//Function to use at the end of an element
function stop($parser,$element_name) {}
//Function to use when finding character data
function char($parser,$data){
//echo $data;
global $currentTag;
global $profileArray;
switch($currentTag) {
/* case "member-url":
if(!isset($profileArray['member-url'])) {
$profileArray['member-url'] = $data;//echo $profileArray['industry'];
}
break;*/
case "id":
if(!isset($profileArray['id'])) {
$profileArray['id'] = $data;//echo $profileArray['industry'];
}
break;
case "site-standard-profile-request":
if(!isset($profileArray['site-standard-profile-request'])) {
$profileArray['site-standard-profile-request'] = $data;//echo $profileArray['industry'];
}
break;
case "first-name":
if(!isset($profileArray['first-name'])) {
$profileArray['first-name'] = $data;//echo $profileArray['industry'];
}
break;
case "last-name":
if(!isset($profileArray['last-name'])) {
$profileArray['last-name'] = $data;//echo $profileArray['industry'];
}
break;
case "industry":
if(!isset($profileArray['industry'])) {
$profileArray['industry'] = $data;//echo $profileArray['industry'];
}
break;
case "headline":
if(!isset($profileArray['headline'])) {
$profileArray['headline'] = $data;
}
break;
case "school-name":
if(!isset($profileArray['school-name'])) {
$profileArray['school-name'] = $data;
}
break;
case "degree":
if(!isset($profileArray['degree'])) {
$profileArray['degree'] = $data;
}
break;
case "field-of-study":
if(!isset($profileArray['field-of-study'])) {
$profileArray['field-of-study'] = $data;
}
break;
}
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen($_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml","r");
//Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);
print_r($profileArray);
getCurrentCookieValue($name)
}
you can use linkedIn javascript API to retrieve profile information