Get Email state using codeigniter & sendgrid Webhook - codeigniter-3

I have integrated sendgrid for send mail. I also want to track whether a user has opened the mail and click the link inside the mail or not.
that's why I used sendgrid.
using it I can send mail, but can't track mail states(mail is opened or not, the link is clicked or not).
I tried the below code for sending mail.
function sendMail($toMails, $body, $subject, $ccMails = array(), $bccMails = array()) {
$ci = &get_instance();
if (empty($toName)) {
$toName = $toMails;
}
$sendMail = $ci->config->item('sendMail');
$email = new \SendGrid\Mail\Mail();
$email->setFrom($ci->config->item('from'), "From User name");
$email->setSubject($subject);
$email->addTos($toMails); //for multiple user pass array with emails and names
$email->addCcs($ccMails);
$email->addBccs($bccMails);
$email->addContent("text/html", $body);
$email->setFooter(false, "", "<strong>If you don't want to receive this type of email in the future, please <a href='http://w3schools.com'>Unsubscribe</a>.</strong>");
//$email->setSpamCheck(true, 1, "http://localhost:8081/");
// Tracking Settings
$email->setClickTracking(true, true);
//$email->setOpenTracking(true, true);
$sendgrid = new \SendGrid($ci->config->item('key'));
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if ($sendMail) :
if (!$response->statusCode()) :
_pre($response->headers());
return false;
else :
return true;
endif;
endif;
}
which is working fine, except it is going in the spam.
now below code, I am using to get details as per email id.
$sendgrid = new \SendGrid($this->config->item('key'));
$query_params = json_decode('{"start_date": "2019-10-07","end_date": "2019-10-07","to_email": "cadmin1#getnada.com","subject":"This is a subject test"}');
$response = $sendgrid->client->stats()->get(null, $query_params);
_pre($response->body());
exit;
above code only gives me date wise data, but I also want email id wise.
but in spite of adding a parameter for that, still, I am not getting desired output.
https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-recipient-email
I have used the above demo, in that demo, they have used curl but I am using CodeIgniter's way.
I am not sure about sendgrid version that's why I added both version tag, I used API one.
anyone having a proper solution regarding it?

I have implemented webhooks to archive my desire output.
for that need to follow steps as per documentation shows
after that need to create a page from where we can get mails status.
on executing that page it returns data as per activity.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
$data = file_get_contents("php://input");
$events = json_encode($data, true);
$requestData = array('response' => $events);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<url which we earlier set for webhook as per documentation>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
?>
i have used Curl for getting desire output.

Related

Separate Payment Integeration For Selected plan type using Drupal Form with Paypal API

I have used a normal class as an API and in that U am passing all the parameters to paypal and i am getting success.
Only thing i am missing is that amount is not being deducted from the sandbox account.
Where as if i pay amount for buying a product by using checkout with paypal the actual amount is being deducted in my sandbox account.
What could be the reason? Is there any other alternative way where i can able to use paypal to receive money through passed arguments in payment details form.
In the submit function of the drupal form i am calling like this.
$paypalDoDirect = new PaypalDoDirect();
// passing all parameters to $paypalDoDirect
$response= $paypalDoDirect->MakePayment();
I am getting transaction is successful and every parameters are getting passed sucessfully.
This is my class api-
class PaypalDoDirect
{
/**Declared all fields **/
function MakePayment()
{
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if ("sandbox" === $this->environment || "beta-sandbox" === $this->environment) {
$API_Endpoint = "https://api-3t.$this->environment.paypal.com/nvp";
}
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$this->paymentType&AMT=$this->amount&CREDITCARDTYPE=$this->cc_type&ACCT=$this->cc_number" .
"&EXPDATE=$this->expdate_month$this->expdate_year&CVV2=$this->cvv2_number&FIRSTNAME=$this->first_name&LASTNAME=$this->last_name&EMAIL=$this->email" .
"&STREET=$this->address1&CITY=$this->city&STATE=$this->state&ZIP=$this->zip&COUNTRYCODE=$this->country&CURRENCYCODE=$this->currencyID";
//$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
$methodName_ = 'DoDirectPayment';
$nvpStr_ = $nvpStr;
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$this->version&PWD=$this->API_Password&USER=$this->API_UserName&SIGNATURE=$this->API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if (!$httpResponse) {
return ("$methodName_ failed: " . curl_error($ch) . '(' . curl_errno($ch) . ')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if (sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if ((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
return "success";
} else {
return (urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]));
}
}
}
Yes there is a paypal API module in drupal. It's a nice structured module to extend paypal IPN in some custom module.
If you use this module, IPN callback will be handled by this module & you can get notification of it by hook_paypal_api_ipn() at your instance. If you go though paypal documentation about handling payment with paypal & look into the module code, you will understand the mechanism to use it well. I will recommend you to use this module.
Though you can create your own module to handle paypal payment either express or forward users there. I have done it once with drupal instance long ago. You will have to send users or data(for express) at given URL for your account with some information & what ever happens in there(pass/fail/terminate), paypal will inform you at your mentioned callback URL of your instance. Receive the info & do work accordingly..
This might be what you looking for,
Paypal Direct pay not working
Exerpt:
The DoDirectPayment call charges credit cards directly; it does not deduct from a PayPal account - even if that card is attached to an existing PayPal account. Therefore it doesn't show up as a transaction in our 'buyer' PayPal account.

