Authentication useing PHP SDK not working - authentication

I am having some trouble with authentication using PHP SDK. I have downloaded "facebook.php" and "base_facebook.php" from github.
Below is the code I am useing but cant figure out where I am going wrong (new to all this).
<?php
require 'facebook.php' ;
$fbconfig['appid' ] = xxx;
$fbconfig['secret'] = "xxxx";
$fbconfig['baseurl'] = "xxx";
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($params​);
$logoutUrl = $facebook->getLogoutUrl();
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
exit();
}
else
{
echo "<p style=\"margin-bottom:20px;\">​<a href=\"{$logoutUrl}\">Logout</​p>\n";
}
?>
Any suggestions much appriciated :)

Based on this site, it looks like you need to explicitly construct your own Facebook object:
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);

Related

Gate.io PHP API create order problem => Signature mismatch

I'm not an expert in API development or using signed messages in PHP.
I have however tried to get the GATE.IO v4 API working in my PHP implementation but keep getting "Signature mismatch". I have followed the API documentation for CREATE ORDER available at Gate.io's website here: https://www.gate.tv/docs/developers/apiv4/#create-an-order
I have managed to get the /spot/accounts working, so I know that the key and secret are correct.
Based on the code below I seem to missing something. Probably a tiny error but those are the hardest, right?
Does anyone have any idea what could be the cause of this issue? Would really appreciate your help after having spent 8+ hours trying to get this to work.
<?php
$accessToken = ''; // Access token for OAuth/Bearer authentication
$key = "XXXXXXXXXXXXXXXXXXXXXXX";
$secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$username = ''; // Username for HTTP basic authentication
$password = ''; // Password for HTTP basic authentication
$host = 'https://api.gateio.ws/api/v4'; // The host
$userAgent = 'OpenAPI-Generator/5.26.0/PHP'; // User agent of the HTTP request, set to "OpenAPI-Generator/{version}/PHP" by default
$sResourcePath = "/spot/orders";
$sMethod = "POST"; // POST or GET
$aPayload['currency_pair'] = "DOT_USDT";
$aPayload['price'] = "6.330033";
$aPayload['account'] = "spot";
$aPayload['side'] = "buy";
$aPayload['amount'] = "1";
$aPayload['time_in_force'] = "gtc";
$sBody = json_encode($aPayload);
$aQueryParams = $aPayload;
$aFullPath = parse_url($host . $sResourcePath);
$fullPath = $aFullPath['path'];
$timestamp = time();
$hashedPayload = hash("sha512", ($payload !== null) ? $payload : "");
$fmt = "%s\n%s\n%s\n%s\n%s";
$sQuery = http_build_query($aQueryParams, false);
$signatureString = sprintf($fmt, $sMethod, $fullPath, $sQuery, $hashedPayload, $timestamp);
$signature = hash_hmac("sha512", $signatureString, $secret);
$aSignHeaders = array(
"KEY" => $key,
"SIGN" => $signature,
"Timestamp" => $timestamp);
$aHeaders[] = "KEY: " . $aSignHeaders['KEY'];
$aHeaders[] = "SIGN: " . $aSignHeaders['SIGN'];
$aHeaders[] = "Timestamp: " . $aSignHeaders['Timestamp'];
$aExtraParams['sHttpHeaders'] = $aHeaders;
if ($sMethod == "POST")
{
$sParams = "?" . http_build_query($aQueryParams, false);
}
else
{
$sQuery = "";
}
$sSubmitUrl = $host . $sResourcePath . $sParams;
$sPage = CURL::doRequest($sMethod, $sSubmitUrl, $sParams, $aExtraParams);
$aPage = json_decode($sPage, true);
if ($aPage)
{
$iPage = count($aPage);
}
echo "<pre>";
print_r($aPage);
echo "</pre>";
?>
based on that example request, you should be doing something like this
//path & urls
$host = 'https://api.gateio.ws';
$prefix = '/api/v4';
$path = '/spot/orders';
$fullPath = "$prefix$path";
$method = 'POST';
//your API keys
$api = [
'secret' => 'xxxx'
];
// Your actual data you can easily modify
$payload = [
'currency_pair' => 'DOT_USDT',
'price' => '6.330033',
'account' => 'spot',
'side' => 'buy',
'amount' => '1',
'time_in_force' => 'gtc'
];
//Convert your data to JSON FORMAT
$jsonPayload = json_encode( $payload );
//Hash your JSON DATA
$hashJsonPayload = hash('sha512', $jsonPayload);
$timeStamp = time();
// dunno if this is required
$queryParam = '';
//Create your signature string
$signString="$method\n$fullPath\n$queryParam\n$hashJsonPayload\n$timeStamp";
//Generate the signature
$signHash = hash_hmac('sha512', $signString, $api['secret']);
// Your Actual headers
$headers = [
'Content-Type: application/json',
'Timestamp: '.$timeStamp,
'Key: '.$api['secret'],
'SIGN: '.$signHash
];
Example request using php curl
$ch = curl_init( "$host$fullPath" ); // URL to POST https://api.gateio.ws/api/v4/spot/orders
curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsonPayload ); // set json payload as body here
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); //define header here
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch)
echo '<pre>', print_r($result, 1), '</pre>';

