Woocommerce Login Custome API Endpoint - wordpress

I am developing an app using woocommerece store and using the Woocommerce REST API for Fetching the Products and Order details, but now I am facing the problem in login because Woocommerce didn't provide this type of API.
So I am creating a custom endpoint and trying this but I am getting the error 404, no rest route available.
Here is my custome end point which i registered.
add_action( 'rest_api_init', function () {
register_rest_route( 'wc/v2', '/login/)', array(
'methods' => 'POST',
'callback'=> 'my_awesome_func',
'args' => array(
),
) );
} );
Here is the login of Login but i think i am doing anything wrong at someplace so please check and help me .
function my_awesome_func( WP_REST_Request $request ) {
global $wpdb;
$username = $request['email'];
$password = $request['password'];
$db = new DbOperation();
$response = array();
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$results = $wpdb->get_row( "SELECT ID FROM rd_users WHERE user_email='".$username."'");
$activation_id = $results->ID;
$activation_key = get_user_meta( $activation_id, 'has_to_be_activated', true );
if($activation_key != false ){
$results = 2;//if activation key exists than show the error
}
else{
$user_verify = wp_signon( $login_data, false );
if ( is_wp_error($user_verify) )
{
$results = 0; //show invalid username and password.
}
else {
$results = 1; //login success.
}
}
if ($results== 1) {
$user_info = get_userdata($student[0]->ID);
$response['id'] = $user_info->ID;
$response['name'] = $user_info->display_name;
$response['fname'] = $user_info->first_name;
$response['lname'] = $user_info->last_name;
$response['email'] = $user_info->user_email;
$response['status'] = 1;
$response["error"] = false;
$response['message'] = "You have successfully Logedin!";
} else {
if($results == 0){
$response['status'] = 0;
$response["error"] = true;
$response['message'] = "Invalid username or password";
}
else{
$response['status'] = 2;
$response["error"] = true;
$response['message'] ="Your account has not been activated yet.
To activate it check your email and clik on the activation link.";
}
}
return $response;
}

See what i have found,
used https authentication. In postman, instead of using oAuth1.0 as the authentication, use Basic authentication and pass consumer key as the username. And the password should be consumer secret.
I hope that would work.

Related

Login WP - Connect single field to an external api

I made a plugin to allow wordpress login with external api.
Everything works, now what I have to do is that when a user logs in for the first time, the plugin checks to see if it is already present on wp, and where it was not already present, it creates a new user by taking behind username, email and password.
The new user is created but I would like it to bring with it also the id field from the external api saving it in an ACF field.
This is the code created so far:
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
$user_email_key = 'email';
$password_key = 'password';
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
// Check user exists locally
$user_exists = wp_authenticate_username_password(null, $username, $password);
if ($user_exists && $user_exists instanceof WP_User) {
$user = new WP_User($user_exists);
return $user;
}
// Build the POST request
$login_data = array(
$user_email_key => $username,
$password_key => $password
);
$auth_args = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'sslverify' => false,
'body' => $login_data
);
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$response_code = $response['response']['code'];
if ($response_code == 400) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __("<strong>Error</strong>: Your username or password are incorrect."));
} else if ($response_code == 200) {
// External user exists, try to load the user info from the WordPress user table
$userobj = new WP_User();
// Does not return a WP_User object but a raw user object
$user = $userobj->get_data_by('email', $username);
if ($user && $user->ID) {
// Attempt to load the user with that ID
$user = new WP_User($user->ID);
}
} else {
// The user does not currently exist in the WordPress user table.
// Setup the minimum required user information
$userdata = array(
'user_email' => $username,
'user_login' => $username,
'user_pass' => $password
);
// A new user has been created
$new_user_id = wp_insert_user($userdata);
// Assign editor role to the new user (so he can access protected articles)
wp_update_user(
array(
'ID' => $new_user_id,
'role' => 'editor'
)
);
// Load the new user info
$user = new WP_User ($new_user_id);
}
}
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}
Anyone have any way how to help me?
Resolved! I hope this will help those who have found themselves in the same situation as me:
add_filter('authenticate', 'au_auth', 10, 3);
add_filter('register_new_user', 'au_registration', 10, 3);
// add_filter('profile_update', 'au_profile_update', 10, 3);
// add_filter('edit_user_profile_update', 'au_profile_edit', 10, 3);
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
$auth_args = [
'method' => 'POST',
'headers' => [
'Content-type: application/x-www-form-urlencoded',
],
'sslverify' => false,
'body' => [
'email' => $username,
'password' => $password,
],
];
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$body = json_decode($response['body'], true);
$response_status_code = $response['response']['code'];
$success = $body !== 'KO';
if (!$success) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __('<strong>Error</strong>: Your username
or password are incorrect.'));
} elseif ($success) {
$idExternal = $body['Id'];
$nome = $body['Name'];
$cognome = $body['Surname'];
$email = $body['Email'];
$userobj = new WP_User();
$user = $userobj->get_data_by('email', $email);
if ($user && $user->ID) {
$user = new WP_User($user->ID);
} else {
$userdata = [
'user_email' => $email,
'user_login' => join(' ', [$name, $surname]),
'user_pass' => '----',
];
$new_user_id = wp_insert_user($userdata);
$new_user_composite_id = 'user_' . $new_user_id;
update_field('field_60084ad3970a8', $idExternal, $new_user_composite_id);
update_field('field_5f22ca201c7b0', $name, $new_user_composite_id);
update_field('field_5f22ccd498f40', $surname, $new_user_composite_id);
update_field('field_5f22ce7b7c1db', $email, $new_user_composite_id);
$user = new WP_User($new_user_id);
}
}
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}

