PHP-SDK publish link not available for public - facebook-php-sdk

When publishing a new link, using php sdk, the link is only available for logged user, it's not publish as public.
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
setcookie('cod_eventos', $_POST['cod_eventos']);
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
setcookie('userlogin', 1);
echo ("<script>window.open('".$login_url."')</script>");
} else {
$page_id = $page_id;
try {
$access_token = $facebook->getAccessToken();
$attachment2 = array(
'access_token' => $access_token
);
$page = $facebook->api('/me/accounts', 'get', $attachment2);
} catch (FacebookApiException $e) {
echo 'Unable to get page access token';
}
$privacy = array(
'value' => 'EVERYONE',
);
$attachment = array(
'access_token' => $page['data'][0]['access_token'],
'name' => 'Test',
'link' => 'http://www.facebook.com/',
'description' =>'Facebook',
'privacy' => json_encode($privacy),
);
try {
$facebook->api('/' . $page_id . '/feed', 'POST', $attachment);
echo '<div class="gestor_ficheiros_tipo">Event publish Facebook</div>';
}
catch (FacebookApiException $e)
{
echo '<div class="gestor_ficheiros_tipo">'.$e->getMessage().'</div>';
}
After running this the content is publish, but not view-able by un-registered facebook users

Apparently, despite what the API documentation says, the privacy setting is 'privacy_type', not 'privacy'. I found that out here on SO I think, but closed the tab so I can't immediately share the link.

Check the settings on your app as well - I think it's the 'Visibility of app and posts' setting defaults to 'Friends' instead of 'Public'. Maybe that'll do it?

I found out what was the problem, I was using facebook app in sandbox mode... :(. Once I've changed it started working perfectly

Related

How to submit contact form 7 programmatically

I want to submit contact form by custom function
The code below is getting the instance of form but when submitted. It submit the form but not the fields which I wanted.
$item = wpcf7_contact_form( $formId );
$result = $item->submit();
Here where I can pass the fields I define in admin panel like "textarea-123" & "email-234" ?
I did not get exact answer for what I look but I found the alternate solution.
function cf7Submit($formId , $args) {
$url = 'http://example.com/wp-json/contact-form-7/v1/contact-forms/'.$formId.'/feedback';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'body' => $args
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
}
I can call this function like this:
cf7Submit(128, array(
'textarea-123' => 'test email',
'email-234' => 'asd#asd.com'));
#daraptoor has found a good solution, but as #davevsdave noticed in the comment, it does not work properly in CF7 5.6.
Error 415 is caused by added to API check for content type passed into a request header:
// part of create_feedback() from CF7's rest-api.php
if ( ! str_starts_with( $content_type, 'multipart/form-data' ) ) {
To figure it out, just add the expected content type into a request header:
$response = wp_remote_post( $url, array(
'method' => 'POST',
'headers' => array(
'Content-Type' => 'multipart/form-data'
),
'body' => $args
)
);
UPD
Faced with an issue, that wp_remote_post() send data in body and not in POST, so CF7 API does not get any fields. It is caused because the WP's function uses http_build_query() (read more here).
I have used cURL request as a workaround:
// Same user agent as in regular wp_remote_post().
$userAgent = 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url');
// Note that Content-Type wrote in a bit different way.
$header = ['Content-Type: multipart/form-data'];
// Same array with fields to pass, not changed.
$body = ['foo' => 'bar'];
$curlOpts = [
// Send as POST
CURLOPT_POST => 1,
// Get a response data instead of true
CURLOPT_RETURNTRANSFER => 1,
// CF7 will reject your request as spam without it.
CURLOPT_USERAGENT => $userAgent,
CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $body,
];
$ch = curl_init($apiUrl); // Create a new cURL resource.
curl_setopt_array($ch, $curlOpts); // Set options.
$response = curl_exec($ch); // Grab response.
if (!$response) {
// Do something if an error occurred.
} else {
$response = json_decode($response);
// Do something with the response data.
}
// Close cURL resource, and free up system resources.
curl_close($ch);
Hope it saves someones time :)
You can add a piece of JS code, like:
$("form.wpcf7").submit()

Connection codeigniter and wordpress

The situation is as: wordpress installation in root and ci installation in /subdomain1 of subdomain1.domain.com.
I want to perform the following; users from my wordpress site can login with the same credentials in the codeigniter app. I tried methods explained here and in other tutorials but one thing keeps happening. When I add require_once('../wp-load.php'); in the index.php file from ci it and adjusted the load.php file and MY_url_helper.php file it keeps redirecting to: subdomain1.domain.com/index.php/login/wp-admin/install.php I tried to shut off rewriting but it doesn't seem to fix this.
Anyone have a solution? I would really appreciate it!
There are two methods:
1. Load the Wordpress Database in your Codeigniter
To do so add to your "application/config/database.php":
$db['wordpress'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => '#',
'password' => '#',
'database' => '#',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Don't forget to replace '#' with your database login information.
After that you can load the database where ever needed with
$this->load->database('wordpress');
Source: https://www.codeigniter.com/user_guide/database/connecting.html
2. Use the Wordpress wp-load.php
Where ever needed to see if the user is logged in use the following code (PS: at the end there is also a check included how you could check if a user purchased a product via EasyDigitalDownloads in your Wordpress installation - if needed):
<?php
define( 'WP_USE_THEMES', false ); // Do not use the theme files
define( 'COOKIE_DOMAIN', false ); // Do not append verify the domain to the cookie
define( 'DISABLE_WP_CRON', true ); // We don't want extra things running...
//$_SERVER['HTTP_HOST'] = ""; // For multi-site ONLY. Provide the
// URL/blog you want to auth to.
// Path (absolute or relative) to where your WP core is running
require("/var/www/yourdomain.com/htdocs/wp-load.php");
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
} else {
$creds = array();
// If you're not logged in, you should display a form or something
// Use the submited information to populate the user_login & user_password
$creds['user_login'] = "";
$creds['user_password'] = "";
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error( $user ) ) {
echo $user->get_error_message();
} else {
wp_set_auth_cookie( $user->ID, true );
}
}
if ( !is_wp_error( $user ) ) {
// Success! We're logged in! Now let's test against EDD's purchase of my "service."
if ( edd_has_user_purchased( $user->ID, '294', NULL ) ) {
echo "Purchased the Services and is active.";
} else {
echo "Not Purchased";
}
}
Source: http://dovy.io/wordpress/authenticating-outside-of-wordpress-on-diff-domain/

post from php to my fan page facebook with facebook sdk 5 api 2.4

I read dozens of articles, the guidelines, I read everything but I do not understand anything. I'm going crazy. Are three days that I'm trying to post on my facebook fan page through the last 4 API 2.4 SDK.
1. I created the app on facebook but the permissions are almost impossible to enforce
2. I have created the appropriate PHP code with the various authentication codes
the result is always the same: NOTHING
Then the questions:
1. What do you need the app to publish on my fan page?
2. What permissions are needed?
3. If I do not have screenshots to be indicated in the permit to push them through whatever I do (I do the screen shot of the source code?).
4. as you get the access token to the fan page?
A desperate help.
$APP_ID = 'XXXXXXXXXXXXXXXXX'; //app id
$APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //app secret
$TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //access token
$page_id = "XXXXXXXXXXXXXXXXXXXXX"; // facebook page id ottenuto da
$message = "Stiamo testando la pubblicazione delle inserzioni anche su Facebook";
$link = "http://qualcosa";
$name = "Me";
/*$fb = new Facebook\Facebook([
'app_id' => $APP_ID,
'app_secret' => $APP_SECRET,
'default_graph_version' => 'v2.4',
]);
$linkData = [
'link' => 'http://qualcosa/altro',
'message' => $message,
];
var_dump($linkData);
$helper = $fb->getPageTabHelper();
$accessToken = $helper->getAccessToken();
var_dump($accessToken);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/feed', $linkData,$TOKEN);//
} catch(Facebook\Exceptions\FacebookResponseException $e) {
$msg = 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
$msg = 'Facebook SDK returned an error: ' . $e->getMessage();
}
var_dump("MSG: ".$msg);
$graphNode = $response->getGraphNode();
var_dump("Graph: ".$graphNode);
$msg = 'Posted with id: ' . $graphNode['id'];
var_dump($msg);
$msg="Nulla";
// I tryed but nothing
try {
FacebookSession::setDefaultApplication($APP_ID, $APP_SECRET);
$session = new FacebookSession($TOKEN);
var_dump($session);
$page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', array(
'access_token' => $TOKEN,
'name' => $name,
'link' => $link,
'picture' => '',
'caption' => 'Test da Cip!',
'message' => $message,
) ))->execute()->getGraphObject()->asArray();
} catch (Facebook\Exceptions\FacebookResponseException $e)
{$msg = 'Graph returned an error: ' . $e->getMessage();}
catch (Facebook\Exceptions\FacebookSDKException $e)
{$msg = 'Facebook SDK returned an error: ' . $e->getMessage();}
// return post_id, optional
var_dump( $page_post );
var_dump($msg);
echo "<br />Finito";
After many attempts I have solved the problem. In graph explorer serves select the App, then the page on publish, assign publishing rights and withdraw the access token created. In the bottom of the page then you can extend the time validity of the token and you will have to use the latter.

Get page_access_token

As I knew there is a way to get access token via https://developers.facebook.com/tools/explorer.
Is there other way to get page_access_token by API?
I want to post request to add app to facebook page but it require a page_access_token as below:
https://graph.facebook.com/myPageId/tabs/?app_id=myAppId&access_token=myPageAccessToken
Thanks.
Yes you can. The current user must be an administrator of this page;
extended permission needed - manage_pages
refer url: https://developers.facebook.com/docs/reference/api/page/
Try this:
$config = array(
'appId' => FB_APP_ID,
'secret' => FB_SECRET_KEY,
'cookie' => true // enable optional cookie support
);
$facebook = new Facebook($config);
// See if there is a user from a cookie
$user = $facebook->getUser();
$params = array(
'scope' => 'manage_pages',
'redirect_uri' => FB_APP_URL,
);
$loginUrl = $facebook->getLoginUrl($params);
<script> window.top.location.href = '<?php echo $loginUrl ?>'; </script>

Facebook page tab changing

I want to change tab name of a facebook page.
Here is the code I am using
<?php
session_start();
$pageId=$_SESSION['pageid'];
require('sdk/facebook.php');
$appId = 'My App Id';
$secret = 'My App Secret';
$pageId = $pageId;
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
));
$access_token=$facebook->getAccessToken();
if($facebook->setAccessToken($access_token))
{
$page_tabs=$facebook->api($pageId . '/tabs');
$name=$page_tabs['data']['0']['name'];
$tabid=$page_tabs['data']['0']['id'];
if($name=="MyTab")
{
$facebook->setAccessToken($access_token);
$facebook->api($tabid, 'POST', array(
'custom_name' => 'MyTab New Name',
'access_token'=>$_SESSION['token']
));
}
echo "OK";
}
?>
But I am getting error for Oauth Exception , it says you need to supply the accesstoken for this
Please Help
you need few changes
Instead of this
'access_token'=>$_SESSION['token']
use this
//get the user access token
$token = $facebook->getAccessToken();
echo "</br>" . 'User Access_Token:' . $atoken;

Resources