This guide outlines the step-by-step process of integrating Facebook and WooCommerce for seamless management of your online store and social media presence.
https://yourdomain.com
.composer require facebook/graph-sdk automattic/woocommerce
in your project directory.php your_script_name.php
.By following these steps, you can effectively integrate Facebook and WooCommerce to streamline your e-commerce operations and enhance your online presence.
Wordpress Page Template App Type: Other > Buisness
/**
* Template Name: Social-feed
**/
require_once get_template_directory() . '/vendor/autoload.php';
use Facebook\Facebook;
use Automattic\WooCommerce\Client;
$site_url = 'Your-site-url';
$consumer_key = 'Your-consumerKey';
$secret_key = 'Your-secret-key';
$appId = 'App-id';
$appSecret = 'Your-secret-id';
$pageId = 'Page-id';
$AccessToken = 'Your-Access Token';
// Function to retrieve stored long-lived access token from options
function get_stored_facebook_token() {
return get_option('facebook_long_lived_token');
}
function is_valid_facebook_token($token) {
$storedTime = get_option('facebook_token_stored_time');
$expiryTime = strtotime($storedTime . ' +60 days');
if (time() < $expiryTime) {
return true; // Token is still valid
} else {
return false; // Token has expired or is invalid
}
}
// Retrieve stored long-lived access token from options table
$storedToken = get_stored_facebook_token();
// Check if stored token is valid
if (is_valid_facebook_token($storedToken)) {
echo "Stored token is valid.<br>";
$fb = new Facebook([
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v2.5'
]);
$longLivedToken = $storedToken; // Reuse stored token
$fb->setDefaultAccessToken($storedToken);
} else {
try {
// Token is stored, generate a longlived token
$fb = new Facebook([
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v2.5'
]);
// Generate new long-lived access token
$longLivedToken = $fb->getOAuth2Client()->getLongLivedAccessToken($AccessToken);
// Store the new long-lived access token
update_option('facebook_long_lived_token', $longLivedToken);
update_option('facebook_token_stored_time', current_time('mysql'));
// Set the new long-lived access token as default
$fb->setDefaultAccessToken($longLivedToken);
echo "New long-lived token generated and stored.<br>";
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
$response = $fb->sendRequest('GET', $pageId, ['fields' => 'access_token'])->getDecodedBody();
$foreverPageAccessToken = $response['access_token'];
//Another way login redirect and fetch access token issue with fb popup blank on redirect
// Initialize WooCommerce client
$woocommerce = new Client(
$site_url,
$consumer_key,
$secret_key,
[
'version' => 'wc/v3',
]
);
try {
$allProducts = $woocommerce->get('products');
$count = 0;
// Retrieve WooCommerce default currency
$default_currency = get_woocommerce_currency_symbol();
// Decode HTML entities for currency symbol
$currency_symbol = html_entity_decode($default_currency, ENT_QUOTES, 'UTF-8');
// Loop through all products retrieved
foreach ($allProducts as $product) {
if ($count >= 2) {
break;
}
$productid = $product->id;
$productname = $product->name;
$productShortDescription = wp_strip_all_tags($product->short_description);
$productLink = $product->permalink;
$productImageUrl = $product->images[0]->src; // Assuming the first image is the featured image
$productPrice = $product->price;
$alreadyPosted = get_post_meta($productid, 'posted', true);
$fb->setDefaultAccessToken($foreverPageAccessToken);
$productType = $product->type; // Get product type
// Check if product type is "simple"
if ($productType === 'simple') {
// Create post data if not already posted
//avoid posting products duplication again and again when running code
// if ($alreadyPosted !== 'true') { //swap this condition once testing is done for not creating products agin and again
if(empty($alreadyPosted) ){
if(!empty($productImageUrl)) {
// Upload the image to the Facebook page's photos
$response = $fb->sendRequest('POST', "/$pageId/photos", [
'message' => $productname . "\nPrice: " . $currency_symbol . $productPrice . "\n" . $productShortDescription ."\nProduct Link: " . $productLink,
'url' => $productImageUrl,
'caption' => $productLink, // Optional: Caption for the photo
// 'no_story' => true
]);
$imageId = $response->getGraphNode()->getField('id');
update_post_meta($productid, 'posted', 'true');
$graphNode = $response->getGraphNode();
$postId = $graphNode['id'];
echo 'Product posted successfully. FB Post ID: ' . $postId . ' Product-id ' . $productid . '<br>';
}else {
// If no image available, share as post feed
$productLink = $product->permalink;
// Create post feed data
$response = $fb->sendRequest('POST', "/$pageId/feed", [
'message' => $productname . "\nPrice: " . $default_currency . $productPrice . "\n" . $productShortDescription . "\nProduct Link: " . $productLink,
'source' => $productLink,
]);
$postId = $response->getGraphNode()->getField('id');
echo 'Product posted as feed successfully. FB Post ID: ' . $postId . ' Product-id ' . $productid . '<br>';
$count++;
continue; // Skip the rest of the loop iteration
}
}
}
$count++;
}
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
get
method. It retrieves a specified number of products per page.This script automates the process of fetching products from a WooCommerce store and posting them on a Facebook page. It’s essential to ensure that all credentials are correctly configured and permissions are granted for smooth execution.
How too add as Post feed
try {
$message = 'Test message website';
$title = 'Post From Website';
$description = 'Programming blog.';
$attachment = array(
'message' => $message,
'name' => $title,
'description' => $description,
);
// Post a message to the user's profile
$response = $fb->post('/me/feed', $attachment ,$accessToken);
// Get the post ID if the post was successful
$graphNode = $response->getGraphNode();
echo 'Post ID: ' . $graphNode['id'];
} catch (FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
} catch (FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
Generate access Token with Login Url App Type : Facebook Login configure Product: Facebook setup Set up Redirect Url
Example shows how to fetch Access token With Login Url ```php
/**
// Get the child theme directory $theme_directory = get_stylesheet_directory();
// Include the autoloader provided in the SDK require_once $theme_directory . ‘/templates/vendor/autoload.php’;
use Facebook\Facebook; use Facebook\Exceptions\FacebookResponseException; use Facebook\Exceptions\FacebookSDKException;
// Set your Facebook App ID and App Secret $appId = ‘882905023657603’; $appSecret = ‘d85238e05bc730e561ed0af95d6b7e2a’; $redirectUri = ‘https://foodsafetystandard.demo1.bytestechnolab.com/social-feed’; $scopes = [‘publish_to_groups’, ‘pages_read_engagement’, ‘pages_manage_posts’,’email’];
$loginUrl = ‘https://www.facebook.com/v12.0/dialog/oauth?’ . http_build_query([ ‘client_id’ => $appId, ‘redirect_uri’ => $redirectUri, ‘scope’ => ‘email’, // ‘scope’ => implode(‘,’, $scopes), ‘response_type’ => ‘code’, ]);
if (isset($_GET[‘code’])) { $tokenUrl = ‘https://graph.facebook.com/v12.0/oauth/access_token’; $postData = [ ‘client_id’ => $appId, ‘client_secret’ => $appSecret, ‘redirect_uri’ => $redirectUri, ‘code’ => $_GET[‘code’], ];
// Use PHP's built-in functions to send a POST request
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($postData),
],
];
$context = stream_context_create($options);
$response = file_get_contents($tokenUrl, false, $context);
if ($response !== false) {
$params = json_decode($response, true);
if (isset($params['access_token'])) {
$accessToken = $params['access_token'];
echo 'Access Token: ' . $accessToken;
//// Process Your code
} else {
echo 'Error: Access token not found';
}
} else {
echo 'Error: Failed to get access token.';
} } else {
header('Location: ' . $loginUrl);
exit(); }