how to login user throught rest api in wordpress

hey i just creat a rest api in wordpress for login its work on old user but when i creat a new user its show invalid user name 400 error
my code is its work on old user but error in new user like this
{"code":400,"msg":"Invalid username"}
and in register api how to convert user password to wordpress hash password
add_action( 'rest_api_init', 'register_api_hooks' );
function register_api_hooks() {
register_rest_route(
'custom-plugin', '/login/',
array(
'methods' => 'GET',
'callback' => 'login',
)
);
}
function login($request){
$creds = array();
$creds['user_login'] = $request["username"];
$creds['user_password'] = md5($request["password"]);
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
{
$user->get_error_message();
return $myArray = ['code'=>400, 'msg'=>'Invalid username'];
}
else
{
$token = wp_get_session_token();
return $myArray = ['code'=>200, 'msg'=>'Success', 'user'=> $user ,'token'=> $token];
}
}
add_action( 'after_setup_theme', 'custom_login' );

How avoid form resubmission on page refresh?

I'm doing a simple feedback form on WordPress. And like many people, I encountered the problem of resending the form when refresh the browser page. I know that this problem is solved through the use of the pattern "Post/Redirect/Get". Which says that you need after processing the data $_POST, request the same page using the $_GET method. But I can not use the result of the wp_mail function for redirection.
if(wp_mail($email, $email_subject, $email_message, $headers)) {
add_action('send_headers', 'simplemail_add_header');
}
function simplemail_add_header() {
header("Location: http://google.com");
}
It just does not work.
UPD
Here is my full code:
class SimpleMailer {
private $nonce = 'feedback_nonce';
public function __construct() {
add_action('phpmailer_init', array($this, 'simplemail_smtp_config'));
add_shortcode('simplemail', array($this, 'simplemail_sendmail'));
}
public function simplemail_smtp_config($phpmailer) {
$phpmailer->isSMTP();
$phpmailer->SetFrom("admin#mail.com");
$phpmailer->addAddress("sender#mail.com");
$phpmailer->Host = "ssl://smtp.mail.com";
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 465;
$phpmailer->Username = "admin#mail.com";
$phpmailer->Password = "password";
$phpmailer->SMTPSecure = 'ssl';
}
public function simplemail_sendmail($shortcode_attributes) {
global $wp;
$result = "";
$error = false;
$data = array();
$required_fields = array("feedback_name", "feedback_email", "feedback_message");
$atts = shortcode_atts(array(
"email" => get_bloginfo('admin_email'),
"form_action" => home_url($wp->request),
"form_cls" => '',
"mail_subject" => "Feedback message from",
"pls_name" => 'Your Name',
"pls_email" => 'Your E-mail Address',
"pls_message" => 'Your Message',
"label_submit" => 'Submit',
"error_common" => 'There was some mistake. Try again, a little later.',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks for your e-mail! We\'ll get back to you as soon as we can.'
), $shortcode_attributes);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$data[$field] = trim(strip_tags($value));
}
foreach ($required_fields as $required_field) {
$value = trim($data[$required_field]);
if(empty($value)) {
$error = true;
$result = $atts['error_empty'];
}
}
if(!empty($data["feedback_blank"])) {
$error = true;
$result = $atts['error_empty'];
}
if(!is_email($data['feedback_email'])) {
$error = true;
$result = $atts['error_noemail'];
}
if(!wp_verify_nonce($data[$this->nonce],'simplemail_nonce')) {
$error = true;
$result = $atts['error_common'];
}
if ($error == false) {
$email_subject = $atts['mail_subject']." [".get_bloginfo('name')."]";
$email_message = $data['feedback_message']."\n\n";
$headers = "From: ".$data['feedback_name']." <".$data['feedback_email'].">\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
if(wp_mail(null, $email_subject, $email_message, $headers)) {
add_action('send_headers', array($this, 'simplemail_add_header', 10, $atts['form_action']));
// wp_redirect( 'http://google.com', 301 );
// exit;
}
$data = array();
$result = $atts['success'];
}
}
return $this->simplemail_draw_form($atts, $data, $result);
}
public function simplemail_draw_form($atts, $data, $result) {
$output = "<form action='".$atts['form_action']."' class='".$atts['form_cls']."' method='post'>".PHP_EOL.
"<input type='text' name='feedback_name' placeholder='".$atts['pls_name']."' value='".#$data['feedback_name']."'>".PHP_EOL.
"<input type='text' name='feedback_blank'>".PHP_EOL.
"<input type='email' name='feedback_email' placeholder='".$atts['pls_email']."' value='".#$data['feedback_email']."'>".PHP_EOL.
"<textarea name='feedback_message' cols='30' rows='10' placeholder='".$atts['pls_message']."'>".#$data['feedback_message']."</textarea>".PHP_EOL;
$output .= wp_nonce_field('simplemail_nonce', $this->nonce, false);
$output .= ($result != "") ? '<div class="feedback-info">'.$result.'</div>' : '<div class="feedback-info"></div>';
$output .= "<button type='submit'>".$atts['label_submit']."</button>".PHP_EOL."</form>";
return $output;
}
public function simplemail_add_header($location) {
header("Location: {$location}");
}
}
$simplemailer = new SimpleMailer();
And I get this error if I uncomment the redirect. And nothing at all, if you try to use simplemail_add_header
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/nav-menu-template.php:256) in /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/pluggable.php on line 1216
I think you need to add a token in a hidden textbox and within the form to be submitted, the text in this text box will be the token and it need to change on every page load. Save this token in a session variable. Then add a condition at the top of the page to validate the token, if the token is different kill the loading process or display a message or whatever you feel is needed. You may also add token longevity to allow submitting of a page within certain amount of time.
The token creation, token validation and token longevity are normally a function somewhere that is called as needed and form different pages.
Edit:
If all you want is redirect the user to a different page then do:
if(mail succeed) {
header('location: thankyou.html');
}