yii2 blocking api call and giving failed to open stream: Connection timed

I need to call a private api in my app. the call works fine using php script.php.
However, when i copy the same php code into an action of a yii controller it gives me an error
failed to open stream: Connection timed
i tried removing the behaviors and other configurations to have a basic yii environment
anyone has an idea why this is happening?
here is some code
public function actionInfo() {
$url = "private url";
$data = array();
$data['function'] = "Getinfo";
$data['login'] = "login";
$data['password'] = "password";
$data['input'] = "data";
$post = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded",
'method' => "POST",
'content' => $post,
),
);
$context = stream_context_create($options);
$resultat = "";
if (!$resultat = file_get_contents($url, false, $context)) {
$resultat = "Echec de l'envoi de la requête";
}
$resultat = json_decode($resultat);
print_r($resultat);
echo "\r\n";
this code works fine outside yii but in this action it does not!!!!
it was a server configuration the firewall was blocking my id on the api side

Why I cannot post image through twitter api?

this is my code, i am trying to post tweet with image, but only text get posted?I really really want to post image as well. I am pulling my hair out for that, HELP!!?
<?php
error_reporting(E_ALL);
require_once('TwitterAPIExchange.php');
//echo 'start';
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
require_once('connect.php');
$recid=$_GET['recid'];
//echo $recid;
$dsn='mysql:host='.$hostname.';dbname=twitter_db';
try{
$dbh=new PDO($dsn,$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$dbh->prepare("SELECT * FROM gr_twitter WHERE recid=:recid");
$stmt->execute(array(
'recid'=>$recid
));
$foundResult=$stmt->fetchAll();
$tweetmsg=$foundResult[0]['tweet'];
$tweetImage=$foundResult[0]['tweetImageName'];
$timestamp=$foundResult[0]['sentTimestamp'];
print_r($foundResult);
$stmt2=$dbh->prepare("UPDATE gr_twitter SET sent=1 WHERE recid=:recid");
$stmt2->execute(array(
'recid'=>$recid
));
}
catch(PDOException $e){}
// Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod='POST';
////images is stored in D:\Databases\RC_Data_FMS\images\Files\images\tweetImage folder
$tweetImage='D:\Databases\RC_Data_FMS\images\Files\images\tweetImage/images.jpg';
$postfields = array(
'status' => $tweetmsg,
'media' => "#{$tweetImage}"
);
/** POST fields required by the URL above. See relevant docs as above **/
//print_r($postfields).'<br />';
$twitter = new TwitterAPIExchange($Yh_settings);
$response= $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "Success, you just tweeted!<br />";
var_dump(json_decode($response));
//////////////////////////////////////////////////////////////////////////
function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
// return array_map(__FUNCTION__, $d);
} else {
// Return array
// return $d;
}
}
?>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I recommend you to use tmhOAuth library if you want to post images that are located in your server.
Here you have an example:
<?php
require_once('./tmhOAuth.php');
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => CONSUMER_KEY,
'consumer_secret' => CONSUMER_SECRET,
'user_token' => OAUTH_TOKEN,
'user_secret' => OAUTH_TOKEN_SECRET
));
$tweetText = 'Your text here';
$imageName = 'picture.png';
$imagePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . $imageName;
$code = $tmhOAuth->request(
'POST',
$tmhOAuth->url('1.1/statuses/update_with_media'),
array(
'media[]' => "#{$imagePath};type=image/png;filename={$imageName}",
'status' => $tweetText
),
true, // use auth
true // multipart
);
?>
Hope this helps!

