Authorization bearer - Wordpress REST API - php

Please i try to make REST API in Wordpress using the plugins WP OAuth Server and after create a new Client in Oauth server and generate a new access token, i could not connect by the Authorization in the header
function register_api_hooks2() {
register_rest_route(
'wp/v2/', '/beacon_products',
array(
'methods' => POST,
'callback' => 'beacon_products',
'args' => [
'id'
],
)
);
function beacon_products($request){
global $wpdb;
$current_user_id = get_current_user_id();
if ( empty( $current_user_id ) ) {
return new WP_Error( 'rest_not_logged_in', __( 'You are not currently logged in.' ), array( 'status' => 401 ) );
}
$result = array();
/* filter_var($_POST['beacon_id'], FILTER_VALIDATE_INT)*/
if(isset($_POST['eid']) && !empty($_POST['eid']) && isset($_POST['uid']) && !empty($_POST['uid'])){
try {
/* code */
}else{
return new WP_Error( 'Beacon introuvable','Aucun beacon associé au ses paramétres', array( 'status' => 404 ) );
}
} catch (Exception $e) {
return new WP_Error( 'Une erreur s\'est produite','Une erreur au niveau de serveur', array( 'status' => 500 ) );
}
}else{
return new WP_Error( 'parametre manquant','eid ou bien uid introuvable', array( 'status' => 403 ) );
}
return $result;
}
}

Lots to do here. You really need to read the documentation
You should use the permissions callback in your initial function and current_user_can instead of get_current_user_id to determine whether or not to run the callback function.
You should return your callback output using return new WP_REST_Response( $result, 200 );

Related

How to use the Facebook API per Page rather than as one app