Send sms to different numbers based on the recipient Twilio and Contact form 7 - Wordpress

I'm working on integrating Twilio with Wordpress and Contact form 7 plugin.
I made a hook for Contact form 7 to send sms with Twilio on form submission. It works.
My next step is to send to different numbers based on the recipient ( I have 3 different location in the contact form 7 and the recipient changes based on the chosen location).
I can't make it work.
Below is my code, any thoughts?
This hook works and sends to 1 number only
add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function() {
$sid = 'xxx';
$token = 'xxx';
$client = new Client($sid, $token);
$to = '+1111111111';
$client->messages->create(
// the number you'd like to send the message to
$to,
array(
'from' =>'+1212121211',
'body' => "form submitted"
)
);
}
This is the second part, I can't make it work.
global $to;
function wpcf7_do_something (&$WPCF7_ContactForm) {
if ($WPCF7_ContactForm->mail['recipient'] = "bla#bla.com") {
$to = '+1XXXXXXXXX';
} else if($WPCF7_ContactForm->mail['recipient'] = "blabla#blabla.com") {
$to = '+1x1x1x1x1x';
} else {
$to = "+1000000000"
}
}
add_action('wpcf7_before_send_mail', 'wpcf7_do_something');
add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function() {
$sid = 'xxxxxxx';
$token = 'xxxxxxx';
$client = new Client($sid, $token);
$client->messages->create(
// the number you'd like to send the message to
$to,
array(
'from' =>'+1XXXXXXXXX',
'body' => "form submitted"
)
);
}
Twilio developer evangelist here.
From what I can tell from other Stack Overflow and Stack Exchange questions, you actually get passed the form to the wpcf7_mail_sent hook, so you don't need the two hooks like you have been trying. Something like the following should work:
add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' );
function your_wpcf7_mail_sent_function($cf7form) {
if ($cf7form->mail['recipient'] = "bla#bla.com") {
$to = '+1XXXXXXXXX';
} else if($cf7form->mail['recipient'] = "blabla#blabla.com") {
$to = '+1x1x1x1x1x';
} else {
$to = "+1000000000"
}
$sid = 'xxx';
$token = 'xxx';
$client = new Client($sid, $token);
$client->messages->create(
// the number you'd like to send the message to
$to,
array(
'from' =>'+1212121211',
'body' => "form submitted"
)
);
}
Let me know if that helps at all.

