I using gotowebinar service to register user from custom landing page:
API LINK https://goto-developer.logmeininc.com/
How to create the right flow to register user into webinar?
and how to get organizer_id ??
thanks
here my code.
$webinar_id = "336-174-566";
$gtwPost = array(
"firstName" => $contact_data['FirstName'],
"lastName" => $contact_data['LastName'],
"email" => $contact_data['Email']
);
$gtwHeaders = array(
"Accept:application/vnd.citrix.g2wapi-v1.1+json",
"Content-Type:application/json",
"Authorization:OAuth oauth_token=xxxxxxxxxx"
);
$this->data['gtw'] = array(
'post' => $gtwPost,
'headers' => $gtwHeaders
);
//Set POST URL for GoToWebinar
$gtw_url = "https://api.citrixonline.com/G2W/rest/organizers/".$organizer_id."/webinars/".$webinar_id."/registrants";
//Start GoToWebinar submission
$curl = #curl_init();
#curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($gtwPost));
#curl_setopt($curl, CURLOPT_URL, $gtw_url);
##curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#curl_setopt($curl, CURLOPT_POST, 1);
#curl_setopt($curl, CURLOPT_HTTPHEADER, $gtwHeaders);
#curl_exec($curl);
$info = #curl_getinfo($curl);
#curl_close($curl);
//End GoToWebinar registrant submission
Solution here, in git hub
https://github.com/zakir-hyder/Citrix-GoToWebinar-PHP-Library
you have to create application first, after provide details to the script:
$citrix = new Citrix('API Key');
$citrix->set_organizer_key('organizer_key');
$citrix->set_access_token('access_token');
code example:
<?php
include "citrix.php";
$citrix = new Citrix('API Key');
$citrix->set_organizer_key('organizer_key');
$citrix->set_access_token('access_token');
try
{
$organizer_key = $citrix->get_organizer_key();
$citrix->pr($organizer_key);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$webinars = $citrix->citrixonline_get_list_of_webinars() ;
$citrix->pr($webinars);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$response = $citrix->citrixonline_create_registrant_of_webinar('webinar id', $data = array('first_name' => 'First Name', 'last_name' => 'Lastnmae', 'email'=>'email#email.com')) ;
$citrix->pr($response);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$webinars = $citrix->get_registrants_of_webinars('webinar id') ;
$citrix->pr($webinars);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$citrix->citrixonline_delete_registrant_of_webinar('webinar id', 'registrant id') ;
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
Related
I want to send notification using FCM. I have added project to Firebase Console got the API key and device_token.
Now I am sending a push notification from PHP, I get the message in logs, but it's showing some exception. I have followed this tutorial.
PHP script function:
function sendInvite()
{
$database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("select * from Invitation where user_name =? and sender_id = ?");
$stmt->execute(array($this->user_name,$this->sender_id));
$rows = $stmt->rowCount();
if ($rows > 0) {
$response = array("status" => -3, "message" => "Invitation exists.", "user_name" => $this->user_name);
return $response;
}
$this->date = "";
$this->invitee_no = "";
$this->status = "0";
$this->contact_id = 0;
$stmt = $dbConnection->prepare("insert into Invitation(sender_id,date,invitee_no,status,user_name,contact_id) values(?,?,?,?,?,?)");
$stmt->execute(array($this->sender_id, $this->date, $this->invitee_no, $this->status, $this->user_name,$this->contact_id));
$rows = $stmt->rowCount();
$Id = $dbConnection->lastInsertId();
$stmt = $dbConnection->prepare("Select device_id from Users where user_id =?");
$stmt->execute(array($this->sender_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$token = $result["device_id"];
$server_key = 'AIzaJaThyLm-PbdYurj-bYQQc';
$fields = array();
$fields['data'] = $data;
if(is_array($token)){
$fields['registration_ids'] = $token;
}else{
$fields['to'] = $token;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;*/
$message = 'Hi,add me to your unique contact list and you never need to update any changes anymore!';
$data = array("message"=>"Hi,add me to your unique contact list and you never need to update any changes anymore!","title"=>"You got an Invitation.");
if (!empty($token)) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $token,
'data' => $data
);
$fields = json_encode($fields);
$headers = array(
'Authorization: key=' . "AIzaSyBGwwJaThyLm-PhvgcbdYurj-bYQQ7XmCc",
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
}
$stmt = $dbConnection->prepare("select * from Invitation where invitation_id=?");
$stmt->execute(array($Id));
$invitation = $stmt->fetch(PDO::FETCH_ASSOC);
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
return $response;
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
return $response;
}
}
MessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
public static final String PUSH_NOTIFICATION = "pushNotification";
private NotificationUtils notificationUtils;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
private void handleNotification(String message) {
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
}else{
// If the app is in background, firebase itself handles the notification
}
}
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "push json: " + json.toString());
try {
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
// boolean isBackground = data.getBoolean("is_background");
String imageUrl = data.getString("image");
String timestamp = data.getString("timestamp");
// JSONObject payload = data.getJSONObject("payload");
Log.e(TAG, "title: " + title);
Log.e(TAG, "message: " + message);
// Log.e(TAG, "isBackground: " + isBackground);
// Log.e(TAG, "payload: " + payload.toString());
Log.e(TAG, "imageUrl: " + imageUrl);
Log.e(TAG, "timestamp: " + timestamp);
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", message);
// check for image attachment
if (TextUtils.isEmpty(imageUrl)) {
showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
} else {
// image is present, show notification with image
showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
}
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
/**
* Showing notification with text and image
*/
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}
}
Exception:
E/MyFirebaseMessagingService: From: 321839166342
10-12 11:49:14.744 21621-27002/com.example.siddhi.contactsapp E/MyFirebaseMessagingService: Data Payload: {title=You got an Invitation., message=Hi,add me to your unique contact list and you never need to update any changes anymore!}
10-12 11:49:14.745 21621-27002/com.example.siddhi.contactsapp E/MyFirebaseMessagingService: Exception: Unterminated object at character 12 of {title=You got an Invitation., message=Hi,add me to your unique contact list and you never need to update any changes anymore!}
What's going wrong here?
I also want to make notification responsive. As it should have Accept and Reject option and on click of that, I want to perform an action.
Can anyone help with this please? Thank you..
Try with below example with manually device token pass
<?php
define("ANDROID_PUSHNOTIFICATION_API_KEY",'API_KEY_HERE'); // FCM
define("ANDROID_PUSHNOTIFICATION_URL",'https://fcm.googleapis.com/fcm/send'); // FCM
function push_android($devicetoken,$param){
$apiKey = ANDROID_PUSHNOTIFICATION_API_KEY; //demo
$registrationIDs[] = $devicetoken;
// Set POST variables
$url = ANDROID_PUSHNOTIFICATION_URL;
$fields = array(
'registration_ids' => $registrationIDs,
'data' => $param,
);
$headers = array(
'Au
thorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
//print_r($result); exit;
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}else{
//echo "success notification";
//print_r($result);
//echo curl_error($ch);
}
// Close connection
curl_close($ch);
return $result;
} ?>
Hope this will help!
This exception is thrown when you have used special characters.Try removing the , before the fullstop.
And to make it responsive like adding accept and reject you can look into the firebase documentation
this is a good explanation
I'm using Quickblox to send push notifications to iPhone users. I created PHP functions for session and creating a user and API is working fine, but testing sending a push notification, I got an error on Dashboard/Queue: "incorrect event" on the message column. The event is created but never arrived.
The response of the API is OK, like the documentation.
I don't know why I got that error.
This is my code:
if (isset($_POST['mensaje'])) {
// Quickblox user Sign Up
$session = createSession( . . . , '...', '...', '...', '...');
$token = $session->token;
$group = '...'; // Hardcoded only for testing
$resp = sendQBPush($_POST['mensaje'], $group, $token);
}
and the function:
function sendQBPush($msg, $group, $token)
{
if (!$msg) {
return false;
}
$message = base64_encode($msg);
// Build post body
$post_body = array(
'event' => array(
'notification_type' => 'push',
'environment' => 'production',
'user' => array(
'tags' => array(
'any' => $group
)
) ,
'push_type' => 'apns',
'message' => 'payload=' . $message
)
);
$request = json_encode($post_body);
$ch = curl_init('http://api.quickblox.com/events.json');
curl_setopt($ch, CURLOPT_POST, true); // Use POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $request); // Setup post body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'QuickBlox-REST-API-Version: 0.1.0',
'QB-Token: ' . $token
));
$resultJSON = curl_exec($ch);
$responseJSON = json_decode($resultJSON);
echo $resultJSON;
// Check errors
if ($responseJSON) {
return $responseJSON;
}
else {
$error = curl_error($curl) . '(' . curl_errno($curl) . ')';
return $error;
}
// Close connection
curl_close($curl);
}
Thanks for your help
I have a job site where 100 jobs posting daily. i also have a Facebook page. i want to post 10 jobs each hour to My Facebook page with cron jobs.
I am using the following code to post to Facebook face by accessing the URL Manually.
<?php
require_once 'facebook_sdk/src/facebook.php';
// configuration
$appid = 'xxxxxxx';
$appsecret = 'xxxxxxx';
$pageId = 'xxxxx';
$msg = 'test';
$title = 'pagetitle';
$uri = 'http://google.com/';
$desc = 'description here';
$pic = 'http://google.com/test/2.png';
$action_name = 'Go to my site';
$action_link = 'http://www.google.com';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
// Contact Facebook and get token
if ($user) {
// you're logged in, and we'll get user acces token for posting on the wall
try {
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
$attachment = array(
'access_token' => $page_info['access_token'],
'message' => $msg,
'name' => $title,
'link' => $uri,
'description' => $desc,
'picture'=>$pic,
'actions' => json_encode(array('name' => $action_name,'link' => $action_link))
);
$status = $facebook->api("/$pageId/feed", "post", $attachment);
} else {
$status = 'No access token recieved';
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
// you're not logged in, the application will try to log in to get a access token
header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
}
echo $status;
?>
It working fine. but i want to post the jobs automatically with corn jobs. how can i do it.
does anyone have any advice?
Please see the codes below and edit/complete it according to yours
class Facebook
{
/**
* #var The page id to edit
*/
private $page_id = '_PAGE_ID_';
/**
* #var the page access token given to the application above
*/
private $page_access_token = '_ACCESS_TOKEN_';
/**
* #var The back-end service for page's wall
*/
private $post_url = '';
/**
* Constructor, sets the url's
*/
public function Facebook()
{
$this->post_url = 'https://graph.facebook.com/'.$this->page_id.'/feed';
}
public function renew_access()
{
$url = 'https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&display=popup&code=_CODE_&redirect_uri=THIS_FILE_FULL_URL'; // THIS_FILE_FULL_URL = like http://site.com/fb.post.php
// request this url to renew access token to send posts when offline. get the access_token and set self::$page_access_token = _ACCESS_TOKEN_
}
private function getcode()
{
$url = 'https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=THIS_FILE_FULL_URL'; // THIS_FILE_FULL_URL = like http://site.com/fb.post.php
// request this url to get _CODE_ to send posts when offline. then get the access_token and set self::$page_access_token = _ACCESS_TOKEN_
}
private function want_to_send()
{
// check for somethings if you want to send or you don't
// for eg. check for time or any other check if sent before, or just return true to pass
return true;
}
public function message($data)
{
// need token
$data['access_token'] = $this->page_access_token;
if(!$data['properties'])
$data['properties'] = '{"TITLE":"DESC"}';
try{
if(self::want_to_send())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->post_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_USERAGENT , 'facebook-php-3.1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$return = curl_exec($ch);
curl_close ($ch);
}
}
catch ( exception $e){
//throw new Exception($e);
// or
error_log(json_encode($data));
}
//return $return; // if you want return
}
}
$facebook = new Facebook();
// make a simple post test
$facebook->message(array( 'message' => 'The status header',
'link' => 'http://cekirdek.com.tr',
'picture' => 'http://domain.com/picture_url.png',
'name' => 'Name of the picture, shown just above it',
'description' => 'Full description explaining whether the header or the picture' ) );
function tratar_hotmail(){
$client_id = '0xxxxxxxxxxxxxxxx2';
$client_secret = 'Wyyyyyyyyyyyyyyyyyp';
$redirect_uri = 'http://example.com/';
$auth_code = $_GET["code"];
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://apis.live.net/v5.0/me/contacts?access_token='.$accesstoken.'';
$xmlresponse = curl_file_get_contents($url);
echo $xmlresponse;
$xml = json_decode($xmlresponse, true);
foreach($xml['data'] as $emails)
{
echo $emails['name'];
}
}
which outputs:
{ "error": { "code": "request_token_invalid", "message": "The access token isn't valid." } }
How can I get the request_access_token?
-EDIT-
Forgot the curl function
function curl_file_get_contents($url)
{
$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
curl_setopt($curl,CURLOPT_URL,$url); //The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5); //The number of seconds to wait while trying to connect.
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); //To stop cURL from verifying the peer's certificate.
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
Here's a class I've just thrown together for talking to the API:
<?php
// Note: the test script below assumes this is in a
// file called class.liverestapiconsumer.php
class LiveRESTAPIConsumer {
protected $accessTokenURI = 'https://login.live.com/oauth20_token.srf';
protected $restAPIBaseURI = 'https://apis.live.net/v5.0';
protected $appId;
protected $appSecret;
protected $accessToken;
protected $accessTokenExpires;
public function __construct($appId = NULL, $appSecret = NULL, $accessToken = NULL, $accessTokenExpires = NULL) {
$this->setAppId($appId);
$this->setAppSecret($appSecret);
$this->setAccessToken($accessToken);
$this->setAccessTokenExpires($accessTokenExpires);
}
public function getAppId() {
return $this->appId;
}
public function setAppId($appId) {
$this->appId = $appId;
}
public function getAppSecret() {
return $this->appSecret;
}
public function setAppSecret($appSecret) {
$this->appSecret = $appSecret;
}
public function getAccessToken() {
return $this->accessToken;
}
public function setAccessToken($accessToken) {
$this->accessToken = $accessToken;
}
public function getAccessTokenExpires() {
return $this->accessTokenExpires;
}
public function setAccessTokenExpires($accessTokenExpires) {
$this->accessTokenExpires = $accessTokenExpires;
}
public function accessTokenIsExpired() {
return $this->accessTokenExpires <= time();
}
public function fetchAccessToken($code, $redirectURI) {
if (!isset($code, $redirectURI, $this->appId, $this->appSecret)) {
throw new \Exception('Cannot fetch access token without an authorization code, redirect URI, application id and application secret');
}
$postFields = array(
'client_id' => $this->appId,
'client_secret' => $this->appSecret,
'code' => $code,
'redirect_uri' => $redirectURI,
'grant_type' => 'authorization_code'
);
$bodyData = http_build_query($postFields);
$headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
$ch = curl_init($this->accessTokenURI);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if (!$response = curl_exec($ch)) {
throw new \Exception('cURL request failed');
} else if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
throw new \Exception('Live API returned an error response code: '.curl_getinfo($ch, CURLINFO_HTTP_CODE));
} else if (!$responseObj = json_decode($response)) {
throw new \Exception('Cannot decode API response as JSON; data: '.$response);
} else if (!isset($responseObj->access_token)) {
throw new \Exception('Live API did not return an access token; error: '.$responseObj->error_description);
}
$this->setAccessToken($responseObj->access_token);
$this->setAccessTokenExpires(time() + $responseObj->expires_in);
}
protected function normalizeAPIPath($path) {
return $path[0] == '/' ? $path : '/'.$path;
}
public function apiCall($method, $path, array $params = array(), $data = NULL) {
if (!isset($this->accessToken)) {
throw new \Exception('Cannot make API requests without an access token');
} else if ($this->accessTokenIsExpired()) {
throw new \Exception('The currently defined access token has expired');
}
$ch = curl_init();
$url = $this->restAPIBaseURI.$this->normalizeAPIPath($path);
if ($params) {
$url .= '?'.http_build_query($params);
}
curl_setopt($ch, CURLOPT_URL, $url);
$method = trim(strtoupper($method));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
$headers = array();
$headers[] = 'Authorization: Bearer '.$this->accessToken;
if ((array) $data) {
$bodyData = json_encode($data);
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyData);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if (!$response = curl_exec($ch)) {
throw new \Exception('cURL request failed');
} else if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
throw new \Exception('Live API returned an error response code: '.curl_getinfo($ch, CURLINFO_HTTP_CODE));
} else if (!$responseObj = json_decode($response)) {
throw new \Exception('Cannot decode API response as JSON; data: '.$response);
}
return $responseObj;
}
}
...and the test script (yes, I am fully aware that my HTML skills are terrible - I don't write very much of it):
<?php
session_start();
require 'class.liverestapiconsumer.php';
// Your details as assigned by Microsoft
$appId = '<your client id>';
$appSecret = '<your client secret>';
// The public (internet) URL of this script
$localUrl = 'http://example.com/path/to/file.php';
// Work out whether we have a valid access token or not
$haveAccessToken = FALSE;
$accessTokenExpiresIn = 'N/A';
if (isset($_SESSION['accessToken'])) {
$now = time();
$haveAccessToken = $now < $_SESSION['accessTokenExpires'];
$accessTokenExpiresIn = ($_SESSION['accessTokenExpires'] - $now).' seconds';
if (!$haveAccessToken || isset($_GET['destroy'])) {
unset($_SESSION['accessToken'], $_SESSION['accessTokenExpires']);
}
if (isset($_GET['destroy'])) {
header('HTTP/1.1 302 Found');
header('Location: '.$localUrl);
}
}
function parse_body_data($str) {
$result = array();
$items = preg_split('/[\r\n]+/', $str, -1, PREG_SPLIT_NO_EMPTY);
foreach ($items as $item) {
$item = explode(':', $item, 2);
if (count($item) !== 2) {
return FALSE;
}
$result[trim($item[0])] = trim($item[1]);
}
return $result;
}
?>
<html>
<head>
<title>Live API Test</title>
<style>
div.label {
margin-top: 10px;
}
</style>
</head>
<body>
<div>Do we have an access token? <b><?php echo $haveAccessToken ? 'Yes <sup>(destroy)</sup>' : 'No'; ?></b> (Expires: <?php echo $accessTokenExpiresIn; ?>)</div>
<?php
if (isset($_POST['path'])) { // get something from the API
do { // do-while so we can easily break out of it on error
$client = new LiveRESTAPIConsumer($appId, $appSecret, $_SESSION['accessToken'], $_SESSION['accessTokenExpires']);
$path = $_POST['path'];
$method = $_POST['method'];
$paramStr = trim($_POST['params']);
$params = array();
if (!empty($paramStr)) {
parse_str($paramStr, $params);
}
if (($body = parse_body_data($_POST['body'])) === FALSE) {
echo "<div>Error: Body data invalid</div>";
break;
}
try {
$result = $client->apiCall($method, $path, $params, $body);
// The class returns the response data decoded to an object, so json_encode() it again for display
echo '
Result:
<pre>'.json_encode($result, JSON_PRETTY_PRINT).'</pre>
';
} catch (\Exception $e) {
echo "<div>Exception: ".$e->getMessage()."</div>";
break;
}
} while(FALSE);
echo '<div>Back</div>';
} else if (isset($_GET['code'])) { // handle redirect from live API
try {
$client = new LiveRESTAPIConsumer($appId, $appSecret);
$client->fetchAccessToken($_GET['code'], $localUrl);
$_SESSION['accessToken'] = $client->getAccessToken();
$_SESSION['accessTokenExpires'] = $client->getAccessTokenExpires();
echo '
<div>Successfully retrieved access token: '.$_SESSION['accessToken'].'</div>
<div>Go to form</div>
';
} catch (\Exception $e) {
echo '
<div>Exception: '.$e->getMessage().'</div>
<div>Back</div>
';
}
} else if ($haveAccessToken) { // Output form
echo '
<form action="'.$localUrl.'" method="post">
<div>
<div class="label">API Path</div>
<div><input name="path" type="text"></div>
</div>
<div>
<div class="label">Parameters (query string)</div>
<div><input name="params" type="text"></div>
</div>
<div>
<div class="label">Method</div>
<div>
<select name="method">
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
<option value="MOVE">MOVE</option>
<option value="COPY">COPY</option>
</select>
</div>
</div>
<div>
<div class="label">Body Data (key: value, newline separated)</div>
<div><textarea name="body" rows="10" cols="40"></textarea></div>
</div>
<input type="submit" value="Send Request">
</form>
API Reference
';
} else { // Don't have access token yet
$opts = array(
'client_id' => $appId,
'scope' => 'wl.basic',
'response_type' => 'code',
'redirect_uri' => $localUrl
);
echo '<div>Get access token</div>';
}
?>
</body>
</html>
All the parts that I think need explanation are commented. If you have any questions let me know.
Note that I haven't extensively tested the class, and it may be lacking when it comes to the more advanced API functionality. Seems to work fairly well for simple contact manipulation though.
In addition to the answer of DaveRandom and the comment of saveATcode: You should submit the redirect url given in $localUrl as a valid redirect url at account live application. They must be exactly the same or else you will get the 'The provided value for the input parameter 'redirect_uri' is not valid....' message. I just mentioned it because mine had a typo and i experienced the same error.
It's final try with PHP, if it fails, I'll try with JS. So my goal is to post on FB page as "Page name" through PHP: this is what I want to get
But all I get is shown pic below. Also, it's visible ONLY to this profile (not to friends/ppl who like/etc.).
This is my current code
function post_facebook($data=null, $redir = null){
$result = "";
require_once (ROOT. "/apps/configuration/models/ConfigurationItem.php");
require_once (ROOT . "/components/facebook/facebook.php");
$this->ConfigurationItem = new ConfigurationItem($this->getContext());
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_login');
$apiid=$row['value']; <= Correct apiid
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_pass');
$secret=$row['value']; <= Correct secret key
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'link' => $this->getLinkToLatestNews(),
'description' => '',
);
try {
$facebook->api('/PAGE ID/feed/', 'post', $attachment);
$result = "Facebook: Sent";
} catch (FacebookApiException $e) {
$result = "Facebook: Failed";
error_log($e);
}
} else {
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
exit;
}
echo $result;
exit;
//return $result;
}
What I'm doing wrong? I couldn't find anything in API documentation/top google results, only for JS. Thanks for help!
You'll need to make sure you're requesting the 'manage_pages' permission for the user. Once you've got that you can do $facebook->api('/me/accounts') and you'll receive a token back (along with the page info) that you can use to post on the page as the page.
I struggled with this most of the day, then found that not using setAccessToken(page_access_token) was the only thing preventing it from working for me. I found that in a stackoverflow post from 18 months ago. I'll put my solution here, for anyone who has this question in the future:
protected $scope = "email,publish_stream,manage_pages";
$url = "{$api_url}/{$fbusername}/accounts?access_token=".$access_token;
$response = json_decode(file_get_contents($url));
foreach($response->data as $data) {
try
{
$res = $this->SDK->setAccessToken($data->access_token);
$res = $this->SDK->api(
"{$data->id}/feed",
"POST",
array('link' => 'www.example.com',
'message' => 'This is a test message from php',)
);
log::debug(__FUNCTION__, print_r($res,true));
}
catch (Exception $e)
{
log::debug(__FUNCTION__, $e->getType().": ".$e->getMessage());
}
}
$feed = '/v2.8/' . $pageID . '/' . "feed";
$params = array(
"access_token" => AQUI TU TOKEN // see: https://developers.facebook.com/docs/facebook-login/access-tokens/
);
$params[ "link" ] = "https://zapatillasnewbalancebaratas.blogspot.com/2018/11/zapatilla-new-balance-ml515-col.html";
$params[ "message" ] = "Zapatilla New Balance Ml515 Col";
$params[ "method" ] = POST;
$graph_url = "https://graph.facebook.com" . $feed;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
echo $output;
curl_close($ch);