Is it possible to pass the amount back to my site

I am new to developer.paypal.com and i am creating a subscribe button in www.sandbox.paypal.com,is it possible to pass back the amount paid for the subscription by the customer to my website or the details that have been made in www.sandbox.paypal.com?if it is, can you show me some example on how to do this.
after i tried the subscription button this are the value returned i could not find some value in the link that you provided.or the subscription variable how can i show them up?
I could not get the start date and the ending date of my subscription
Thank you.
You could do this one of two ways. You could use IPN or PDT to return information to your site once a payment completes. The better of the two ways, would be to use IPN, or atleast use IPN in conjunction with PDT.
Instant Payment Notification (IPN) is a message service that notifies you of events related to PayPal transactions. You can use it to automate back-office and administrative functions, such as fulfilling orders, tracking customers, and providing status and other information related to a transaction.
You can find more on IPN the page here. Also on that page, off to the left hand side are some more links that are useful as well. There are pages for creating a listener, setup, testing, IPN history, IPN with FMF, IPN/PDT variables, and sample code here. There are also a few more examples of sample code here as well.
PayPal’s PDT system sends order confirmations to merchant sites that use PayPal Payments Standard and lets them authenticate this information. Such sites can then display this data locally in an “order confirmation” page. IPN is more reliable than PDT, and also with PDT it is dependent on the buyer clicking a button to return to your site. If they they dont click on the button to return to your site, no information is sent back and you can not resend this information like you can with IPN. You can find more on PDT here.
I personally only use PDT for crating a dynamic thank you page on my site, and use IPN for updating my database and automating some tasks. Hope this helps. :)
SAMPLE PHP (v5.2) IPN SCRIPT
<?php
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
?>
SAMPLE PDT PHP (v5.3) SCRIPT
<?php
$pp_hostname = "www.paypal.com"; // Change to www.sandbox.paypal.com to test against sandbox
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "GX_sTf5bW3wxRfFEbgofs88nQxvMQ7nsI8m21rzNESnl_79ccFTWj2aPgQ0";
$req .= "&tx=$tx_token&at=$auth_token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$pp_hostname/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: $pp_hostname"));
$res = curl_exec($ch);
curl_close($ch);
if(!$res){
//HTTP ERROR
}else{
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$itemname = $keyarray['item_name'];
$amount = $keyarray['payment_gross'];
echo ("<p><h3>Thank you for your purchase!</h3></p>");
echo ("<b>Payment Details</b><br>\n");
echo ("<li>Name: $firstname $lastname</li>\n");
echo ("<li>Item: $itemname</li>\n");
echo ("<li>Amount: $amount</li>\n");
echo ("");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
?>
Your transaction has been completed, and a receipt for your purchase has been emailed to you.<br> You may log into your account at <a href='https://www.paypal.com'>www.paypal.com</a> to view details of this transaction.<br>

PayPal how to get post back params if response is FAIL

Could I get post back params if in scenario to a buyer click 'cancel and return to xxx store'? below code is how I tried to have post back params echo out after buyer click cancel during the palpal webscr process:
$req = 'cmd=_notify-synch';
$pp_hostname = "www.sandbox.paypal.com";
$tx_token = $_GET['tx'];
$auth_token = "Ti-bfX-sv-zNDXZS";
$req .= "&tx=".$tx_token."&at=".$auth_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://".$pp_hostname."/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".$pp_hostname));
$res = curl_exec($ch);
curl_close($ch);
if(!$res){
//HTTP ERROR
}else{
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if(strcmp($lines[0], "SUCCESS") == 0){
for($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
//process payment
}else if(strcmp($lines[0], "FAIL") == 0){
$lines = explode("\n", $res);
$keyarray = array();
for($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// echo post back params if FAIL
echo "<p><h3>Transaction ".$keyarray['payment_status']."!</h3></p>";
}
}
Is that possible to get post back params if response FAIL? I need some data to process in db if buyer cancel the transaction.
Thanks.
PayPal would not pass back any parameters to your cancel your, but you could pass back your own. You could dynamically populate the cancel URL that helps you to identify the user or order, and then read that on the cancel URL. For example, you could dynamically populate the cancel URL to something like https://www.mysite.com/cancel.php?orderid=483723 and then you would do your own look up in your system based on the order id, or what ever you pass over and back to your cancel URL.
paypal provide all things about transaction information for more information check below link info
reason_code
https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/

How to use dodirect payment paypal on form submission?

I have to use dodirect payment method after the form submission. The form will be displayed on the site for all the card detail such as card type (visa or master), card card no, security number, expiration date, name on card, address, state, postal, country, phone, email etc.
I searched how to use the dodirect method and found as below
<?php
/** DoDirectPayment NVP example; last modified 08MAY23.
*
* Process a credit card payment.
*/
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('my_api_username');
$API_Password = urlencode('my_api_password');
$API_Signature = urlencode('my_api_signature');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
// Set request-specific fields.
$paymentType = urlencode('Authorization'); // or 'Sale'
$firstName = urlencode('customer_first_name');
$lastName = urlencode('customer_last_name');
$creditCardType = urlencode('customer_credit_card_type');
$creditCardNumber = urlencode('customer_credit_card_number');
$expDateMonth = 'cc_expiration_month';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode('cc_expiration_year');
$cvv2Number = urlencode('cc_cvv2_number');
$address1 = urlencode('customer_address1');
$address2 = urlencode('customer_address2');
$city = urlencode('customer_city');
$state = urlencode('customer_state');
$zip = urlencode('customer_zip');
$country = urlencode('customer_country'); // US or other valid country code
$amount = urlencode('example_payment_amuont');
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}
?>
I didn't get an idea how to use this code on submission of the form that I have on my site. Can anyone help me out how to use this after submitting form.
Thanks in advance :)
That's really not a very well built function. It's basically wanting you to just fill in the values within the function rather than pass them in. It's a pretty rough example and you can see it was last updated in 2008 according to the comments.
If you want to use it, though, you can simply fill in all those placeholders where they show things like "my_api_username" with the data that you want to actually include.
If you want something a lot easier to work with, I would recommend using this PHP library for PayPal that I developed and have maintained for years. It's current and contains straight forward samples for running DoDirectPayment. You could have it up-and-running within minutes.
I offer 30 min of free training via screen share, too, if you're interested in that.
Actually there are samples available for DoDirectPayment as part of the official SDKs available at https://www.x.com/developers/paypal/documentation-tools/paypal-sdk-index#expresscheckoutnew
Suggest using the official SDK and check the samples inside them. In case of any issues please post back here or open an issue at https://github.com/paypal/merchant-sdk-php/issues

How to count likes on FB page?

I have to do a very simple operation but my programming skills are not enough. I have to count likes in Facebook page and print that number on my web-site. I have two scripts that do the job well for ordinary web-sites, but they don't want to show the number of likes for the page.
<?php
$source_url = "http://www.facebook.com/"; //This could be anything URL source including stripslashes($_POST['url'])
$url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($source_url);
$likes = $xml->link_stat->like_count;
$comments = $xml->link_stat->comment_count;
$total = $xml->link_stat->total_count;
$max = max($shares,$likes,$comments);
echo $likes;
?>
<?php
$fql = "SELECT url, normalized_url, share_count, like_count, comment_count, ";
$fql .= "total_count, commentsbox_count, comments_fbid, click_count FROM ";
$fql .= "link_stat WHERE url = 'http://www.apple.com/'";
$apifql="https://api.facebook.com/method/fql.query?format=json&query=".urlencode($fql);
$json=file_get_contents($apifql);
print_r( json_decode($json));
?>
Both scripts work for ordinary web-sites but cant fetch fb page likes number. May be I should enter the link in another format or something?
I can get required data using graph like this http://graph.facebook.com/?ids=AutoSpecCenter , just by entering page name like that. But I don't know how to manipulate with this data.
As you already wrote in your question, you can query such information through Facebooks' Graph API. This short example will get the information of the Coca-Cola page, decode the JSON and outputs the number of people that like the page $data->likes.
<?php
$ch = curl_init("https://graph.facebook.com/CocaCola?access_token=<Access Token>");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$raw = curl_exec($ch);
curl_close($ch);
$data = json_decode($raw);
echo $data->likes . " people like Coca-Cola";
?>
If you need to perform more tasks than just getting the likes of a page, consider using the Facebook SDK as cpilko suggested.
Here's the quick and dirty way:
<?php
$fb_id = 'AutoSpecCenter';
$url = 'https://graph.facebook.com/' . urlencode($fb_id);
$result = json_decode( file_get_contents($url) );
printf("<p>There are %s people who like %s</p>", $result->likes, $result->name);
You'd do much better off installing the Facebook PHP SDK or using cURL to get this.
You could set $fb_id equal to a url as well.
here is a easy way too....
<?php
$page_id = 'yourfbpageid'; // your facebook page id
$xml = #simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
?>
<li class="text white"><span></span><?php echo $fans.' Fans'; ?></li>
courtesy:ravi patel
This worked for me
<?php
function getData($username){
$access_token = 'YOUR ACCESS TOKEN'; //Replace it with your Access Token
$json = json_decode(file_get_contents("https://graph.facebook.com/".$username."?fields=fan_count&access_token=".$access_token),true);
return $json;
}
$data = getData("Mypage");//Replace it with your Username
$likes = $data['fan_count'];
echo "Facebook Likes: ".$likes;
?>
I was having same problem, just adding likes.summary(true),comments.summary(true) in parameter in against "fields" worked for me.
e.g. I used https://graph.facebook.com/me/feed?access_token=ACCESS_TOKEN&fields=story,from,story_tags,likes.summary(true),comments.summary(true)
instead of https://graph.facebook.com/me/feed?access_token=ACCESS_TOKEN
Also you can add other parameters if you want; separated by a ,
Also if you want count of single post you can use
https://graph.facebook.com/POST_ID/likes?summary=true&access_token=ACCESS_TOKEN
for likes count
Or
https://graph.facebook.com/POST_ID/comments?summary=true&access_token=ACCESS_TOKEN
for comment count
Try this code
<?php echo facebooklike('209414452444193');
function facebooklike($page_id){
$likes = 0; //Initialize the count
//Construct a Facebook URL
$json_url ='https://graph.facebook.com/'.$page_id.'';
$json = get_contents($json_url);
$json_output = json_decode($json);
//Extract the likes count from the JSON object
if($json_output->likes){
$likes = $json_output->likes;
}
return $likes;
}
function get_contents($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>