I'm building an app that populates the database with Facebook posts, based on People that are in the database with a facebook page ID. If a facebook page ID is found it pulls in their posts, and saves the posts that use a particular hashtag to the database.
My problem is, the Facebook API keeps timing out, and i've only got 4 or 5 people listed at the moment. I see that you can get 250 requests per user, but i'm not sure i'm using the API in the correct way to get the posts per page.
Do I have to have the person login and personally give approval to do it this way? That doesn't really work for what i'm trying to do.
I've been using the PHP SDK found on Github, below is my code. I've been following it using the Graph Explorer, but one thing i'm not sure on is how to generate a token per page.
I'm currently using a manual token because i've no idea how to generate them per page, i've tried looking at the docs for both the Git PHP SDK, and also the Facebook API - and it's just not going in my brain, so i'm hoping somebody here might be able to spell it out to me a little better.
Thankyou for your help in advance, i'm a total newb to the Facebook API.
$apitoken = 'EAAF4azHPHh0BABSb7ZCPVv2U4pbBsZAfOMjA0tiTcKJoKKIsgfe0ZBZBf8ZAo5lZCHVh51WQzd1lvdOreA8Q4vU9F3ZCP9B1si1NWKZA7tiXxX1V06hNmQhT2tTZA8N27kinhiUDG0gDbYqLLZBZBRkGlAGuGdNZC3hdI6yJXLqd8QoPGWoi2LiLVmlqex2znHlbuqPzx0aq7YCVBQZDZD';
if( have_rows('social_networks') ):
while( have_rows('social_networks') ): the_row();
if( have_rows('facebook_group') ):
while( have_rows('facebook_group') ): the_row();
if(get_sub_field('facebook_username')){
require_once __DIR__ . '/vendor/autoload.php'; // change path as needed
require_once 'src/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '413876769201693',
'app_secret' => '1517da72a5c8ccaf5524d95a02d8481a',
'default_graph_version' => 'v3.3',
//'default_access_token' => '{access-token}', // optional
]);
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$username = $facebook_username;
$response = $fb->get("/$username?fields=fan_count,id,name,instagram_business_account,feed", "$apitoken");
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
//print_r($me);
////////////////////////////////////////////////////////
//////////////////// FACEBOOK///////////////////
//////////////////////////////////////////////////////
$facebook_likes = $me['fan_count'];
$facebook_posts = $me['feed'];
} endwhile; endif; endwhile; endif;
////////////////////////////////////////////////////////
//////////////////// FACEBOOK POSTS ///////////////////
//////////////////////////////////////////////////////
foreach($facebook_posts as $facebook_post){
$facebook_post_id = $facebook_post['id'];
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get("/$facebook_post_id?fields=likes.limit(0).summary(true),comments.limit(0).summary(true),shares,reactions.limit(0).summary(true),message", "$apitoken");
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$facebook_post_details = $response->getGraphUser();
$facebook_post_message = $facebook_post_details['message'];
$facebook_post_likes = $facebook_post_details['likes']['summary']['total_count'];
$facebook_post_comments = $facebook_post_details['comments'];
$facebook_post_shares = $facebook_post_details['shares'];
$post_id_fb = get_the_ID();
$args_fb = array(
'post_type' => 'campaigns',
);
$the_query_fb = new WP_Query( $args_fb );
if ( $the_query_fb->have_posts() ) : while ( $the_query_fb->have_posts() ) : $the_query_fb->the_post();
$campaign_id = get_the_ID();
$hashtag_fb = get_field('hashtag');
$post_title_fb = get_the_title(get_the_ID());
if (strpos($facebook_post_message, $hashtag_fb) !== false) {
if (get_page_by_title($facebook_post_message, OBJECT, 'campaign-posts')) {
wp_update_post(array(
'post_title'=> ' '.$facebook_post_message.' :facebook',
'post_type'=>'campaign-posts',
'post_content'=> $facebook_post_message,
'status' => 'published',
'meta_input' => array(
'likes' => $facebook_post_likes,
// 'shares' => $facebook_post_shares,
// 'reactions' => $facebook_post_reactions,
'influencer' => $post_id_fb,
'hashtag' => $hashtag_fb,
'platform'=> 'facebook',
'link' => $facebook_username,
)
));
wp_update_post(array(
'post_title'=> $post_title_fb,
'post_type'=> 'campaigns',
'post_content'=> get_the_content($campaign_id),
'status' => 'published',
'meta_input' => array(
'hashtag' => $hashtag_fb,
)
));
}else{
wp_insert_post(array(
'post_title'=> ' '.$facebook_post_message.' :facebook',
'post_type'=>'campaign-posts',
'post_content'=> $facebook_post_message,
'status' => 'published',
'meta_input' => array(
'likes' => $facebook_post_likes,
// 'shares' => $facebook_post_shares,
// 'reactions' => $facebook_post_reactions,
'influencer' => $post_id_fb,
'hashtag' => $hashtag_fb,
'platform'=> 'facebook',
'link' => $facebook_username,
)
));
wp_update_post(array(
'post_title'=> $post_title_fb,
'post_type'=> 'campaigns',
'post_content'=> get_the_content($campaign_id),
'status' => 'published',
'meta_input' => array(
'hashtag' => $hashtag_fb,
)
));
}
}
endwhile;
endif;
}

How to set delay on the client side before redirect?

After registering the user and clicking on the sign-up button, a message is displayed to confirm the email on the same page, but the page is immediately redirect and the user does not have enough time to view the message. I want to set a delay (e.g 5 seconds) before the redirect action, and after that, the redirect action will be performed.
if ( is_wp_error($user_id) ){
throw new Exception($user_id->get_error_message() , 401);
}
$data = get_userdata( $user_id );
$userdata = QA_Member::convert($data);
// generate new nonces
$msg = ae_get_option( 'user_confirm' ) ? __('You have registered an account successfully but are not able to join the discussions yet. Please confirm your email address first.', ET_DOMAIN) : __('You are registered and logged in successfully.', ET_DOMAIN) ;
$response = array(
'success' => true,
'code' => 200,
'msg' => $msg,
'data' => $userdata,
'redirect' => apply_filters( 'qa_filter_redirect_link_after_register', home_url() )
);
} catch (Exception $e) {
$response = array(
'success' => false,
'code' => $e->getCode(),
'msg' => $e->getMessage()
);
}
wp_send_json( $response );
}
The best way to do this is to implement the redirect in JS rather than in PHP. For example you can put this JS code to you ajax callback:
window.setTimeout( function(){
window.location = "PATH_TO_REDIRECT";
}, 100 );

