I am having trouble posting a notification.
This is my PHP code:
try {
$id = Fb_Config::get_app_id();
$secret = Fb_Config::get_secret_code();
$url = "https://graph.facebook.com/oauth/access_token?client_id=$id&client_secret=$secret&grant_type=client_credentials";
$appAccessToken = end(explode("=", file_get_contents($url), 2));
var_export(Fb_Facebook::get()->api_post("/".$this->get_logged_in_user()->get_id()."/notifications?access_token=$appAccessToken", array(
href => "http://www.disney.com",
template => "this is awesome"
)));
} catch (Exception $e) {
echo "<pre>Error: ";
echo $e->getMessage();
echo "</pre>";
}
The error is:
Error: (#15) This method must be called with an app access_token.
Don’t make this more complicated than it has to be – the combination of app_id|app_secret (pipe symbol in the middle) works as app access token.
Related
I cannot find any documentation on this.
Here is my code:
I'm using Laravel 5.5 and Facbook graph. Im posting to a page but I got this error fb_exchange_token parameter not specified but I have successfully logged in.
Due to shoddy documentation I cannot find anything on fb_exchange_token on the Facebook's website nor elsewhere.
Can anyone help?
{
$facebook = Facebooks::findOrFail($id);
$fb = new Facebook([
'app_id' => 'my_id', // Replace {app-id} with your app id
'app_secret' => 'my_secret',
'default_graph_version' => 'v3.3',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages', 'publish_pages']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach($pages as $key){
if($key['name'] == 'CloudGuest Test'){
if(isset($_POST['facebook_status'])){
$text1 = $_POST['facebook_status'];
$post = $fb->post('/' . $key['id'] . '/feed', array('message' =>$text1),$key['access_token']);
$post = $post->getGraphNode()->asArray();
print_r($post);
}
}
}
}
Hi guys i need your help, i installed facebook sdk with composer on my application, y created a login system, on facebook developer i added my dev domain on localhost https://devlocalhost.io and my domain from production, so in localhost the loging is working fine, but on production i get this error
Argument 3 passed to GuzzleHttp\Client::request() must be of the type array, string given, called in /home/user/src/app/vendor/guzzlehttp/guzzle/src/Client.php on line 89
here is part of my code,
on my SecurityController
public function facebookCallback(Request $request,UserPasswordEncoderInterface $encoder)
{
$fb = $this->facebook();
$helper = $this->fHelper($fb);
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name,email,link,picture', $accessToken->getValue());
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user_info = $response->getGraphUser();
//here i create the user on my app or check if the user exist
}
So, here are my private method to the Facebook object and helper
private function facebook()
{
$fb = new Facebook([
'app_id' => 'myapp-id', // Replace {app-id} with your app id
'app_secret' => 'my-secret',
'default_graph_version' => 'v3.1',
]);
return $fb;
}
private function fHelper($fb)
{
$helper = $fb->getRedirectLoginHelper();
return $helper;
}
private function furlLogin()
{
$fb = $this->facebook();
$helper = $this->fHelper($fb);
$permissions = ['email']; // Optional permissions
//$loginUrl = $helper->getLoginUrl('https://devlocalhost.io/es/fb-callback/', $permissions);
$loginUrl = $helper->getLoginUrl('https://my_domain.com/es/fb-callback/', $permissions);
return $loginUrl;
}
so, on local host ys working fine but when i did the deploy os the branch i installed the dependency on server etc, is giving me this error
any idea?
I am using symfony. I have to create programme for facebook login. I created on class and in that create two function first is for generating link and other is callback function.
In controller created one action name is indexAction, in that object of class present. But when we run programme using link as http://localhost/symfony-demo-project/web/app_dev.php/login on browser it gives Error like:
The autoloader expected class "Btit\Bundle\CommonBundle\facebook\facebookLogin" to be defined in file "/var/www/html/symfony-demo-project/src/Btit/Bundle/CommonBundle/facebook/facebookLogin.php". The file was found but the class was not in it, the class name or namespace probably has a typo.
<?php
namespace Btit\Bundle\CommomBundle\facebook;
use Facebook\Facebook;
$fb = new Facebook/Facebook([
'app_id' => '1622871987981966',
'app_secret' => '6a15b7ae9e4409b6d33553ed3ed61f95',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://localhost/symfony-demo-project/app-dev.php/login/', $permissions);
echo 'Log in with Facebook!';
}
function Callback()
{
$fb = new Facebook/Facebook([
'app_id' => '1622871987981966',
'app_secret' => '6a15b7ae9e4409b6d33553ed3ed61f95',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');
}
}
?>
Controller is like that
<?php
namespace Btit\Bundle\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Btit\Bundle\CommonBundle\facebook\facebookLogin;
class LoginController extends Controller
{
/**
* #Route("/login")
* #Template()
*/
public function indexAction()
{
$l = new facebookLogin;
$l->LoginLink();
$l->Callback();
//return array();
}
}
?>
Give me solution for this error...
I need to validate shipping information entered when goods are dispatched. (I am having a nightmare using Cake!)
Each shipping company has a different format for their tracking references. I have written some regex to validate, and these are stored in my database.
All the validation for CakePHP happens in the model so I cannot use $this to retrieve the correct regex.
The regex is available in the view; is there anyway to use this to validate before the form is submitted?
I am currently sending the data through an ajax call
Controller
public function editTracking() {
$this->autoRender = false;
if ($this->request->is('ajax')) {
if($this->GoodsOutNote->save($this->request->data['GoodsOutNote'])){
$this->GoodsOutNote->save($this->request->data['GoodsOutNote']);
print_r($this->request->data['GoodsOutNote']['tracking_details']);
}else{
print_r($errors = $this->GoodsOutNote->validationErrors);
}
}
}
View
<?php echo $this->Form->create('GoodsOutNote',array(
'action'=>'editTracking','default' => false)); ?>
<fieldset>
<?php
echo $this->Form->input('id',array(
'default'=>$goodsOutNote['GoodsOutNote']['id']));
echo $this->Form->input('tracking_details',array(
'default'=>$goodsOutNote['GoodsOutNote']['tracking_details']));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));
$data = $this->Js->get('#GoodsOutNoteEditTrackingForm')->serializeForm(array(
'isForm' => true, 'inline' => true));
$this->Js->get('#GoodsOutNoteEditTrackingForm')->event('submit',
$this->Js->request(
array('action' => 'editTracking', 'controller' => 'goods_out_notes'),
array(
'update' => '#tracking_details,#GoodsOutNoteTrackingDetails',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'PUT'
)
)
);
echo $this->Js->writeBuffer();
?>
In the view, I can use $goodsOutNote['ShippingMethod']['valid_regex'] to access the correct format but I am lost as to how I can pass this to the form.
I have fixed this using the following approach.
In my controller, I retrieve the full record that I am about to edit. I can then validate the input using preg_match(). I would really appreciate any comments on this - is there a better approach?
public function editTracking() {
$this->autoRender = false;
if ($this->request->is('ajax')) {
$id = $this->request->data['GoodsOutNote']['id'];
$options = array('conditions' => array('GoodsOutNote.' . $this->GoodsOutNote->primaryKey => $id));
$goodsOutNote = $this->GoodsOutNote->find('first', $options);
$trackingRef = $this->request->data['GoodsOutNote']['tracking_details'];
$regex = "/".$goodsOutNote['ShippingMethod']['valid_regex']."/";
if(preg_match($trackingRef,$regex)){
if($this->GoodsOutNote->save($this->request->data['GoodsOutNote'])){
$this->GoodsOutNote->save($this->request->data['GoodsOutNote']);
print_r($trackingRef);
}
else{
print_r($errors = $this->GoodsOutNote->validationErrors);
}
}
else {
print_r($errors = $trackingRef.'is not valid');
}
}
}
Everything else works fine except for the location. The actual city/state does not come across. Instead the word Array is displayed. My field type in the database is text but I've tried every field type through mysql. The HTML file is JSON where it comes to the field names. I am very new at this so any help is appreciated.
This is my php file:
<? ob_start(); ?>
<?php
define('FACEBOOK_APP_ID', '');
define('FACEBOOK_SECRET', '');
// No need to change function body
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
if ($_REQUEST) {
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
/*
echo "<pre>";
print_r($response);
echo "</pre>"; // Uncomment this for printing the response Array
*/
$name = $response["registration"]["name"];
$email = $response["registration"]["email"];
$gender = $response["registration"]["gender"];
$prosecutor = $response["registration"]["prosecutor"];
$location = $response["registration"]["location"];
// Connecting to Database
$con = mysql_connect("my_hosting_site","Database","password");
if (!$response)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Database", $con);
mysql_query("INSERT INTO my_table (name, email, gender, prosecutor, location)
VALUES ('$name', '$email', '$gender', '$prosecutor', '$location')");
mysql_close($con);
}
$URL="https://www.facebook.com";
header ("Location: $URL");
?>
<? ob_flush(); ?>
Facebook
Basically, it's an array.
[location] => Array
(
[name] => Delhi, India
[id] => 1.1604xxxxxx286E+14
)
Use this for getting location stored in your db, like I have written below:
$location = $response["registration"]["location"]["name"];