I have a login form and using REST api service for login to the Wordpress. I can login to the wordpress using the form. But for some users wp_set_auth_cookie() function not working and I am getting 502 bad gateway. Can any one help me for sort out this?
This is my login endpoint function
function user_authentication() {
global $wp_rest_auth_cookie;
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
$user_data['user_login'] = $decoded['username'];
$user_data['user_password'] = $decoded['password'];
$user_data['remember'] = false;
$user = wp_signon( $user_data, false );
if ( !is_wp_error( $user ) ) {
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID);
wp_set_auth_cookie ( $user->ID );
$wp_rest_auth_cookie = wp_create_nonce('wp-rest') ;
$token = encrypt_decrypt('encrypt',$user->ID);
$name = get_name($user->ID);
$response = array(
'status'=> 'success',
'token' => $token,
'username' => $name,
'uname' => $user->ID
);
return json_encode( $response);
}else{
$response = array(
'status' => 'fail',
'message'=> "The username and password you entered don't match."
);
return json_encode($response);
}
die();
}
Add below code into your code and check wp_set_auth_cookie working or not.
$user_data['user_login'] = $decoded['username'];
$user_data['user_password'] = $decoded['password'];
$user_data['remember'] = true;
$user = wp_signon( $user_data, false );
if ( !is_wp_error( $user ) ) {
wp_set_auth_cookie( $user->ID, true );
} else {
echo $user->get_error_message();
}
I have solved this myself. There was some undefined variable errors along with the api response. Those errors was conflicting with the wp_set_auth_cookie() function. When I fixed those errors from my code, the 502 bad gate way issue get solved.
Related
I was using this code until yesterday and it ran without any problems
But it does not work any more
Get post count from instagram api
<?php
$username = 'instagram';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$full_name = $data['graphql']['user']['full_name'];
$follower = $data['graphql']['user']['edge_followed_by']['count'];
$follows = $data['graphql']['user']['edge_follow']['count'];
$posts = $data['graphql']['user']['edge_owner_to_timeline_media']['count'];
echo "<h2><a href='https://www.instagram.com/{$username}'>{$full_name}</a></h2>
<p><span>{$posts} posts</span> <span>{$follower} followers</span> <span>{$follows} following</span></p>";
}
} else {
echo 'Username not found.';
}
?>
I am trying to solve a problem, I am currently doing tests with stripe where the user pays for a small percentage of a reservation, this payment is reflected in my stripe account (test) and everything is in order. The problem is that there is an event that fails and it is retried to send from webhook, when this event is retried to send it causes me on the web page to be marked as fully paid, the ideal would be that this event always comes out as successful or that it does not return to try, hope there is a solution.
This is the code from the theme when the function take place of payment_intent.succeeded:
$endpoint_secret = esc_html ( wprentals_get_option('wp_estate_stripe_webhook','') );
$payload = #file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400); // PHP 5.4 or greater
exit('');
} catch(\Stripe\Error\SignatureVerification $e) {
// Invalid signature
http_response_code(400); // PHP 5.4 or greater
exit();
}
if ($event->type == "payment_intent.succeeded") {
$intent = $event->data->object;
$pay_type = intval($event->data->object->charges->data[0]->metadata->pay_type);
$userId = intval($event->data->object->charges->data[0]->metadata->user_id);
$depozit = intval($intent->amount);
if($pay_type==1){
$invoice_id = intval($event->data->object->charges->data[0]->metadata->invoice_id);
$booking_id = intval($event->data->object->charges->data[0]->metadata->booking_id );
$is_stripe=1;
wpestate_booking_mark_confirmed($booking_id,$invoice_id,$userId,$depozit,$user_email,$is_stripe);
$redirect=wpestate_get_template_link('user_dashboard_my_reservations.php');
http_response_code(200);
wp_redirect($redirect);exit();
}else if($pay_type==2){
$listing_id = intval($event->data->object->charges->data[0]->metadata->listing_id);
$is_featured = intval($event->data->object->charges->data[0]->metadata->featured_pay);
$is_upgrade = intval($event->data->object->charges->data[0]->metadata->is_upgrade);
$time = time();
$date = date('Y-m-d H:i:s',$time);
if($is_upgrade==1){
update_post_meta($listing_id, 'prop_featured', 1);
$invoice_id = wpestate_insert_invoice('Upgrade to Featured','One Time',$listing_id,$date,$current_user->ID,0,1,'' );
update_post_meta($invoice_id, 'invoice_status', 'confirmed');
wpestate_email_to_admin(1);
}else{
update_post_meta($listing_id, 'pay_status', 'paid');
$admin_submission_status = esc_html ( wprentals_get_option('wp_estate_admin_submission','') );
$paid_submission_status = esc_html ( wprentals_get_option('wp_estate_paid_submission','') );
if($admin_submission_status=='no' && $paid_submission_status=='per listing' ){
$post = array(
'ID' => $listing_id,
'post_status' => 'publish'
);
$post_id = wp_update_post($post );
}
// end make post publish
if($is_featured==1){
update_post_meta($listing_id, 'prop_featured', 1);
$invoice_id = wpestate_insert_invoice('Publish Listing with Featured','One Time',$listing_id,$date,$current_user->ID,1,0,'' );
update_post_meta($invoice_id, 'invoice_status', 'confirmed');
}else{
$invoice_id = wpestate_insert_invoice('Listing','One Time',$listing_id,$date,$current_user->ID,0,0,'' );
update_post_meta($invoice_id, 'invoice_status', 'confirmed');
}
wpestate_email_to_admin(0);
}
$redirect = wpestate_get_template_link('user_dashboard.php');
http_response_code(200);
wp_redirect($redirect);exit();
}
I am trying to use serverPilot API from my website. I have created simple functions like below for sample usage but its giving me error like below
Fatal error: Uncaught Error: Call to undefined function app_create()
I am new in PHP and don't know proper method to declare and use functions. Let me know what I am missing in this? My full PHP code is like below
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createApp'])){
$name = "sampleName";
$name = "hello";
$runtime ="php5.5";
$password = "Test#123";
$domains = array("www.example.com","example2.com");
app_create( $name, $sysuserid, $runtime, $domains = array());
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createDb'])){
$id = 1;
$name = "hello";
$username ="testuser";
$password = "Test#123";
database_create( $id, $name, $username, $password );
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createUser'])){
$id = 1;
$name = "hello";
$password = "Test#123";
sysuser_create( $id, $name, $password = NULL )();
}
class ServerPilot {
// variables
public $apiID = "";
public $apiKey = "";
public $decode;
// constants
const SP_API_ENDPOINT = 'https://api.serverpilot.io/v1/';
const SP_USERAGENT = 'ServerPilot-PHP/1.0';
const SP_HTTP_METHOD_POST = 'post';
const SP_HTTP_METHOD_GET = 'get';
const SP_HTTP_METHOD_DELETE = 'delete';
// error constants
const SP_MISSING_CONFIG = 'Missing config data';
const SP_MISSING_API = 'You must provide API credentials';
const SP_CURL_ERROR = 'Curl error code returned ';
public function __construct( $config = array() ) {
if( empty($config) ) throw new Exception(ServerPilot::SP_MISSING_CONFIG);
if( !isset($config['id']) || !isset($config['key']) ) throw new Exception(ServerPilot::SP_MISSING_API);
$this->apiID = $config['id'];
$this->apiKey = $config['key'];
$this->decode = ( isset($config['decode']) ) ? $config['decode'] : true;
}
public function sysuser_create( $id, $name, $password = NULL ) {
$params = array(
'serverid' => $id,
'name' => $name);
if( $password )
$params['password'] = $password;
return $this->_send_request( 'sysusers', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function app_create( $name, $sysuserid, $runtime, $domains = array() ) {
$params = array(
'name' => $name,
'sysuserid' => $sysuserid,
'runtime' => $runtime);
if( $domains )
$params['domains'] = $domains;
return $this->_send_request( 'apps', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function database_create( $id, $name, $username, $password ) {
$user = new stdClass();
$user->name = $username;
$user->password = $password;
$params = array(
'appid' => $id,
'name' => $name,
'user' => $user);
return $this->_send_request( 'dbs', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
private function _send_request( $url_segs, $params = array(), $http_method = 'get' )
{
// Initialize and configure the request
$req = curl_init( ServerPilot::SP_API_ENDPOINT.$url_segs );
curl_setopt( $req, CURLOPT_USERAGENT, ServerPilot::SP_USERAGENT );
curl_setopt( $req, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $req, CURLOPT_USERPWD, $this->apiID.':'.$this->apiKey );
curl_setopt( $req, CURLOPT_RETURNTRANSFER, TRUE );
// Are we using POST or DELETE? Adjust the request accordingly
if( $http_method == ServerPilot::SP_HTTP_METHOD_POST ) {
curl_setopt( $req, CURLOPT_HTTPHEADER, array('Content-Type: application/json') );
curl_setopt( $req, CURLOPT_POST, TRUE );
curl_setopt( $req, CURLOPT_POSTFIELDS, json_encode($params) );
}
if( $http_method == ServerPilot::SP_HTTP_METHOD_DELETE ) {
curl_setopt( $req, CURLOPT_CUSTOMREQUEST, "DELETE" );
}
// Get the response, clean the request and return the data
$response = curl_exec( $req );
$http_status = curl_getinfo( $req, CURLINFO_HTTP_CODE );
curl_close( $req );
// Everything when fine
if( $http_status == 200 )
{
// Decode JSON by default
if( $this->decode )
return json_decode( $response );
else
return $response;
}
// Some error occurred
$data = json_decode( $response );
// The error was provided by serverpilot
if( property_exists( $data, 'error' ) && property_exists( $data->error, 'message' ) )
throw new ServerPilotException($data->error->message, $http_status);
// No error as provided, pick a default
switch( $http_status )
{
case 400:
throw new ServerPilotException('We couldn\'t understand your request. Typically missing a parameter or header.', $http_status);
break;
case 401:
throw new ServerPilotException('Either no authentication credentials were provided or they are invalid.', $http_status);
break;
case 402:
throw new ServerPilotException('Method is restricted to users on the Coach or Business plan.', $http_status);
break;
case 403:
throw new ServerPilotException('Forbidden.', $http_status);
break;
case 404:
throw new ServerPilotException('You requested a resource that does not exist.', $http_status);
break;
case 409:
throw new ServerPilotException('Typically when trying creating a resource that already exists.', $http_status);
break;
case 500:
throw new ServerPilotException('Something unexpected happened on ServerPilot\'s end.', $http_status);
break;
default:
throw new ServerPilotException('Unknown error.', $http_status);
break;
}
}
}
?>
<html>
<body>
<form action="server.php" method="post">
<input type="submit" name="createApp" value="Create APP" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createDb" value="Create DB" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createUser" value="Create USER" />
</form>
</body>
</html>
Its giving error in all three functions same. Letme know if someone can help me for come out from this issue, I am trying from last two hours and its not working.
Thanks
You can not access class function directly like this.You need to create class object first and then call the function with object variable.
It's better to save class code in a separate file and include it in the above give file at the top to avoid errors.
E.g:
// $config as array, You need it to set in construct method.check construct method.
$config = [
"id" => ENTER_ID,
"key" => ENTER_KEY,
"decode" => true, //Optional you can leave this ,default is true anyway.
];
$ServerPilot_Obj = New ServerPilot($config);
$ServerPilot_Obj->app_create( $name, $sysuserid, $runtime, $domains = array());
Just implemented facebook login on my test site, and it seems too simple to be true?
I am using these two from GitHub
https://github.com/Lusitanian/PHPoAuthLib
https://github.com/artdarek/oauth-4-laravel
To implement this I added a button:
{{ link_to_action('UserController#loginWithFacebook', 'Facebook Login in', $parameters = array(), $attributes = array('class' => 'btn btn-primary fb-login-btn')); }}
And then modifiying the example login method to authorise the user after success:
public function loginWithFacebook() {
$code = Input::get( 'code' );
$fb = OAuth::consumer( 'Facebook' );
if ( !empty( $code ) ) {
$token = $fb->requestAccessToken( $code );
$result = json_decode( $fb->request( '/me' ), true );
// ADDED SECTION
$newUser = User::create(
array(
'email' => $result['email']
)
);
$user = User::find($newUser->id);
Auth::login($user);
return Redirect::to('/');
} else {
$url = $fb->getAuthorizationUri();
return Redirect::to( (string)$url );
}
}
This works, which has surprised me... is this really all it takes?
The question im asking really is would this be the way its intended to be used? The response is used to create a user, then log them in after with their ID.
I only use their email, since they only need to login using the facebook button. In the future I could prompt them to add a password so they don't always have to use facebook login but the basics of this is correct?
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode($fb->request( '/me?fields=id,name,first_name,last_name,email,photos' ), true);
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name']. $result['email'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
//echo('http://graph.facebook.com/'.$result['id'].'/picture?type=large<br>');
//dd($result);
$user = \User::where("email",$result['email'])->first();
if($user!=NULL){
$userxx = Sentry::findUserByLogin($result['email']);
Sentry::login($userxx, false);
return Redirect::to('Beşiktaş');
}
else
{
$k=str_random(8);
$user = Sentry::register(array(
'activated' => 1,
'facebook' => 1,
'password' => $k,
'email' => $result['email'],
'first_name' =>$result['first_name'],
'last_name' => $result['last_name'] ,
'avatar' => 'http://graph.facebook.com/'.$result['id'].'/picture?type=large',
));
Sentry::login($user, false);
return Redirect::to('Beşiktaş');
}
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
im working with laravel 4 framework and magento api soap. this is my login method:
public function APIauthentication( $apiUser, $apiKey ) {
$error = array();
if( empty( $apiUser ) ) {
$error[] = 'Unknown api user';
}
if( empty( $apiKey ) ) {
$error[] = 'Invalid api key';
}
if( empty( $error ) ) {
$client = $this->_getClient();
$token = $client->login( $apiUser, $apiKey );
$this->_setToken( $token );
return $this->_apiJsonResult( $token );
} else {
return $this->_apiJsonResult( $error );
}
}
now im getting on laravel screen SoapFault Access denied.
i need to return error string if url is incorrect or API user/key is incorrect.
like this:
return Redirect::to('user/stores/magento/')->with('status', 'apie user or key is incorrect');
how to do this? there is fault code but i dont know how to log that
http://www.magentocommerce.com/api/soap/introduction.html#Introduction-GlobalAPIFaults
A SoapFault is an Exception that needs to be caught. The fault code and error string can be accessed via the Exception. Also, make sure the SoapClient is instantiated with the 'exceptions' option set to true, otherwise I believe PHP just throws a fatal error.
if( empty( $error ) ) {
$client = $this->_getClient();
try {
$token = $client->login( $apiUser, $apiKey );
} catch (SoapFault $e) {
// login failed logic
$faultcode = $e->faultcode; // ex: 2
$message = $e->faultstring; // ex: Access denied.
// return redirect, etc...
}
// login successful logic
$this->_setToken( $token );
return $this->_apiJsonResult( $token );
} else {
return $this->_apiJsonResult( $error );
}