POST Facebook Notification using Graph API - php

I'm trying to post notification using facebook graph api post method but I'm getting
(#15) This method must be called with an app access_token.
However the access_token which I'm sending in querystring is app access token which is fetched using this method
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".FB_APP_ID."&client_secret=".FB_SECRET."&grant_type=client_credentials";
I 've seen few guys have implemented it but don't know why its not working for me, someone pls tell me where I'm wrong in it.
Thanks
EDIT
I got it working, here is the change
This line of code will never work, because the internal access_token will override the app access_token which we are trying to pass in query string.
$this->facebook->api("/".$to_userId."/notifications?access_token=$app_token_url&template=message",'POST');
So Use this code
$data = array(
'href'=> 'https://apps.facebook.com/MY_APP/',
'access_token'=> $app_token,
'template'=> 'test'
);
try {
$this->facebook->api("/".$to_userId."/notifications",'POST',$data);
} catch (FacebookApiException $e) {
}

Is your app accidentally configured as a 'native/desktop' app in the app settings? if so, change it back to 'web'

Related

Facebook PHP SDK get page posts data is empty

I'm having a strange problem with the Facebook PHP SDK,
$response = $this->getConnection()->get("me/posts");
$feedEdge = $response->getGraphEdge();
var_dump($response); exit;
the getConnection() call provides me with a \Facebook\Facebook object with the default_access_token set but this works as I get a response from Facebook
But the body from the above var_dump gives:
["decodedBody":protected]=>
array(1) {
["data"]=>
array(0) {
}
}
What is really strange is when I use the Graph Explorer (as my Application and using the same Page) I see all the posts. So I thought maybe it was the access token was not working correctly so I copied and pasted the access token shown in from the graph explorer into my get() call to override the default like below unfortunately this did not work and I got exactly the same output.
$response = $this->getConnection()->get("me/posts", "EAA....");
$feedEdge = $response->getGraphEdge();
var_dump($response); exit;
So I'm unsure why the same token in one place would get the information when in another it would get an empty set the worst part is it's not like the Request is failing as that throws an exception it is like Facebook Graph API is reacting differently for my application when using the PHP-SDK verses using the Explorer.
So after hours of messing around testing stuff in the Graph API Explorer and the API I worked out, there is a problem with /me/posts endpoint when using the PHP SDK even if your using a manage_pages access_token it seems to lock on to the user that instead of the page unlike the graph explorer that the /me/posts, posts to the entity of the access_token.
So make sure to request /{page_id|user_id}/posts and it works correctly.

Bigcommerce customer login api (single sign-on) invalid login issue

I'm new to bigcommerce and jwt tokens. I'm trying to get the customer login api to work on a trail store. But have not been able to successfully login a customer automatically.
I got it to work once or twice, but now it doesn't work anymore, and an unable to figure out the odd behavior since nothing changed with the code. I've tried googling if anyone else has had issues with the customer login api but have found nothing.
I've gone thru the tutorial on https://developer.bigcommerce.com/api/v2/#customer-login-api and copied the example provided.
Is there something I'm missing with the code below?
I've gone to developer.bigcommerce.com and created a draft app.
I got the Client ID and Client Secret from the draft app.
I've gone into my trial store and successfully installed the draft app.
I've tested this page on SSL as well.
Could it be because it's a trail store and it will only work if it's a real store?
Thanks.
Here is the php code below:
include "vendor/autoload.php";
use Bigcommerce\Api\Client as Bigcommerce;
use Firebase\JWT\JWT;
function getCustomerLoginToken($id, $redirectUrl = '', $requestIp = '') {
/*
if (empty(self::$client_secret)) {
throw new Exception('Cannot sign customer login tokens without a client secret');
}
*/
$payload = array(
'iss' => '#MyApp1's Client ID#',
'iat' => time(),
'jti' => bin2hex(random_bytes(32)),
'operation' => 'customer_login',
'store_hash' => '#Store Hash#',
'customer_id' => $id
);
if (!empty($redirectUrl)) {
$payload['redirect_to'] = $redirectUrl;
}
if (!empty($requestIp)) {
$payload['request_ip'] = $requestIp;
}
return JWT::encode($payload, "#MyApp1's Client Secret#", "HS256");
}
$jwt = getCustomerLoginToken(1);
header("Location: " . 'https://store-#Store Hash#.mybigcommerce.com/login/token/' . $jwt);
exit();
There are a couple of constraints that can cause errors:
The app must be installed on the store (seems like you're all good here - you can also test with an API token created locally in the store - https://support.bigcommerce.com/articles/Public/Store-API-Accounts/)
The app must have the Login OAuth scope
The JWT URL must be visited within about 30 seconds, or it won't work.
The computer/server that's generating the JWT needs to have a clock that's synchronized, otherwise your IAT value will appear to have been created more than 30 seconds ago or even in the future which will fail.
The URL can only be visited exactly once - if anything runs a GET request against it other than the intended end user's browser, it won't work. For example, if you send the URL in a Slack message, slack will try to preview the link by visiting it and therefore invalidate it.
It's good to double-check that your JWT is valid at https://jwt.io/
BigCommerce support has access to logs which can shed more light on the situation if you've ruled out the above.
Hope this helps!
do not need app client_id and Secret code , you need to api's client_id and secret code

Facebook Platform - Verifying Facebook User Access Token in v2.2

Question about the upgrade to v2.2 of the Facebook Platform, in particular, this part:
The previously deprecated REST API has been completely removed in
v2.1, and all apps still using it must migrate to using Graph API.
For the most part, in my Android and iOS app I am not using the REST API. I'm using the Android SDK and the iOS SDK. However, I do have one exception. When I call my server to login or really do basically anything, I try to assure that the person trying to login/access data is indeed the person they say they are. I do this:
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$response = file_get_contents("https://graph.facebook.com/debug_token?input_token=".$accessToken."&access_token=MY_APP_ACCESS_TOKEN", false, $context);
$jsonObject = json_decode($response, true);
$data = $jsonObject["data"];
$facebookId = $this->getFacebookId();
if(isset($data['is_valid']) && $data['is_valid'] === true) {
if(isset($data['user_id'])) {
if($data['user_id'] == $facebookId) {
return true;
A little bit of code missing there, but that's the gist of it. Get an access token and a facebook id. I use the access token to see if it's legitamite and the user_id assigned to that access token is the id of the person trying to get info. If so, I let them in.
My question is, am I understanding correctly that this is going away and I have to use the Graph API to somehow do the same thing? How is this done through the Graph API in PHP given an access token and facebook id from Android/iOS?
EDIT: Just realized this is actually in the 2.0 to 2.1 section, but question still stands, should I be concerned about my server side code?
Thanks!
I'm thinking I don't have anything to worry about. The approach I'm using is in the Facebook Platform docs here:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2#checktoken
Under inspecting access tokens. Nothing on this page talks about it being deprecated.

graph api notifications returns empty data

im building a facebook app and i want to notify the user
https://developers.facebook.com/docs/games/notifications
im using facebook php sdk
what i do:
user auths the app and accepts permission
i get the accesstoken like:
$facebook->getAccessToken()
and then i generate a long-time token like:
public function generateLongTimeToken($token){
$long_time_token_req_body = array(
"grant_type"=>"fb_exchange_token",
"client_id"=>$this->facebookOptions["appId"],
"client_secret"=>$this->facebookOptions["secret"],
"fb_exchange_token"=>$token
);
$query = http_build_query($long_time_token_req_body);
$lttreq = file_get_contents("https://graph.facebook.com/oauth/access_token?".$query);
$lttresp = parse_str($lttreq, $output);
if ( array_key_exists("access_token", $output)){
$this->logger->info("Facebook-app: Successfuly generated long_time_token");
return $output["access_token"];
}else {
$this->logger->err("Facebook-app: generating oauth long_time_token failed \n".$lttreq);
return false;
}
}
some later i use this token for background processes to post on the users wall and them all work fine
now i also want to notificate the user like that :
public function notifyUser($message,$facebookClientId,$token){
$appsecret_proof= hash_hmac('sha256', $token, $this->facebookOptions["secret"]);
$req_body = array(
"access_token"=>$token,
"appsecret_proof"=>$appsecret_proof,
"href"=>"/index",
"template"=>$message,
"ref"=>"post"
);
$query = http_build_query($req_body);
$url = "https://graph.facebook.com/".$facebookClientId."/notifications?".$query;
$lttreq = file_get_contents($url);
return $lttreq;
}
but when i try to notify the user i always get empty data back
when i open the url in browser with all parameters facebook returns the same
{
data: [ ]
}
so i have no idea whats going on,when i look on SO i only find about people posting to sites but i want to notify the user itself
thanks for any help
First, from the Facebook docs:
Currently, only apps on Facebook.com can use App Notifications.
Notifications are only surfaced on the desktop version of
Facebook.com.
Also, an App Token is needed, not a User Token.
Btw, file_get_contents is very bad, use CURL for Facebook. May be another reason why it does not work. A basic example of using CURL with the Facebook API: http://www.devils-heaven.com/extended-page-access-tokens-curl/
Additional Info: I recently wrote a blogpost about App Notifications, it is in german but the small code part may be interesting for you: http://blog.limesoda.com/2014/08/app-notifications-facebook-apps/

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

Categories