| Server IP : 13.126.101.145 / Your IP : 216.73.217.37 Web Server : Apache/2.4.52 (Ubuntu) System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64 User : www-data ( 33) PHP Version : 8.3.17 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/html/rentals_updated/wp-content/plugins/api_manager/includes/ |
Upload File : |
<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly
class SAP_Endpoint {
// Constructor to register the custom endpoint
public function __construct() {
add_action('init', [$this, 'register_custom_endpoint']);
}
// Register a custom endpoint
public function register_custom_endpoint() {
add_rewrite_rule('^sap-endpoint/?$', 'index.php?sap_endpoint=1', 'top');
add_filter('query_vars', [$this, 'add_query_var']);
add_action('template_redirect', [$this, 'handle_custom_endpoint']);
}
// Add custom query var for detection
public function add_query_var($query_vars) {
$query_vars[] = 'sap_endpoint';
return $query_vars;
}
// Handle requests to the custom endpoint
public function handle_custom_endpoint() {
if (get_query_var('sap_endpoint') != 1) {
return;
}
// Include WordPress functions for DB
global $wpdb;
// Basic Auth credentials
$valid_username = 'RMS_USER'; // Replace with your username
$valid_password = 'RMS_iTroSys123!'; // Replace with your password
// Basic Authentication
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
header('WWW-Authenticate: Basic realm="Restricted Area"');
header('HTTP/1.0 401 Unauthorized');
echo json_encode(['error' => 'Unauthorized: Missing credentials']);
exit;
}
if ($_SERVER['PHP_AUTH_USER'] !== $valid_username || $_SERVER['PHP_AUTH_PW'] !== $valid_password) {
header('HTTP/1.0 401 Unauthorized');
echo json_encode(['error' => 'Unauthorized: Invalid credentials']);
exit;
}
// Parse the incoming data
$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);
if (empty($data['contract_number']) || empty($data['customer_sap_id']) || empty($data['invoice_number']) || empty($data['invoice_date']) || empty($data['irn_number']) || empty($data['qr_code'])) {
header('HTTP/1.0 400 Bad Request');
echo json_encode(['error' => 'Invalid data: Missing required fields']);
exit;
}
// Sanitize data
$contract_number = sanitize_text_field($data['contract_number']);
$customer_sap_id = sanitize_text_field($data['customer_sap_id']);
$invoice_number = sanitize_text_field($data['invoice_number']);
$invoice_date = sanitize_text_field($data['invoice_date']);
$irn_number = sanitize_text_field($data['irn_number']);
$qr_code = sanitize_text_field($data['qr_code']);
// Database table name
$table_name = $wpdb->prefix . 'custom_data';
// Ensure the table exists
$wpdb->query("
CREATE TABLE IF NOT EXISTS $table_name (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
contract_number INT,
customer_sap_id INT,
invoice_number VARCHAR(255) NOT NULL,
invoice_date DATE,
irn_number LONGTEXT NOT NULL,
qr_code LONGTEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (id)
) " . $wpdb->get_charset_collate()
);
// Insert the data
$inserted = $wpdb->insert($table_name, [
'contract_number' => $contract_number,
'customer_sap_id' => $customer_sap_id,
'invoice_number' => $invoice_number,
'invoice_date' => $invoice_date,
'irn_number' => $irn_number,
'qr_code' => $qr_code,
'created_at' => current_time('mysql'),
]);
// Return the response
if ($inserted) {
header('Content-Type: application/json');
echo json_encode(['success' => 'Data saved successfully']);
} else {
header('HTTP/1.0 500 Internal Server Error');
echo json_encode(['error' => 'Failed to save data']);
}
exit;
}
}
// Initialize the endpoint
new SAP_Endpoint();
// class SAP_Endpoint {
// public function __construct() {
// add_action('rest_api_init', [$this, 'register_endpoint']);
// }
// // Register the custom REST API endpoint
// public function register_endpoint() {
// register_rest_route('woocommerce/v1', '/receive-data', [
// 'methods' => 'POST',
// 'callback' => [$this, 'handle_post_request'],
// 'permission_callback' => [$this, 'validate_request'], // Use WooCommerce authentication
// ]);
// }
// // Validate the request using WooCommerce's authentication
// public function validate_request() {
// // Debug: Log all server variables related to authorization
// error_log('SERVER AUTHORIZATION DEBUG:');
// error_log('HTTP_AUTHORIZATION: ' . print_r($_SERVER['HTTP_AUTHORIZATION'] ?? 'Not Set', true));
// error_log('PHP_AUTH_USER: ' . print_r($_SERVER['PHP_AUTH_USER'] ?? 'Not Set', true));
// error_log('PHP_AUTH_PW: ' . print_r($_SERVER['PHP_AUTH_PW'] ?? 'Not Set', true));
// // Check if Authorization header is present
// $authorization = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
// if (empty($authorization)) {
// error_log('No Authorization header found');
// return false;
// }
// // Remove 'Basic ' from the header
// $authorization = str_replace('Basic ', '', $authorization);
// // Decode the credentials
// $decoded = base64_decode($authorization);
// error_log('Decoded Credentials: ' . $decoded);
// // Split credentials
// $credentials = explode(':', $decoded);
// if (count($credentials) !== 2) {
// error_log('Invalid credential format');
// return false;
// }
// $consumer_key = $credentials[0];
// $consumer_secret = $credentials[1];
// // Validate against your WooCommerce API credentials
// $valid_key = 'ck_81633c6b96652842d43ab7f9d7e94207ece685f8';
// $valid_secret = 'cs_f8b81590315bc80222bb7c3f89c33203933c939f';
// // Debug: Log incoming credentials
// error_log('Incoming Key: ' . $consumer_key);
// error_log('Incoming Secret: ' . $consumer_secret);
// // Strict comparison of credentials
// if ($consumer_key === $valid_key && $consumer_secret === $valid_secret) {
// error_log('Credentials Validated Successfully');
// return true;
// }
// error_log('Credential Validation Failed');
// return false;
// }
// // public function validate_request() {
// // // Authentication is handled by WooCommerce's built-in REST API system
// // return current_user_can('manage_woocommerce');
// // }
// // Handle the POST request
// public function handle_post_request(WP_REST_Request $request) {
// // Get the POST data
// $data = $request->get_json_params();
// // Validate the payload
// if (empty($data) || !isset($data['field_1']) || !isset($data['field_2'])) {
// return new WP_Error('invalid_data', 'Invalid or missing data', ['status' => 400]);
// }
// // Insert the data into a custom database table
// global $wpdb;
// $table_name = $wpdb->prefix . 'received_data'; // Replace with your table name
// // Insert data into the database
// $result = $wpdb->insert($table_name, [
// 'field_1' => sanitize_text_field($data['field_1']),
// 'field_2' => sanitize_text_field($data['field_2']),
// 'created_at' => current_time('mysql'),
// ]);
// // Check for database errors
// if ($result === false) {
// return new WP_Error('db_error', 'Failed to save data', ['status' => 500]);
// }
// return new WP_REST_Response(['message' => 'Data received successfully'], 200);
// }
// // Create the custom database table on plugin activation
// public static function create_database_table() {
// global $wpdb;
// $table_name = $wpdb->prefix . 'received_data'; // Replace with your table name
// $charset_collate = $wpdb->get_charset_collate();
// $sql = "CREATE TABLE IF NOT EXISTS $table_name (
// id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
// field_1 VARCHAR(255) NOT NULL,
// field_2 VARCHAR(255) NOT NULL,
// created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
// PRIMARY KEY (id)
// ) $charset_collate;";
// require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// dbDelta($sql);
// }
// }
// // Instantiate the class
// new SAP_Endpoint();
// // Hook to create the database table
// register_activation_hook(__FILE__, ['SAP_Endpoint', 'create_database_table']);
// class SAP_Endpoint {
// private $secure_key = '123456789'; // Replace with your secure key.
// public function __construct() {
// add_action('rest_api_init', [$this, 'register_api_endpoint']);
// register_activation_hook(__FILE__, [$this, 'create_database_table']);
// }
// // Register the custom API endpoint.
// public function register_api_endpoint() {
// register_rest_route('sap/v1', '/submit-data', [
// 'methods' => 'POST',
// 'callback' => [$this, 'handle_post_request'],
// 'permission_callback' => [$this, 'validate_auth']
// ]);
// }
// // Validate authentication
// public function validate_auth() {
// // Check Authorization header
// $auth_header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
// // Log received headers for debugging
// error_log('Received Authorization Header: ' . $auth_header);
// // If no header is present, return unauthorized
// if (empty($auth_header)) {
// error_log('No Authorization header found');
// return new WP_Error('unauthorized', 'No authorization header', ['status' => 401]);
// }
// // Check if the header starts with 'Basic '
// if (strpos($auth_header, 'Basic ') !== 0) {
// error_log('Invalid Authorization header format');
// return new WP_Error('unauthorized', 'Invalid authorization header', ['status' => 401]);
// }
// // Extract and decode the credentials
// $encoded_credentials = substr($auth_header, 6); // Remove 'Basic ' prefix
// $decoded_credentials = base64_decode($encoded_credentials);
// // Logging decoded credentials for debugging
// if (!$decoded_credentials) {
// error_log('Base64 decoding failed');
// return new WP_Error('unauthorized', 'Invalid base64 encoding', ['status' => 401]);
// }
// error_log('Decoded credentials: ' . $decoded_credentials);
// // Split username and password
// $credentials = explode(':', $decoded_credentials);
// // Ensure we have two parts (username and password)
// if (count($credentials) !== 2) {
// error_log('Malformed credentials');
// return new WP_Error('unauthorized', 'Malformed credentials', ['status' => 401]);
// }
// // Extract username and password
// $username = trim($credentials[0]);
// $password = trim($credentials[1]);
// // Log extracted username and password
// error_log('Provided username: ' . $username);
// error_log('Provided password: ' . $password);
// // Replace with your actual credentials
// $valid_username = 'itrosys';
// $valid_password = '123456';
// // Verify credentials
// if ($username === $valid_username && $password === $valid_password) {
// error_log('Authentication successful');
// return true;
// }
// // Log failed authentication attempt
// error_log('Authentication failed. Provided username: ' . $username);
// return new WP_Error('unauthorized', 'Invalid credentials', ['status' => 401]);
// }
// // Handle the POST request.
// public function handle_post_request(WP_REST_Request $request) {
// // Get the raw POST body
// $body = $request->get_body();
// // Log the received body for debugging
// error_log('Received Body: ' . $body);
// // Attempt to decode the JSON
// $data = json_decode($body, true);
// // Check if JSON decoding was successful
// if (json_last_error() !== JSON_ERROR_NONE) {
// error_log('JSON Decode Error: ' . json_last_error_msg());
// return new WP_Error('invalid_json', 'Invalid JSON format', ['status' => 400]);
// }
// // Check if secure key matches.
// if (empty($data['secure_key']) || $data['secure_key'] !== $this->secure_key) {
// return new WP_Error('forbidden', 'Invalid secure key', ['status' => 403]);
// }
// // Validate JSON payload structure (add your validation logic here).
// if (empty($data['field_1']) || empty($data['field_2'])) {
// return new WP_Error('invalid_data', 'Invalid JSON payload', ['status' => 400]);
// }
// // Save data to the database.
// global $wpdb;
// $table_name = $wpdb->prefix . 'sap_data';
// $inserted = $wpdb->insert($table_name, [
// 'field_1' => sanitize_text_field($data['field_1']),
// 'field_2' => sanitize_text_field($data['field_2']),
// 'created_at' => current_time('mysql')
// ]);
// if ($inserted === false) {
// return new WP_Error('db_error', 'Failed to save data', ['status' => 500]);
// }
// // Return success response.
// return new WP_REST_Response(['message' => 'Data collected'], 200);
// }
// // Create the database table.
// public function create_database_table() {
// global $wpdb;
// $table_name = $wpdb->prefix . 'sap_data';
// $charset_collate = $wpdb->get_charset_collate();
// $sql = "CREATE TABLE IF NOT EXISTS $table_name (
// id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
// field_1 VARCHAR(255) NOT NULL,
// field_2 VARCHAR(255) NOT NULL,
// created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
// PRIMARY KEY (id)
// ) $charset_collate;";
// require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// dbDelta($sql);
// }
// }
/*
class SAP_Endpoint {
private $consumer_key;
private $consumer_secret;
public function __construct() {
add_action('rest_api_init', [$this, 'register_api_endpoint']);
register_activation_hook(__FILE__, [$this, 'create_database_table']);
// Get WooCommerce API keys from options
$this->consumer_key = get_option('woocommerce_api_consumer_key');
$this->consumer_secret = get_option('woocommerce_api_consumer_secret');
}
// Register the custom API endpoint.
public function register_api_endpoint() {
register_rest_route('sap/v1', '/submit-data', [
'methods' => 'POST',
'callback' => [$this, 'handle_post_request'],
'permission_callback' => '__return_true' // Allow unauthenticated access
]);
}
// Handle the POST request.
public function handle_post_request(WP_REST_Request $request) {
// Get the raw POST body
$body = $request->get_body();
// Log the received body for debugging
error_log('Received Body: ' . $body);
// Attempt to decode the JSON
$data = json_decode($body, true);
// Check if JSON decoding was successful
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('JSON Decode Error: ' . json_last_error_msg());
return new WP_Error('invalid_json', 'Invalid JSON format', ['status' => 400]);
}
// Validate consumer key and secret
if (empty($data['consumer_key']) || empty($data['consumer_secret'])) {
return new WP_Error('missing_credentials', 'Consumer key or secret is missing', ['status' => 401]);
}
if ($data['consumer_key'] !== $this->consumer_key || $data['consumer_secret'] !== $this->consumer_secret) {
return new WP_Error('invalid_credentials', 'Invalid consumer key or secret', ['status' => 401]);
}
// Validate JSON payload structure (add your validation logic here).
if (empty($data['field_1']) || empty($data['field_2'])) {
return new WP_Error('invalid_data', 'Invalid JSON payload', ['status' => 400]);
}
// Save data to the database.
global $wpdb;
$table_name = $wpdb->prefix . 'sap_data';
$inserted = $wpdb->insert($table_name, [
'field_1' => sanitize_text_field($data['field_1']),
'field_2' => sanitize_text_field($data['field_2']),
'created_at' => current_time('mysql')
]);
if ($inserted === false) {
return new WP_Error('db_error', 'Failed to save data', ['status' => 500]);
}
// Return success response.
return new WP_REST_Response(['message' => 'Data collected'], 200);
}
// Create the database table.
public function create_database_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'sap_data';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
field_1 VARCHAR(255) NOT NULL,
field_2 VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
*/