I'm trying to use Facebook's PHP SDK. The code that makes a call to Facebook to retrieve user's information is saved in a file called fbcall.php. The fbcall.php page is called through an href link from another page called index.php
The Entire Code (index.php):
<?php
echo "Login Here";
?>
Index.php is also my FacebookRedirectLoginHelper redirect url.
The question I have is that I'm not seeing an output for the following statement in the fbcall.php file and I'm not sure why?
echo "Name: " . $user_profile->getName();
I get the sense that my sessions isn't initiated but I'm sure how to validate this. And if it isn't initiated then I'm not sure what i'm doing wrong considering I'm following Facebook's guidelines here (or atleast I think I am).
The Entire Code (fbcall.php):
<?php
session_start();
// Make sure to load the Facebook SDK for PHP via composer or manually
require_once 'autoload.php';
//require 'functions.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('AM USING MY APP ID HERE','AM USING MY SECRET KEY HERE');
$helper = new FacebookRedirectLoginHelper('http://localhost/facebook/index.php');
$params = array('email','public_profile', 'user_status', 'user_friends');
$loginUrl = $helper->getLoginUrl($params);
try {
$session = $helper->getSessionFromRedirect();
// var_dump($session);
} catch(FacebookRequestException $ex) {
} catch(\Exception $ex) {
}
if (isset($session)) {
var_dump($session);
}
else
{
$loginUrl = $helper->getLoginUrl();
header("location:".$loginUrl);
exit;
}
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
if(isset($session)) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
?>
Once the user grant your permissions, he/she will be redirected to index.php (because of your redirect_uri).
So there is two solutions:
- change you're redirect_uri to be fbcall.php
- move all fbcall.php logic to index.php, and change header("location:".$loginUrl); by echo "Login Here";
Related
I am following Justin Slope's API Tutorial which was made in 2020.
This is the code that I pasted with some changes on the redirect URLs and using a site that is ok with the developer website.
$creds = array(
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET,
'default_graph_version' => 'v3.2',
'persistent_data_handler' => 'session'
);
// create facebook object
$facebook = new Facebook\Facebook( $creds );
// helper
$helper = $facebook->getRedirectLoginHelper();
// oauth object
$oAuth2Client = $facebook->getOAuth2Client();
if ( isset( $_GET['code'] ) ) { // get access token
try {
$accessToken = $helper->getAccessToken();
} catch ( Facebook\Exceptions\FacebookResponseException $e ) { // graph error
echo 'Graph returned an error ' . $e->getMessage;
} catch ( Facebook\Exceptions\FacebookSDKException $e ) { // validation error
echo 'Facebook SDK returned an error ' . $e->getMessage;
}
if ( !$accessToken->isLongLived() ) { // exchange short for long
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken( $accessToken );
} catch ( Facebook\Exceptions\FacebookSDKException $e ) {
echo 'Error getting long lived access token ' . $e->getMessage();
}
}
echo '<pre>';
var_dump( $accessToken );
$accessToken = (string) $accessToken;
echo '<h1>Long Lived Access Token</h1>';
print_r( $accessToken );
} else { // display login url
$permissions = [
'public_profile',
'instagram_basic',
'pages_show_list',
'instagram_manage_insights',
'instagram_manage_comments',
'manage_pages',
'ads_management',
'business_management',
'instagram_content_publish',
'pages_read_engagement'
];
$loginUrl = $helper->getLoginUrl( FACEBOOK_REDIRECT_URI, $permissions );
echo '<a href="' . $loginUrl . '">
Login With Facebook
</a>';
}
Whenever I try to use the code this is always the output been trying for about an hour by the time this is posted
I tried changing the graph versions and double-checking redirects and I am still stumped on this.
Had to remove almost all of the stuff on the permissions 'pages_show_list' was the only thing left since the data isn't supported on the standard access on the Facebook developer website, have to get a privacy URL to get full access to all the other permissions.
I try to have an app that can pause/resume my adset (accounts owned by myself).
I get no error message(or anything) output when requesting this
$adset = new AdSet($adsetid);
$adset->campaign_status = AdSet::STATUS_ACTIVE;
try{
$adset->updateSelf();
} catch (RequestException $e) {
$response = json_decode($e->getResponse()->getBody(), true);
var_dump($response);
}
But I see that the adset status did not change.
Now, I do see that the Marketing API, Settings section shows me that the API access Level is development and the app doesn't have Ads management standard access.
When I check permissions at App review > Permissions and features it shows 'Standard access' and 'ready to use'. (however not 'Active')
And at the same time my request count and error rate in the past 30 days are acceptable.
I don't understand what is missing to make it work. Can anyone help me out?
The code I have shown in my question was based on the code I copied from the Facebook marketing API documentation.
Strangely when I simulated my request using the Graph API Explorer and hit the "Get code" button it will suggest you a different code.
When I used that code instead of the code of the marketing API docs it did seem to work just as expected.
This code worked as opposed to the code from the docs:
$adsetid = "YOUR ADSET ID";
$access_token = "YOUR ACCESS TOKEN";
try {
$response = $fb->post(
'/'.$adsetid,
array (
'fields' => 'status',
'status' => 'ACTIVE'
),
$access_token
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
There is PS script for verifying webservice and it works:
$SiteURL = "http://wsf.cdyne.com/WeatherWS/Weather.asmx?op=GetCityWeatherByZIP"
$request = [Net.HttpWebRequest]::Create($SiteURL)
try
{
#Get the response from the requst
$response = [Net.HttpWebResponse]$request.GetResponse()
Write-Host "The service is running."
$request.Abort()
}
Catch
{
Write-Warning "The service of site does not run or maybe you don't have the Credential"
}
But how I can specify query parameter, ZIP?
add a $zip parameter to get zip as an input
param($zip)
update your url to include zip when sending request
$siteURL="http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=$zip"
I am trying to do a simple soap call to a weather service and I keep getting Invalid ZIP error. Can someone tell me what I am doing wrong below is my code.
Thanks
require_once 'SOAP/Client.php';
$client = new Soap_Client('http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL');
$method = 'GetCityWeatherByZIP';
$params = array('ZIP' => '07108');
$result = $client->call($method, $params);
if (PEAR::isError($result)) {
echo $result->getMessage();
} else {
print_r($result);
}
Use PHP's in-built SOAP client. The one in PEAR was written at a time PHP did not have one itself.
Their service is no SOAP service. The wiki states:
$url = "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP";
$url .= "?ZIP=" . $this->ZipCode;
$this->response = simplexml_load_file($url) or die("ERROR");
I have my index.php file which is calling web service out of sugar and it returns me as response when I run it on my local Apache this result which is OK:
<soapenv:Envelope <soapenv:Body> <ns:CommandResponseData>
<ns:Operation name="BalanceAdjustment"> </ns:Operation>
</ns:CommandResponseData> </soapenv:Body> </soapenv:Envelope>
I created one additional button within Detail View which I plan to call this web service but I do not know how to bind that button, my index.php file and result from that web service to pack in some field.
For testing purposes I would like to put this whole response on example in field Comment of Contact module: so that field Comment should Contain above whole response (I will later parse it).
I created new button (which does not do anything currently )
I created button in view.detail.php.
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/json_config.php');
require_once('include/MVC/View/views/view.detail.php');
class ContactsViewDetail extends ViewDetail
{
function ContactsViewDetail()
{
parent::ViewDetail();
}
function display()
{
$this->dv->defs['templateMeta']['form']['buttons'][101] = array (
'customCode' => '<input title="Call" accesskey="{$APP.LBL_PRINT_PDF_BUTTON_KEY}" class="button" onClick="javascript:CustomFunctionHere();" name="tckpdf" value="Call" type="button">');
parent::display();
}
}
?>
I will appreciate help with this. So to recapitulate : With this my button I want to call my index.php file which will call web service and I want to set web service response in my field Comment (I am getting response in index.php file as htmlspecialchars($client->__getLastResponse())
this is the whole index.php file that I am using currently to call some web service.
<?php
include_once 'CommandRequestData.php';
include_once 'CommandResponseData.php';
$client = new SoapClient("http://127.0.0.1:8181/TisService?WSDL", array(
"trace" => 1, // enable trace to view what is happening
"exceptions" => 1, // disable exceptions
"cache_wsdl" => 0) // disable any caching on the wsdl, encase you alter the wsdl server
);
$req = new CommandRequestData();
$req->Environment->Parameter[0]->name = "ApplicationDomain";
$req->Environment->Parameter[0]->value = "CAO_LDM_00";
$req->Environment->Parameter[1]->name = "DefaultOperationNamespace";
$req->Environment->Parameter[1]->value = "CA";
$req->Command->Operation->namespace = "CA";
$req->Command->Operation->name = "BalanceAdjustment";
$req->Command->Operation->ParameterList->StringParameter[0]->name = "CustomerId";
$req->Command->Operation->ParameterList->StringParameter[0]->_ = "387671100009";
$req->Command->Operation->ParameterList->IntParameter[0]->name = "AmountOfUnits";
$req->Command->Operation->ParameterList->IntParameter[0]->_ = "1000";
$req->Command->Operation->ParameterList->IntParameter[1]->name = "ChargeCode";
$req->Command->Operation->ParameterList->IntParameter[1]->_ = "120400119";
try {
$result = $client->ExecuteCommand($req);
$result->CommandResult->OperationResult->Operation->name . "<br /><br />";
}
catch(SoapFault $e){
echo "<br /><br />SoapFault: " . $e . "<br /><br />";
}
catch(Exception $e){
}
echo "<p>Response:".htmlspecialchars($client->__getLastResponse())."</p>";
?>