Number of users currently viewing forum

I am trying to input a feature that vBulletin has on my forum which is using BBpress. It's to display how many users are currently viewing a particular forum or thread. I am trying to edit the CBX Users Online plugin because it has a function to display how many users are currently viewing a current page so I am trying to figure out how to edit it for each individual forum instead of the current page.
This is the function that logs the user's visit on the current page:
public function log_visit($page_url = '', $page_title = '') {
global $wpdb;
if (empty($page_url))
$page_url = sanitize_text_field($_SERVER['REQUEST_URI']);
//$page_url = bbp_forum_permalink($forum_id);
if (empty($page_title))
$page_title = self::get_title();
$referral = CBXUseronlineHelper::get_referral();
$user_ip = CBXUseronlineHelper::get_ipaddress();
$user_agent = CBXUseronlineHelper::get_useragent();
$current_user = wp_get_current_user();
$bots = CBXUseronlineHelper::get_bots();
$bot_found = false;
$user_id = '';
foreach ($bots as $name => $lookfor)
{
if (stristr($user_agent, $lookfor) !== false)
{
$user_id = $_COOKIE[CBX_USERONLINE_COOKIE_NAME];
$user_name = $name;
$username = $lookfor;
$user_type = 'bot';
$bot_found = true;
break;
}
}
// If No Bot Is Found, Then We Check Members And Guests
if (!$bot_found)
{
if ($current_user->ID)
{
// Check For Member
$user_id = $current_user->ID;
$user_name = $current_user->display_name;
$user_type = 'user';
$where = $wpdb->prepare("WHERE user_id = %d", $user_id);
}
elseif (isset($_COOKIE[CBX_USERONLINE_COOKIE_NAME])){
$user_id = $_COOKIE[CBX_USERONLINE_COOKIE_NAME];
$user_name = (!empty($_COOKIE['comment_author_' . COOKIEHASH])) ? trim(strip_tags($_COOKIE['comment_author_' . COOKIEHASH])): __('Guest', 'cbxuseronline');
$user_type = 'guest';
}
}
else{
return;
}
$mobile = (CBXUseronlineHelper::is_mobile())? 1: 0;
// Current GMT Timestamp
$timestamp = current_time('mysql');
$cbxuseronline_tablename = CBXUseronlineHelper::get_tablename();
$userid = $user_id;
$cbxuseronline_basics = get_option('cbxuseronline_basics');
$refresh_time = isset($cbxuseronline_basics['refreshtime'])? intval($cbxuseronline_basics['refreshtime']): 3600;
// Purge table
$real_purge = $wpdb->query( $wpdb->prepare( "DELETE FROM $cbxuseronline_tablename WHERE userid = %s OR timestamp < DATE_SUB(%s, INTERVAL %d SECOND)", $userid, $timestamp, $refresh_time ) );
if($real_purge !== false){
do_action('cbxuseronline_record');
}
// Insert Users
$data = compact( 'timestamp', 'user_type', 'userid', 'user_name', 'user_ip', 'user_agent', 'page_title', 'page_url', 'referral', 'mobile' );
$data = stripslashes_deep( $data );
$wpdb->replace( $cbxuseronline_tablename, $data );
// Count Users Online
$cbxuseronline_mostonline_now = intval( $wpdb->get_var( "SELECT COUNT( * ) FROM $cbxuseronline_tablename" ) );
$cbxuseronline_mostonline_old = get_option('cbxuseronline_mostonline');
if($cbxuseronline_mostonline_old === FALSE || ($cbxuseronline_mostonline_now > intval($cbxuseronline_mostonline_old['count'])) ){
update_option('cbxuseronline_mostonline', array(
'count' => $cbxuseronline_mostonline_now,
'date' => current_time( 'timestamp' )
));
}
}
I'm pretty sure that this is the piece of code responsible for logging the user's visit on the current page:
$page_url = sanitize_text_field($_SERVER['REQUEST_URI']);
But I have tried to edit it to something like this:
$page_url = bbp_forum_permalink($forum_id);
but unfortunately that doesn't work.
Does anyone know what I'm doing wrong please?
Thanks in advance for any info / advice given.

Resources