In codeigniter api I am getting 400 bad request always in android but getting 200 in postman

this is my code for registration I am getting 400 bad request in response always when I hit api in android but in postman i am getting 200 response whats wrong with me. Please Help. Here is my controller code.
its validating registration data and saving it.
public function register_user_get()
{
$user_data = $_GET['user_details'];
$user_details_arr = array();
$user_details_arr = json_decode($user_data);
$username_exist = $this->apilogin_model->check_username_exists($user_details_arr->username);
if(!empty($username_exist))
{
$response = array(
'message'=>'Username is already exist',
'status'=>false
);
$this->response($response,200);
}
$referred_by = $user_details_arr->referred_by; //'company';
if($referred_by == 'company')
{
$referral_code = ROOT_REFERRAL_CODE;
$user = $this->apilogin_model->get_user_details_by_referral_code($referral_code);
if(empty($user))
{
// if referral code in invalid
$response = array(
'message'=>'Invalid Referral code',
'status'=>false
);
$this->response($response,200);
}
}
else if($referred_by == "manual")
{
$referral_code = $user_details_arr->referral_code;
$user = $this->apilogin_model->get_user_details_by_referral_code($referral_code);
if(empty($user))
{
$response = array(
'message'=>'Invalid Referral code',
'status'=>false
);
$this->response($response,200);
}
}
else
{
}
$parent_id = $user[0]->id;
$data = array(
'name' => $user_details_arr->name,
'username' => $user_details_arr->username,
'password' => md5($user_details_arr->password),
'paytm_no' => $user_details_arr->paytm_no,
'mobile_no' => $user_details_arr->mobile_no,
'email_id' => $user_details_arr->email_id,
'parent_id' => $parent_id,
'referral_code' => $this->generate_code(), // for generate 10 digit unique referral code
'is_deleted' => 'N',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
);
$res = $this->apilogin_model->save_affiliate_data($data);
$transaction_data = $this->parent_get($res,$parent_id,LEVEL_FOR_HELP);
$child_arr = array(
'sender_id' =>$res,
'receiver_id' =>COMPANY_ID,
'status'=>0,
'created_at' =>date('Y-m_d H:i:s')
);
array_push($transaction_data,$child_arr);
//$this->db->set($transaction_data);
$this->db->insert_batch(DB_PREFIX.'_transaction', $transaction_data);
if($res > 0)
{
// if data saved successfully
$response = array(
'message'=>'Registered Successfully',
'status'=>true
);
$this->response($response,200);
}
else
{
// if data doesn't saved successfully
$response = array(
'message'=>'Registration Failed',
'status'=>false
);
$this->response($response,200);
}
}
while I am calling same function in postman it working fine but while trying with android I am getting 400 bad request even I am not responding 400 anywhere in my code.
The reason why you are getting 400 is that you are trying to pass not allowed character such as(#) to CodeIgniter without encoding it.
In order to fix this try to encode the inputs from your android side
Or enable some special character such as (#) which been used in your registration email,... from Code Igniter configuration.
$config['permitted_uri_chars']

Magento API for customer login with session

I have searched a lot on Google & StackOverflow but still did not get the code or suggestion for the customer login from another server to create a session.
I used this code but it is not working:
$session = Mage::getSingleton( 'customer/session' );
Mage::app()->getStore()->setWebsiteId(1);
try {
$session->login( $email, $password );
$customer = $session->getCustomer();
return json_encode(array('status' => 'OK', 'userData' => $this->info($customer->getId())));
}
catch( Exception $e ) {
return json_encode(array('status' => 'error', 'message' => $e->getMessage()));
}

REST API connected to Facebook

I'm currently developing a REST API on my webserver for handling calls towards a Facebook application. This way I can check if the user has a valid license in our license database before allowing him/her to post to Facebook.
I'm using two separate calls at the moment, one to authorize the client with Facebook and store his/her access token in our license database. And another to actually publish to Facebook (and also other social platforms).
The Authorization seems to work. But the publishing always returns
{
"success": false,
"error": {
"message": "(#200) User must have accepted TOS",
"type": "FacebookRequestAppException",
"code": 200
}
}
I am currently working with a development app (on Facebook), without the proper permissions submitted, would this be the issue? And if so, how can I test it if I'm not allowed to use it?
The PHP code that triggers the Exception:
try {
$app = ( new FacebookRequest($app_session, 'POST', $post_url, array( 'appsecret_proof' => $appsecret_proof ) ) )->execute()->getGraphObject();
$output = array_merge( array( 'success' => true ), $output );
} catch(FacebookRequestException $e) {
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'FacebookRequestAppException', 'code' => $e->getCode() ) ) );
}
Edit:
The call:
$app_id = '1503912413161954';
$app_secret = '<app_secret_censored>';
$user_access_token = (string)$this->getIdentity()->facebook_token;
$app_access_token = (string)$this->getIdentity()->facebook_app_token;
$license_id = (int)$this->getIdentity()->license_id;
$user_account_type = (string)$this->getIdentity()->user_account_type;
$redirect_url = 'http://api.example.com/authorize';
include 'lib/fb_authorize.php';
The authorization code - have in mind that it's not yet complete, and that I'm using Yii Framwork as well to add connectivity to our database:
<?php
$http_session = new CHttpSession;
$http_session->setTimeout(60);
$http_session->setSessionName('fb_session');
$http_session->open();
require( 'vendor/autoload.php' );
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
FacebookSession::setDefaultApplication($app_id, $app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url, $app_id, $app_secret);
if ( isset( $user_access_token ) ) {
$user_session = new FacebookSession( $user_access_token );
try {
if ( !$user_session->validate() ) {
$user_session = null;
}
} catch ( Exception $e ) {
$user_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaUserSessionException', 'code' => $e->getCode() ) ) );
}
} else {
try {
$user_session = $helper->getSessionFromRedirect();
} catch( Exception $e ) {
$user_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaUserSessionException', 'code' => $e->getCode() ) ) );
}
}
if( isset( $user_session ) ) {
$appsecret_proof= hash_hmac('sha256', $user_session->getToken(), $app_secret);
if( isset( $http_session['getpages'] ) ) {
try {
// Get Page ID
$user = ( new FacebookRequest($user_session, 'GET', '/me/accounts', array( 'appsecret_proof' => $appsecret_proof ) ) )->execute()->getGraphObject();
$output = array( 'success' => true, 'user' => $user );
} catch(FacebookRequestException $e) {
$output = array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'FacebookRequestUserException', 'code' => $e->getCode() ) );
}
}
try {
$app_session = new FacebookSession( $app_access_token );
} catch ( Exception $e ) {
$app_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaAppSessionException', 'code' => $e->getCode() ) ) );
}
$c = new CDbCriteria();
$c->compare( 'id', $license_id );
$l = _Licenses::model()->find( $c );
$l->facebook_token = $user_session->getToken();
$l->facebook_app_token = $app_session->getToken();
$l->save();
$output = array_merge( $output, array( 'success' => true, 'user_token' => $l->facebook_token ) );
} else {
header( 'Location: '.$helper->getLoginUrl( array( 'manage_pages','publish_actions','public_profile' ) ) );
}
?>

Categories