Authentication with PHP SDK

I am having trouble using the PHP SDK for authentication. The effect I am trying to get is whene a user visits the site if they are loged in with FB they see "Logout" which loggs them out when clicked but if they are not logged in when they arrive they should see "You need to log in with FB" which loggs them in. The effect I am currently getting is that the site displays the "You need to log in with FB" even if the user is already logged in, whene this is clicked the user is taken to facebook.com with an error message displayed reading "An error occurred. Please try later". Im sure I must be missing something in my code but cant figure out what, I am fairly new to FB development. Please see my code below. Any help much appriciated.
<?php
require_once("facebook.php");
$user = $facebook->getUser();
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
session_start();
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
}
else
{
echo "<p style=\"margin-bottom:20px;\"><a href=\"{$logoutUrl} \">Logout</p>\n";
}
?>
Try this out
<?php
require_once("facebook.php");
$user = $facebook->getUser();
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
<?php if ($user) { ?>
<p>Logout</p>
<?php } else { ?>
<p>Click here to View Your Stalker of the Day</p>
<?php } ?>
You can not call $facebook before creating the instance, This code should work:
<?php
session_start();
require_once("facebook.php");
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$user = $facebook->getUser();
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
}
else
{
echo "<p style=\"margin-bottom:20px;\"><a href=\"{$logoutUrl} }\">Logout</p>\n";
}
?>
$params = array( 'next' => 'xxx' );
is deprecated SDK, use
$params = array( 'redirect_uri' => 'xxx' );
instead.

Facebook SDK 3.1 getUser most basic code not working

I had some really complicated code, and now I've made it ridiculously simple, and it doesn't work.
Currently it simply takes me back to the page with the login URL echoed out.
Code is here:
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'sd',
'secret' => 'sda',
));
// Get User ID
$user = $facebook->getUser();
if($user) {
echo $user;
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>'http://www.facebook.com/pages/CharlesTestPage/225802194155435?sk=app_252946408094785','scope'=>'email'));
echo $loginUrl;
}
exit;
?>
Please. I have spent a whole paid work day on this now, and am at the point of crying, not only for myself but for my boss.
Cry.
Edit: OK, the weird thing is, if I have the redirect_uri set to the facebook tab, if it's not authenticated itself, then it constantly redirects in an infinite loop. However, if I remove the redire
This is what's working for me using PHP SDK 3.1.1. Try it and let us know if this works:
include('facebook.php');
session_start();
//facebook application
$config['appid' ] = "YOUR_APP_ID";
$config['secret'] = "YOUR_APP_SECRET";
$config['baseurl'] = "http://example.com/facebookappdirectory";
$config['appbaseurl'] = "http://apps.facebook.com/your-app-name";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $config['appid'],
'secret' => $config['secret'],
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('APP ERROR: '.$e);
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if (isset($_GET['code'])){
header("Location: " . $config['appbaseurl']);
exit;
}
Check for
if(isset($_GET['code'])){
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
}
Facebook return userID only after the login and that code.