I started with facebook business sdk for php. Was following this doc: https://developers.facebook.com/docs/business-sdk/getting-started/
installed without trouble, then tried testing as they instructed,
created src/test.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
$app_id = "{app-id}";
$app_secret = "{appsecret}";
$access_token = "{access-token}";
$account_id = "act_{{adaccount-id}}";
Api::init($app_id, $app_secret, $access_token);
$account = new AdAccount($account_id);
$cursor = $account->getCampaigns();
// Loop over objects
foreach ($cursor as $campaign) {
echo $campaign->{CampaignFields::NAME}.PHP_EOL;
}
filled in the required values. and ran the file. Getting this:
FacebookAds\CrashReporter : Enabled
FacebookAds\CrashReporter : Exception detected!
FacebookAds\CrashReporter : Successfully sent report
Fatal error: Uncaught FacebookAds\Http\Exception\AuthorizationException: Invalid OAuth access token. in C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Exception\RequestException.php:174
Stack trace:
#0 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Client.php(215): FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))
#1 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Request.php(286): FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))
#2 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Api.php(165): FacebookAds\Http\Request->execute()
#3 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Api.php(214): FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request))
#4 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\ApiRequest.php(187): FacebookAds\Api->call('/act_3667840345...', 'GET', Array, Array)
#5 in C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Exception\RequestException.php on line 174
Not sure what I am doing wrong. Didnt find much by searching. Can anyone please help?
The error you get is pretty explicit: "Invalid OAuth access token"
you can check the token you supplied using Facebook's token-debbuger # https://developers.facebook.com/tools/debug/accesstoken/
most probably you are missing the "ads_management" permission.
Related
I'm trying to embed Server Side conversion in a website (due to iOS 14 update) but I'm experiencing issues with the PHP SDK so everytime I try a conversion code in a page it turns out Fatal Error.
So my question is, how can I use/embed correctly these conversions code?
Thanks in advance to who will answer
EDIT: To explain better
I Downloaded the Facebook Php SDK from here https://php-download.com/package/facebook/php-sdk-v4 and then I uploaded in my website root, after that I've included the following code(from https://developers.facebook.com/docs/marketing-api/conversions-api/payload-helper ) in a thank you page to track "purchase" conversion:
<?php
define('SDK_DIR', __DIR__ . '/..'); // Path to the SDK directory
$loader = include SDK_DIR . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\ServerSide\Content;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\DeliveryCategory;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\Gender;
use FacebookAds\Object\ServerSide\UserData;
// Configuration.
// Should fill in value before running this script
$access_token = null;
$pixel_id = null;
if (is_null($access_token) || is_null($pixel_id)) {
throw new Exception(
'You must set your access token and pixel id before executing'
);
}
// Initialize
Api::init(null, null, $access_token);
$api = Api::instance();
$api->setLogger(new CurlLogger());
$events = array();
$user_data_0 = (new UserData())
->setEmail("hashed email");
$custom_data_0 = (new CustomData())
->setValue(142.52)
->setCurrency("USD");
$event_0 = (new Event())
->setEventName("Purchase")
->setEventTime(1620379012)
->setUserData($user_data_0)
->setCustomData($custom_data_0)
->setActionSource("email");
array_push($events, $event_0);
$request = (new EventRequest($pixel_id))
->setEvents($events);
$request->execute();
Of course this code do not contain token and pixel ID but in the website I filled all the variables with the right values.
I also adjusted the require on top with the right path and then i got the following error in the page:
Fatal error: Uncaught Error: Class 'FacebookAds\Api' not found in mywebsite/public_html/template/includes/analyticstracking2.inc.php:60 Stack trace: #0 /mywebsite/public_html/it/thankyou_page.php(134): require() #1 {main} thrown in mywebsite/public_html/template/includes/analyticstracking2.inc.php on line 60
On line 60 there's the following: Api::init(null, null, $access_token);
Onestly I do not understand where the issue it's coming from.
Now to answer to 'why do not use composer' I can't from a shared hosting server, if someone knows howo to do maybe I can start from there.
I am building an API, but I get an Uncaught error when creating my token with JWT, when I run a post man call, I get in my error log Stack trace:
#0 [internal function]: Api->generateToken()
#1 /home/osconliz/public_html/Osconlizapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#2 /home/osconliz/public_html/Osconlizapicall/index.php(4): Rest->processApi()
#3 {main}
thrown in /home/osconliz/public_html/Osconlizapicall/api.php on line 36
[19-May-2018 02:04:47 UTC] PHP Fatal error: Uncaught Error: Class 'JWT' not found in /home/osconliz/public_html/Osconlizapicall/api.php:36
Stack trace:
#0 [internal function]: Api->generateToken()
#1 /home/osconliz/public_html/Osconlizapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#2 /home/osconliz/public_html/Osconlizapicall/index.php(4): Rest->processApi()
#3 {main}
but when I check my jwt file on my PHP server it has class JWT in it.
**jwt.php** page with class jwt screen shot
Then the page I am using to create the token which is **api.php**
//SECRETE_KEY is a constant for creating a pass for JWT
<?php
class Api extends Rest {
public $dbConn;
public function __construct(){
parent::__construct();
$db = new DbConnect;
$this->dbConn = $db->connect();
}
public function generateToken(){
$client_id_key = $this->validateParameter('client_id_key', $this->param['client_id_key'], STRING);
//$client_secret_key = $this->validateParameter('client_secret_key', $this->param['client_secret_key'], STRING);
//client_secret_key should be commented out it is not used for validation for security purposes, only id key
$stmt = $this->dbConn->prepare("SELECT * FROM `api_clients_properties` WHERE client_id = :client_id_key");
$stmt->bindParam(":client_id_key", $client_id_key);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!is_array($user)){
$this->returnResponse(API_NAME_REQUIRED, "Invalid Client Id Key");
}
if ($user['property_status'] == "not verified"){
$this->returnResponse(API_NAME_REQUIRED, "Property not verified, please contact admin, to verify it");
}
$payload = [
'iat' => time(),
'iss' => 'localhost',
'exp' => time() + (60),
'userId' => $user['id']
];
$token = JWT::encode($payload, SECRETE_KEY);
echo $token;
}
}
?>
The JWT class is in the namespace Firebase\JWT, so you will either need to use it:
use \Firebase\Jwt\Jwt;
Jwt::encode(...);
Or use its full namespace when invoking:
\Firebase\Jwt\Jwt::encode();
If you copied the file from GitHub rather than using composer to install it, you will need to comment out the namespace lines at the top of the file. so from my snapshot at the very top of the first line of jwt.php screenshot, you will comment out //namespace Firebase\JWT; and you would not get the 500 internal server error again.
I am just trying to connect my PHP with Google API. My aim is to fetch a particular folder's content and show them as feeds in my site. So for a base I am trying to pull the kind of file of my drive. I am struck. Here is my code.
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_DriveService.php';
$client = new Google_Client(); $client->setApplicationName("My Application");
$client->setDeveloperKey("<mykey>");
$service = new Google_DriveService($client);
$optParams = array('fields' => 'kind'); $results = $service->files->listFiles($optParams);
foreach ($results['files'] as $item) {
print($item['kind'].'<br>');
}
?>
When I execute this, I get the following error,
Fatal error: Uncaught exception 'Google_ServiceException' with message
'Error calling GET
https://www.googleapis.com/drive/v2/files?fields=kind&key=:
(403) Insufficient permissions for this file' in
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\io\Google_REST.php:66
Stack trace: #0
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\io\Google_REST.php(36):
Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\service\Google_ServiceResource.php(177):
Google_REST::execute(Object(Google_HttpRequest)) #2
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\contrib\Google_DriveService.php(465):
Google_ServiceResource->__call('list', Array) #3
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\test.php(12):
Google_FilesServiceResource->listFiles(Array) #4 {main} thrown in
C:\xampp\htdocs\ccl\gdapi\google-api-php-client\src\io\Google_REST.php
on line 66
I gave proper key. Kindly help me. Thank you
I use the Blogger library v3 for php,I can not insert a new post.
The error message was:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/blogger/v3/blogs/3631076204866601722/posts: (403) We're sorry, but you don't have permission to access this resource.' in E:\xampp\htdocs\Udemy2Blogger\libs\Google\Http\REST.php:79
Stack trace:
#0 E:\xampp\htdocs\Udemy2Blogger\libs\Google\Http\REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 E:\xampp\htdocs\Udemy2Blogger\libs\Google\Client.php(508): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 E:\xampp\htdocs\Udemy2Blogger\libs\Google\Service\Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 E:\xampp\htdocs\Udemy2Blogger\libs\Google\Service\Blogger.php(1495): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 E:\xampp\htdocs\Udemy2Blogger\index.php(78): Google_Service_Blogger_Posts_Resource->insert('363107620486660...', Object(Google_Service_Blogger_Post), Array)
#5 {main} thrown inE:\xampp\htdocs\Udemy2Blogger\libs\Google\Http\REST.php on line 79
the code is:
<?php
session_start();
$path = "libs";
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Client.php';
require_once 'Google/Service/Blogger.php';
$blogId = 'xxxxxxxxxxxxxxxxxxxx';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxx';
$key_file_location = 'udemy coupon free-e0de16bee449.p12';
$client = new Google_Client();
$client->setAccessType('offline');
$client->setApplicationName("Udemy coupon free");
$bloggerService = new Google_Service_Blogger($client);
/************************************************
If we have an access token, we can carry on.
Otherwise, we'll get one with the help of an
assertion credential. In other examples the list
of scopes was managed by the Client, but here
we have to list them manually. We also supply
the service account
************************************************/
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key1 = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/blogger'),
$key1
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$newpost = new Google_Service_Blogger_Post();
$newpost->setTitle("test");
$newpost->setContent("test content");
$post = $bloggerService->posts->insert($blogId, $newpost, array());
print_r($post);
Enable Blogger Api v3:
Create client id (service account):
Please help me, thanks a lot!
I've successful after switching to use Client ID (Web application) instead of using Client ID (Service account).
Thanks!
Sometimes if the google blogger ID doesn't match then you might get this error. You can find the blogger ID in the URL of the blogger account.
I was trying the same via REST client. Seems like service account didn't have permission to add blogger posts.
The reason might be - Only an author/admin can create/edit Posts and
service email can't be added to this list.
Attached ARC screenshot
I am trying to make work a php code for listing the users of a google user. I have followed a youtube tutorial and tryed the solutions proposed in this one But I still get this annoying error when I call the authenticate method :
Fatal error: Uncaught exception 'Google_IOException' with message 'HTTP Error: (0) couldn't connect to host' in D:\xampp\htdocs\yac\proxy\lib\google-api-client\io\Google_CurlIO.php:128 Stack trace: #0 D:\xampp\htdocs\yac\proxy\lib\google-api-client\auth\Google_OAuth2.php(103): Google_CurlIO->makeRequest(Object(Google_HttpRequest)) #1 D:\xampp\htdocs\yac\proxy\lib\google-api-client\Google_Client.php(131): Google_OAuth2->authenticate(Array, NULL) #2 D:\xampp\htdocs\yac\proxy\contacts.php(36): Google_Client->authenticate() #3 {main} thrown in D:\xampp\htdocs\yac\proxy\lib\google-api-client\io\Google_CurlIO.php on line 128
here is my PHP code :
<?php
session_start();
require_once 'lib/google-api-client/Google_Client.php';
$client = new Google_Client();
$client->setApplicationName("Contactoos");
$client->setClientId('*************************************');
$client->setClientSecret('*********************************');
$client->setScopes(array('http://www.google.com/m8/feeds'));
$client->setRedirectUri('http://localhost/yac/proxy/contacts.php');
$client->setAccessType('online');
if(isset($_GET['code']))
{
echo "here";
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('location:http://localhost/yac/proxy/contacts.php');
}
if(!isset($_SESSION['token']))
{
$url = $client->createAuthUrl();
?>
List google contacts
<?php
}
else
{
$client->setAccessToken($_SESSION['token']);
}
?>
As I said, I tried the solutions proposed in the second tutorial but in vain.
Does anyone know how to fix this problem ?
Thanks.
It looks like your server is having issues connecting to www.googleapis.com. You will need to check your network connection.
See if you're able to visit https://www.googleapis.com/discovery/v1/apis from that machine.
If you are using a proxy then you need to add curl_setopt($ch, CURLOPT_PROXY, 'your-proxy-settings'); to Google_CurlIO.php.
I've added it on line 111, after curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent());