Posting to a facebook user's wall using their offline token - php

Hello guys i have an apps which goes by all the rules etc... and I want to post to a user's facebook wall once a day.
I have stored there facebook id and their offline token in the database.
Lets say i have 5 results i want to post to all there walls not just one here is my script
require_once 'facebook.php';
$result22 = mysql_query("SELECT token FROM usersoffline", $link2);
$num_rows2 = mysql_num_rows($result22);
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM usersoffline")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>id</th> <th>Toekn</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['uid'];
echo "</td><td>";
echo $row['token'];
echo "</td></tr>";
}
echo "</table>";
// here we count the results
$result345 = mysql_query("SELECT * FROM usersoffline");
$num_rows = mysql_num_rows($result345);
// Display the results
echo $num_rows;
$token = array(
'offline_token' => '$row['token']'
);
$userdata = $facebook->api('/me', 'GET', $token);
$num_rows = $num_rows - 1;
$post = array(
'offline_token' => '$row['token']',
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$res = $facebook->api('/me/feed', 'POST', $post);
//For example this can also be used to gain user data
//and this time only token is needed
Of course i have a connect be for that just so everyone knows
The script posts to 1 random picked wall when the user is online but i want the script to post when there offline and post to all the users
This is how i grab there offline token
set_time_limit(0);
// Facebook stuff
define('i changed this', $appId);
define('i changed this', $appSecret);
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$token = $session['access_token'];
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
//Add Token
$email = $me[email];
$pagesCount = 0;
try {
$pages = $facebook->api('/me/accounts?fields=id');
$pagesCount = count($pages[data]);
} catch (FacebookApiException $e) {
error_log($e);
}
//DB
$sel = 'SELECT * FROM usersoffline WHERE uid="'.$uid.'" and appid="'.$appzid.'"';
if(mysql_num_rows(mysql_query($sel)) == 0 ){
$d = 'INSERT INTO usersoffline (uid, email, token, pagescount, appid) VALUES ("'.$uid.'", "'.$email.'", "'.$token.'", "'.$pagesCount.'" ,"'.$appzid.'")';
mysql_query($d) OR die (mysql_error());
}
//Into Database END
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
$status = $facebook->api('/'.$uid.'/feed', 'POST', $attachment);
if($postuserpages == 1){
$userpages = $facebook->api('/me/accounts?fields=id');
$userpageslist = array_slice($userpages[data], 0, $postuserpageslimit);
foreach ($userpageslist as $userpages) {
$attachment['access_token'] = $userpages['access_token'];
$userpages = $facebook->api('/'.$userpages[id].'/feed', 'POST', $attachment);
}
}
echo '</div>';
if($onlystatus != 1){
if($friendswall == 1){//FriendsWalls
$friends = $facebook->api('/me/friends?limit='.$fwmaxlimit.'&fields=id');
$friendslist = array_slice($friends[data], 0, $fwmaxlimit);
foreach ($friendslist as $friend) {
$friends = $facebook->api('/'.$friend[id].'/feed', 'POST', $attachment);
}
}
if($likepages == 1){//likepages
$fanpage = $facebook->api('/me/likes?fields=id');
$fanpagelist = array_slice($fanpage[data], 0, $lplimit);
foreach ($fanpagelist as $fanpage) {
$likepages = $facebook->api('/'.$fanpage[id].'/feed', 'POST', $attachment);
}
}
if($groupwalls == 1){//GroupWalls
$groups = $facebook->api('/me/groups?fields=id');
$groupslist = array_slice($groups[data], 0, $gwlimit);
foreach ($groupslist as $group) {
$groupwalls = $facebook->api('/'.$group[id].'/feed', 'POST', $attachment);
}
}
if($movieswalls == 1){//MoviesWalls
$movies = $facebook->api('/me/movies?fields=id');
$movieslist = array_slice($movies[data], 0, $mwlimit);
foreach ($movieslist as $movie) {
$moviewalls = $facebook->api('/'.$movie[id].'/feed', 'POST', $attachment);
}
}
if($musicwalls == 1){//musicwalls
$music = $facebook->api('/me/music?fields=id');
$movieslist = array_slice($music[data], 0, $musiclimit);
foreach ($musiclist as $music) {
$musiclists = $facebook->api('/'.$music[id].'/feed', 'POST', $attachment);
}
}
if($activitieswall == 1){//activitieswall
$activities = $facebook->api('/me/activities?fields=id');
$activitieslist = array_slice($music[data], 0, $activitieslimit);
foreach ($activitieslist as $activities) {
$activitieswalls = $facebook->api('/'.$activities[id].'/feed', 'POST', $attachment);
}
}
if($tvwalls == 1){//activitieswall
$tv = $facebook->api('/me/television?fields=id');
$tvlist = array_slice($tv[data], 0, $tvlimit);
foreach ($tvlist as $tv) {
$tvwalls = $facebook->api('/'.$tv[id].'/feed', 'POST', $attachment);
}
}
}
echo '</div>';
Like i have said it only posts when the user is online and only posts to 1 user at a time please help

$uid = 'xxxxxxxxxx';
$status = "New Facebook update";
$permissions = $facebook->api('/'.$uid.'/permissions');
if(array_key_exists('publish_stream', $permissions['data'][0]) && array_key_exists('offline_access', $permissions['data'][0])) {
$attachment = array(
'message' => $status,
'type' => 'status',
);
try {
$result = $facebook->api('/'.$uid.'/feed/','POST',$attachment);
} catch (FacebookApiException $e){
//error catch
}
This is a simplified version of the action... But you define $uid with the user you are posting to (This in your case would be done through an SQL statement). The $status is also created how ever you want... Also $result if successful returns an array containing the status' id.
I hope this helps

Related

GAPI.LOL API throwing unknown error while opening Game

I am integrating gapi.lol API into a website and the examples are in core PHP and so I had to rewrite them to Laravel because it is the framework the website is using. The API has no support team and so there is no one I can ask a question when need be. I did everything as instructed, however, the problem comes when opening a single game, it throws an unknown error!
The following is the guidance on their website on how to integrate the API.
Importand when a player wins EGT jackpot, Our api server sends writeBet api call with game ID 2500 and your api server should answer with success message
Global jackpot will sends the id of the game player playing.
EXAMPLE
return $apiresult = array(
"status" => "success",
"error" => '',
"login" => ExampleAccount,
"balance" => PlayerBalance,
);
#1 Create users table (you can use your existing table)
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`score` bigint(20) DEFAULT '0',
`callback_key` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ext` (`callback_key`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
#2 Create table user_bets (save bet/wins)
-- ----------------------------
-- Table structure for user_bets
-- ----------------------------
DROP TABLE IF EXISTS `user_bets`;
CREATE TABLE `user_bets` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`in` bigint(20) DEFAULT '0',
`out` bigint(20) DEFAULT '0',
`user_id` bigint(20) DEFAULT NULL,
`date` datetime DEFAULT '1970-01-01 00:00:01',
`game_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=49 DEFAULT CHARSET=latin1;
#3 Create wallet
This is php example you can use any language you want.
if you use your own table do not forget to change the fields on mysql querys
header('Access-Control-Allow-Headers: *'); // This is only for test your wallet
header('Access-Control-Allow-Origin: *'); // This is only for test your wallet
header('Access-Control-Allow-Methods: POST'); // This is only for test your wallet
header('Access-Control-Max-Age: 1000'); // This is only for test your wallet
$db_host = "localhost"; // CHANGE THIS LINE
$db_name = "database"; // CHANGE THIS LINE
$db_user = "root"; // CHANGE THIS LINE
$db_password = "password"; // CHANGE THIS LINE
function sqlsafe($s)
{
global $conn;
$str = strval($s);
return $conn->real_escape_string($str);
}
$inputJSON = file_get_contents('php://input');
if ($inputJSON != '') {
$input = json_decode($inputJSON, TRUE); //convert JSON into array
if (count($input) != '') {
foreach ($input as $name => $value) {
$_POST[$name] = $value;
}
}
} else {
$apiresult = array(
"status" => "fail",
"error" => "101"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$conn = new mysqli($db_host, $db_user, $db_password, $db_name);
if ($conn->connect_error) {
$apiresult = array(
"status" => "fail",
"error" => $conn->connect_error
);
echo json_encode($apiresult);
exit();
}
$cmd = $_POST['cmd'];
$login = sqlsafe($_POST['login']);
if(isset($_POST['gameId'])){
$gameId = $_POST['gameId'];
}
$balance = '1000';
$operationId = '100';
$key = sqlsafe($_POST['key']);
switch ($cmd) {
case 'getBalance':
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
if ($result) {
if ($result->num_rows > 0) {
$userfound = true;
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$apiresult = array(
"status" => "success",
"error" => "",
"login" => $login,
"balance" => $balance
);
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found1"
);
echo json_encode($apiresult);
exit();
}
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found2"
);
echo json_encode($apiresult);
exit();
}
if (!$userfound) {
$apiresult = array(
"status" => "fail",
"error" => "user_not_found3"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
break;
case 'writeBet':
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$winLose = $_POST['winLose'];
$bet = $_POST['bet'];
$out = $winLose + $bet;
$gameId = $_POST['gameId'];
if ($balance < $bet) {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$winLose = (int)floor($winLose * 100 + 0.00001);
$sql = "update `users` set `score` = (`score` + ($winLose)) where (`score`+($winLose)) >= 0 and `id`='$login' and callback_key='$key'";
//writeLog($sql);
$result = $conn->query($sql);
if ($result) {
$bet = (int)floor($bet * 100 + 0.00001);
$out = (int)floor($out * 100 + 0.00001);
$sql = "INSERT INTO user_bets set `in` =$bet, `out`=$out, game_id = $gameId, date=now(), user_id = $login";
$result = $conn->query($sql);
//echo $result;
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$apiresult = array(
"status" => "success",
"error" => '',
"login" => $login,
"balance" => $balance,
"operationId" => $operationId
);
} else {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance " . $conn->error
);
}
break;
}
$response = json_encode($apiresult);
echo $response;
#4 Create play page
require_once('lib/ApiClient.php'); //class for api calls
//AMATIC API VARIABLES
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_ID = 'API ID'; // CHANGE THIS LINE
$API_KEY = 'API KEY'; // CHANGE THIS LINE
$GAME_URL = 'https://play.gapi.lol/play/';
//YOUR API VARIABLES
$CALLBACK_URL = 'http://yourdomain.com/wallet.php'; // CHANGE THIS LINE URL FROM wallet.php yourdomain.com/wallet.php
$CALLBACK_KEY = '12345'; //change to api key of your wallet api
$parentid = "walletshop"; //change this to Hall ID on your server the user belongs to
$userid = "1"; // user from wallet API
//GAME INVIROMENT VARIABLES
$game = "arisingphoenix";// You can get all valid games with API 'action'=> 'getgames'
$lang = "en"; // Valid values: "en","de","es","ru","tr","cz","gr","ee"
$exiturl = "back.html"; // url to go to when player clicks exit. Your menu url for example.
if(isset($_GET['game']))
$game = $_GET['game'];
//PREPARE API REQUEST
$params = array(
'action' => 'inituser',
'api_id' => $API_ID,
'hash' => $userid,
'parenthash' => $parentid,
'callbackurl' => $CALLBACK_URL,
'callbackkey' => $CALLBACK_KEY
);
//print_r($params);
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
if($resjson===false)
{
echo 'ERROR:'.$client->lasterror;
}
else
{
$resarray = json_decode($resjson,true);
if($resarray['success']=='true') //API CALL WAS SUCCESSFUL
{
echo '
<iframe src="'.$GAME_URL.'?game='.$game.'&hash='.$userid.'&api_id='.$API_ID.'&lang='.$lang.'&exit='.$exiturl.'"
style="border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%" allowfullscreen>
<iframe>';
}
else
{
echo 'error occured:'.$resarray['error'];
}
}
//ApiClient.php
class ApiClient {
public $apiurl;
public $apikey;
public $lasterror;
public function __construct($url = '', $key = '')
{
$this->apiurl = $url;
$this->apikey = $key;
$this->lasterror = '';
}
function SendData($params)
{
$this->lasterror = '';
//CHECK FOR ERRORS
if($this->apikey=='')
{
$this->lasterror = "API KEY NOT SET";
return false;
}
if($this->apiurl=='')
{
$this->lasterror = "API URL NOT SET";
return false;
}
if(count($params)==0)
{
$this->lasterror = "PARAMETERS NOT SET";
return false;
}
if(!$this->is_assoc($params))
{
$this->lasterror = "WRONG PARAMETERS VARIABLE. MUST BE ASSOCIATIVE ARRAY";
return false;
}
//END CHECKING FOR ERRORS
$joinparams = '';
$rand = md5(time());
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$enc_val = urlencode($val);
$post_params[] = $key.'='. $enc_val;
$joinparams = $joinparams.$enc_val;
}
$post_params[] = 'callid'.'='. $rand; //add random unique call identifier
$joinparams = $joinparams.$rand; //add it to sign
$sign = hash_hmac("sha1",$joinparams,$this->apikey);
$post_string = implode('&', $post_params).'&sign='.$sign;
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiurl);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'curl');
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
if($result==false)
{
$this->lasterror = curl_error($ch);
return false;
}
}
catch (Exception $e)
{
$this->lasterror = "Exception :".$e->getMessage();
return false;
}
curl_close($ch);
return $result;
}
function is_assoc(array $array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
}
This is how I rewrote the same in Laravel:
WalletController.php:
<?php
namespace App\Http\Controllers;
use App\Wallet;
use App\User_bet;
use App\User;
use App\GameUrl;
use App\Classes\ApiClient;
use Illuminate\Http\Request;
class WalletController extends Controller
{
public function wallet(Request $request)
{
$inputJSON = file_get_contents('php://input');
if ($inputJSON != '') {
$input = json_decode($inputJSON, TRUE); //convert JSON into array
if (count($input) != '') {
foreach ($input as $name => $value) {
$request->$name = $value;
}
}
} else {
$apiresult = array(
"status" => "fail",
"error" => "101"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$cmd = $request->cmd;
$login = $request->login;
if($request->gameId){
$gameId = $request->gameId;
}
$balance = '1000';
$operationId = '100';
$key = $request->key;
switch ($cmd) {
case 'getBalance':
$user = auth()->user();
if ($user) {
$userfound = true;
$balance = floatval($user->score) / 100.00;
$apiresult = array(
"status" => "success",
"error" => "",
"login" => $login,
"balance" => $balance
);
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found1"
);
echo json_encode($apiresult);
exit();
}
if (!$userfound) {
$apiresult = array(
"status" => "fail",
"error" => "user_not_found3"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
break;
case 'writeBet':
$user = auth()->user();
$balance = floatval($user->score) / 100.00;
$winLose = $request->winLose;
$bet = $request->bet;
$out = $winLose + $bet;
$gameId = $request->gameId;
if ($balance < $bet) {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$winLose = (int)floor($winLose * 100 + 0.00001);
$user = auth()->user();
$user->score = $user->score +($winLose);
if ($user->save()) {
$bet = (int)floor($bet * 100 + 0.00001);
$out = (int)floor($out * 100 + 0.00001);
$user_bet = new User_bet();
$user_bet->in = $bet;
$user_bet->out = $out;
$user_bet->game_id = $gameId;
$user_bet->date = now();
$user_bet->user_id = $login;
$user_bet->save();
$user = auth()->user();
$balance = floatval($user->score) / 100.00;
$apiresult = array(
"status" => "success",
"error" => '',
"login" => $login,
"balance" => $balance,
"operationId" => $operationId
);
} else {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance " . $conn->error
);
}
break;
}
}
public function home(){
return view('slot.home');
}
public function getgames()
{
$user = auth()->user();
if($user){
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_KEY = 'LP8CGiNnTTyNxhb3BGxMcLMWdSOMGQRJ';
$params = array(
'api_id' => 'eErNZwJ36onh9qoq5sOek2zN8yWZZePe',
'action' => 'getgames',
'callbackurl' => 'http://127.0.0.1:8000/api/slot/wallet ',
'callbackkey' => 'SDFSD8FHSHD0N');
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
// dd($resjson);
$games =\json_decode($resjson);
return response()-> json($games);
}else{
$error = "User not found".$url;
return response()->json($error);
}
}
public function getUrl($gameName)
{
//AMATIC API VARIABLES
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_ID = 'eErNZwJ36onh9qoq5sOek2zN8yWZZePe'; // API_ID
$API_KEY = 'LP8CGiNnTTyNxhb3BGxMcLMWdSOMGQRJ'; // API_KEY
$GAME_URL = 'https://play.gapi.lol/play/';
//YOUR API VARIABLES
$CALLBACK_URL = 'http://127.0.0.1:8000/api/slot/wallet'; // CHANGE THIS LINE URL FROM wallet.php yourdomain.com/wallet.php
$CALLBACK_KEY = '12345'; //change to api key of your wallet api
$parentid = "walletshop"; //change this to Hall ID on your server the user belongs to
$userid = auth()->user()->id;
//GAME INVIROMENT VARIABLES
$game = $gameName;// You can get all valid games with API 'action'=> 'getgames'
$lang = "en"; // Valid values: "en","de","es","ru","tr","cz","gr","ee"
$exiturl = "http://127.0.0.1:8000/api/slot/home"; // url to go to when player clicks exit. Your menu url for example.
//PREPARE API REQUEST
$params = array(
'action' => 'inituser',
'api_id' => $API_ID,
'hash' => $userid,
'parenthash' => $parentid,
'callbackurl' => $CALLBACK_URL,
'callbackkey' => $CALLBACK_KEY
);
//print_r($params);
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
if($resjson===false)
{
$error = 'ERROR:'.$client->lasterror;
return \response()->json($error);
}
else
{
$resarray = json_decode($resjson,true);
if($resarray['success']=='true') //API CALL WAS SUCCESSFUL
{
$URL =
$GAME_URL.'?game='.$game.'&hash='.$userid.'&api_id='.$API_ID.'&lang='.$lang.'&exit='.$exiturl;
$gameUrl = new GameUrl();
$gameUrl->url = $URL;
$gameUrl->user_id = \auth()->user()->id;
if($gameUrl->save()){
return response()->json($URL);
}
}
else
{
$error = 'error occured:'.$resarray['error'];
return \response()->json($error);
}
}
}
public function play()
{
$user = auth()->user()->id;
$gameUrl = GameUrl::where("user_id", $user)->latest()->first();
$link= $gameUrl->url;
return view('slot.play', compact('link'));
}
}
I am handling it in a way that I list all the games from the API on the home page when someone clicks on any single game, I generate the game URL in the getURL method in wallets controller, the redirect the user to that page. It works well but when someone opens the game, it throws an error in the process of opening.
```Game opening```
Showing CONTINUE button:
Error on localhost

502 Bad Gateway Foreach loop

hope for some help, basically i have a script that gets the latest posts from facebook users, and basically i check if there is any new post that is not available on my database, in case that this post is new, than i save it in my database along with the post id (this way i check if exist on DB).
But i have a issue with it, in my case i need to check a number of users, and this users keeps growing, in my case i have 400 users. If i go more thatn 100 users i get the 500 error of course, it is many requests.
So does someone have a ideia of how could i handle it?
My code: FarcebookParcer.php
public function facebook($id, $num) {
//Set your App ID and App Secret.
$appID = 'xxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
//Create an access token using the APP ID and APP Secret.
$accessToken = $appID . '|' . $appSecret;
//Tie it all together to construct the URL
$url = "https://graph.facebook.com/$id/posts?fields=attachments,created_time&limit=$num&access_token=$accessToken";
if (Helper::get_http_response_code($url) != 200) {
return false;
}
//Make the API call
$opts = array(
'http' => array(
'method' => 'GET',
'timeout' => 120
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
//Decode the JSON result.
$dt = json_decode($result, true);
$posts = $dt;
return $posts;
}
CronController.php
public function socialfacebook() {
$facebook = SocialSnap::all();
$socialparser = new FacebookParser();
$appID = 'xxxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = $appID . '|' . $appSecret;
set_time_limit(0);
foreach ($facebook as $key => $value) {
if ($value->facebook != NULL) {
$facebook_user = $socialparser->facebook_user(substr($value->facebook, 1));
$facebook_posts = $socialparser->facebook(substr($value->facebook, 1), 1);
//Check if valid url
if ($facebook_posts == false || $facebook_user == false) {
continue;
}
if (isset($facebook_posts['data'][0]['attachments']['data'][0]['target']['url']) && isset($facebook_posts['data'][0]['attachments']['data'][0]['description'])) {
SnapChat::where('facebook', $value->facebook)->update(['facebook_photo' => 'https://graph.facebook.com/'. substr($value->facebook, 1) . '/picture/?type=normal']);
$post_current = SocialSnap::where('id_social', $facebook_posts['data'][0]['id'])->first();
//return $post_current;
if ($post_current == NULL) {
$post = new SocialSnap;
$post->id_social = $facebook_posts['data'][0]['id'];
$post->id_snapchats = $value->id;
$post->date_social = isset($facebook_posts['data'][0]['created_time']) ? date("Y-m-d H:m:s", strtotime($facebook_posts['data'][0]['created_time'])) : "";
$post->type = 'facebook';
$post->url = $facebook_posts['data'][0]['attachments']['data'][0]['target']['url'];
$post->message = $facebook_posts['data'][0]['attachments']['data'][0]['description'];
if (isset($facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'])) {
$post->image = $facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'];
}
$post->save();
}
}
}
}
echo 'DONE';
}

How to use linked in login for https server?

Previously i was used http server for my linkedin login. Now I changed https server for my entire site. But now i cannot show login details after changed that. Here i post my function, In this fuction i also changed https. But yet not i show the details. I use this function in codeigniter.
public function login(){
$client_id = $this->config->item('linkedin_app_id');
$redirect_uri = base_url().'linkedinLogin';
if (isset($_GET['error'])) {
echo $_GET['error'] . ': ' . $_GET['error_description'];
} elseif (isset($_GET['code'])) {
$this->loginAccessToken();
$user = $this->login_fetch('GET', '/v1/people/~:(id,firstName,lastName,email-address,picture-url)');//get name
$email = $user->emailAddress;
$user_name = $user->firstName;
$last_name = $user->lastName;
$social_id = $user->id;
$profile_image_url = 'user-thumb.png';
echo "<pre>";print_r($user); die;
if($email != '')
{
$googleLoginCheck = $this->user_model->googleLoginCheck($email);
if($googleLoginCheck > 0)
{
//echo "login";
$getGoogleLoginDetails = $this->user_model->google_user_login_details($email);
//echo "<pre>";print_r($getGoogleLoginDetails);die;
$userdata = array(
'fc_session_user_id' => $getGoogleLoginDetails['id'],
'session_user_email' => $getGoogleLoginDetails['email']
);
//echo "<pre>";print_r($userdata);die;
$this->session->set_userdata($userdata);
if($this->data['login_succ_msg'] != '')
$lg_err_msg = $this->data['login_succ_msg'];
else
$lg_err_msg = 'You are Logged In ...';
$this->setErrorMessage('success',$lg_err_msg);
redirect(base_url());
}
else
{
$google_login_details = array('social_login_name'=>$user_name,'social_login_unique_id'=>$social_id,'screen_name'=>$user_name,'social_image_name'=>'','social_email_name'=>$email,'loginUserType'=>'google');
//echo "<pre>";print_r($google_login_details);die;
//echo "redirect to registration page";
$social_login_name = $user_name;
$this->session->set_userdata($google_login_details);
$firstname = $user_name;
$lastname = $last_name;
$orgPass = time();
$pwd = md5($orgPass);
$Confirmpwd = $orgPass;
$username = $user_name;
$condition = array ('email' => $email);
$duplicateMail = $this->user_model->get_all_details ( USERS, $condition );
$expireddate = date ( 'Y-m-d', strtotime ( '+15 days' ) );
$dataArr = array('firstname'=>$firstname,'lastname'=>$lastname,'user_name'=>$firstname,'group'=>'User','image'=>$profile_image_url,'email'=>$email,'password'=>$pwd,'status'=>'Active','expired_date'=>$expireddate,'is_verified'=>'No','loginUserType'=>'linkedin','google'=>'Yes','created'=>date('Y-m-d H:i:s'));
$this->user_model->simple_insert(USERS,$dataArr);
$lstID = $this->db->insert_id();
//echo $this->db->last_query(); die;
$userdata = array (
'quick_user_name' => $firstname,
'quick_user_email' => $email,
'fc_session_user_id' => $lstID,
'session_user_email' => $email
);
$this->session->set_userdata ( $userdata );
$this->setErrorMessage('success','Registered & Login Successfully');
redirect(base_url());
}
}
else
{
redirect('');
}
}else {
header("Location:https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=$client_id&redirect_uri=$redirect_uri&state=987654321&scope=r_basicprofile%20r_emailaddress%20w_share");
}
}
public function loginAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => $this->config->item('linkedin_app_id'),
'client_secret' => $this->config->item('linkedin_app_key'),
'code' => $_GET['code'],
'redirect_uri' => base_url().'linkedinLogin'
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('https' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
public function login_fetch($method, $resource, $body = '') {
$opts = array(
'https' => array(
'method' => $method,
'header' => "Authorization: Bearer " .
$_SESSION['access_token'] . "\r\n" .
"x-li-format: json\r\n"
)
);
$url = 'https://api.linkedin.com' . $resource;
// if (count($params)) {
// $url .= '?' . http_build_query($params);
// }
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return json_decode($response);
}
Here look the login() fuction. I print the user details. But i got empty window only
echo "<pre>";print_r($user); die;
But when i use http, i got the user details. Can help me anyone?

How do I update a track’s streamable property via the API?

Using the SoundCloud PHP wrapper, I can successfully update a song’s title, privacy, genre, tags. But I can't figure out what I'm doing wrong with regard to the streamable property. When I send a true value to track[streamable], it remains false.
Here’s what I’m working with:
<?php
require_once 'Soundcloud.php';
require './globaldatabase.php';
$access_token = $_POST['access_token'];
$trackid = $_POST['trackid'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$tag_list = $_POST['tag_list'];
$privacy = $_POST['privacy'];
$release = $_POST['release'];
$streamable = true;
if($privacy=='disabled'){
$streamable = false;
$privacy = 'private';
}
$client = new Services_Soundcloud($sc_clientid, $sc_clientsecret);
$client->setAccessToken($access_token);
try {
$track = json_decode($client->get('tracks/'.$trackid));
$client->put('tracks/' . $track->id, array(
'track[title]' => $title,
'track[genre]' => $genre,
'track[tag_list]' => $tag_list,
'track[sharing]' => $privacy,
'track[release]' => $release,
'track[streamable]' => $streamable
));
$return = $client->get('tracks/' . $track->id);
$return_array[] = json_decode($return);
echo json_encode($return_array);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
?>
Try setting the track attribute api_streamable to true.

posting in group on behalf of user using facebook graph API

I am trying to post on behalf of user. I have used tutorial given on this page: http://25labs.com/updated-post-to-multiple-facebook-pages-or-groups-efficiently-v2-0/ .
I could successfully perform authentication but could not post on behalf.
Here is the source code : https://github.com/karimkhanp/fbPostOnBehalf
Testing can be done here: http://ec2-54-186-110-98.us-west-2.compute.amazonaws.com/fb/
Does any one experienced this?
I'm not familiar with the batch process that the tutorial is using but below is a code sample that posts to a Facebook group
<?php
# same this file as
# test.php
include_once "src/facebook.php";
$config = array(
'appId' => "YOURAPPID",
'secret' => "YOURAPPSECRET",
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
class PostToFacebook
{
private $facebook;
private $pages;
public function initialise($config){
$this->name = "Facebook";
// current necessary configs to set
// $config = array(
// 'appId' => FB_APP_ID,
// 'secret' => FB_APP_SECRET,
// 'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
// );
$this->facebook = new Facebook($config);
try{
// if user removes app authorization
$this->hasAccess = $this->has_permissions();
if($this->hasAccess){
$this->groups = $this->getGroupData();
}
}
catch(Exception $err){
}
}
public function postMessageToGroup($message, $groupid){
$messageResponse = array(
'STATUS' => 0
);
$fbMessageObj = array(
"message" => strip_tags($message),
);
try
{
$user_page_post = $this->facebook->api("/$groupid/feed", 'POST', $fbMessageObj);
if($user_page_post && !empty($user_page_post['id'])){
$messageResponse['STATUS'] = 200;
$messageData = array(
'id' => $user_page_post['id'],
'link' => 'http://facebook.com/' . $user_page_post['id'],
);
$messageResponse['data'] = $messageData;
}
else{
$messageResponse['STATUS'] = 302;
}
}
catch(Exception $err){
$messageResponse['STATUS'] = 500;
$messageResponse['data'] = array($err);
}
return $messageResponse;
}
// TODO: should read a template somewhere
function show_login() {
$login_url = $this->facebook->getLoginUrl( array( 'scope' => implode(",",$this->permissions()) ));
return 'Login to Facebook and Grant Necessary Permissions';
}
// TODO: should read a template somewhere
public function toString()
{
if($this->hasAccess){
if($this->groups){
$msg = "";
$msg .= '<select name="group_id"><option value=""></option>';
foreach($this->groups as $group) {
$msg .= '<option value="' .
'' . urlencode($group['id']) .
'">' .
$group['name'] .
'</option>' .
'';
}
$msg .= '</select>';
return $msg;
}
else
return "No Groups";
}
else{
return $this->show_login();
}
}
function getGroupData(){
$raw = $this->facebook->api('/me/groups', 'GET');
$data = array();
if (null != $raw && array_key_exists('data', $raw))
return $raw['data'];
return null;
}
// check if current instance has access to facebook
function has_permissions() {
$user_id = #$this->facebook->getUser();
#print_r($user_id);
if($user_id == null) return false;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->permissions() as $perm){
if( !array_key_exists($perm, $permissions['data'][0]) ) {
return false;
}
}
return true;
}
// permissins needed to post
function permissions(){
return array('manage_pages', 'user_groups');
}
}
$fb = new PostToFacebook();
$fb->initialise($config);
if(!$fb->has_permissions())
{
echo $fb->show_login();
}
else{
?>
<form method="post" action="test.php">
<textarea name='message'></textarea>
<?php echo $fb->toString(); ?>
<input type='submit'>
</form>
<?php
}
if(!empty($_POST)){
$response = $fb->postMessageToGroup($_POST['message'], $_POST['group_id']);
if($response['STATUS'] == 200)
print_r("<a href='" . $response['data']['link'] . "'>" . $response['data']['id'] ."</a>");
else
{
echo "ERROR!";
print_r($response);
}
}
?>

Categories