api = Qixit_API::get_instance(); $this->logger = Qixit_Logger::get_instance(); add_filter('wp_insert_post_data', array($this, 'gate_author_publish'), 20, 2); add_action('admin_notices', array($this, 'render_admin_notice')); add_action('template_redirect', array($this, 'handle_purchase_callbacks')); add_action('admin_init', array($this, 'handle_admin_purchase_callbacks')); } public function is_enabled() { return boolval(get_option('qixit_enable_author_commerce', false)); } public function get_onboarding_fee() { return max(0, floatval(get_option('qixit_author_onboarding_fee', 0))); } public function get_publish_fee() { return max(0, floatval(get_option('qixit_author_publish_fee', 0))); } public function get_revision_fee() { return max(0, floatval(get_option('qixit_author_revision_fee', 0))); } public function charge_on_revision_edits() { return boolval(get_option('qixit_author_charge_on_revision', false)); } public function get_default_split_percent() { $percent = intval(get_option('qixit_author_default_split_percent', 0)); return max(0, min(100, $percent)); } public function requires_author_approval() { return boolval(get_option('qixit_author_require_moderation', true)); } public function get_onboarding_purchase_url() { return $this->get_or_create_onboarding_purchase_url(); } public function get_publish_fee_purchase_url($post_id) { return $this->get_or_create_publication_fee_purchase_url($post_id); } /** * Ensure required reusable author-commerce products exist/update. * * @param bool $from_settings_save * @return array */ public function ensure_required_products($from_settings_save = false) { $result = array( 'success' => true, 'messages' => array(), 'errors' => array(), ); if (!$this->is_enabled()) { return $result; } $site_key = get_option('qixit_site_api_key', ''); if (empty($site_key)) { $site_key = get_option('qixit_developer_api_key', ''); } if (empty($site_key)) { $result['success'] = false; $result['errors'][] = __('Site API Key is missing. Add it in Settings before provisioning products.', '2waymicropay'); } $category = get_option('qixit_default_commercial_category', ''); if (empty($category)) { $result['success'] = false; $result['errors'][] = __('Default Commercial Code is missing. Select one in Settings before provisioning products.', '2waymicropay'); } if (!$result['success']) { return $result; } if ($this->get_onboarding_fee() > 0) { $url = $this->get_or_create_onboarding_purchase_url(); if (empty($url)) { $result['success'] = false; $result['errors'][] = sprintf( /* translators: %s: provisioning error details */ __('Failed to provision "Purchase of Author Rights" product. %s', '2waymicropay'), $this->get_last_provision_error() ); } elseif ($from_settings_save) { $result['messages'][] = __('Author-rights product is ready.', '2waymicropay'); } } if ($this->get_publish_fee() > 0) { $url = $this->get_or_create_publication_fee_purchase_url(0); if (empty($url)) { $result['success'] = false; $result['errors'][] = sprintf( /* translators: %s: provisioning error details */ __('Failed to provision "Payment for Publication of Article" product. %s', '2waymicropay'), $this->get_last_provision_error() ); } elseif ($from_settings_save) { $result['messages'][] = __('Publication-fee product is ready.', '2waymicropay'); } } // Revision-fee provisioning intentionally disabled. // Once publication fee is paid, subsequent edits should not require // additional charges. if ($from_settings_save) { $immediate = $this->ensure_immediate_access_page(); if (!empty($immediate['url']) && !empty($immediate['created'])) { $result['messages'][] = __('Created a default "Logging into your author account" page and set it as the Author Instructions URL. You can edit that page anytime.', '2waymicropay'); } } return $result; } private function set_last_provision_error($message) { $message = trim((string)$message); $this->last_provision_error = $message; } private function get_last_provision_error() { if (empty($this->last_provision_error)) { return __('Check vendor login, Site API Key, and default commercial category.', '2waymicropay'); } return $this->last_provision_error; } /** * Create checkout URL for a new-author signup request. * * @param array $raw_input * @return array */ public function create_signup_checkout_url($raw_input) { $payload = $this->normalize_signup_payload($raw_input); if (!$payload['success']) { return $payload; } $signup_token = wp_generate_password(40, false, false); $transient_key = 'qixit_author_signup_' . $signup_token; $source_page_url = isset($raw_input['source_page_url']) ? esc_url_raw($raw_input['source_page_url']) : ''; if (empty($source_page_url)) { $source_page_url = home_url('/'); } set_transient( $transient_key, array( 'username' => $payload['username'], 'email' => $payload['email'], 'email_original' => isset($payload['email_original']) ? $payload['email_original'] : '', 'email_replaced' => !empty($payload['email_replaced']) ? 1 : 0, 'display_name' => $payload['display_name'], 'first_name' => $payload['first_name'], 'last_name' => $payload['last_name'], 'password_encrypted' => Qixit_Auth::get_instance()->encrypt_password($payload['password']), 'source_page_url' => $source_page_url, 'created_at' => current_time('timestamp'), ), 2 * HOUR_IN_SECONDS ); $url_result = $this->create_onboarding_purchase_url_for_signup($signup_token, $payload); if (!$url_result['success']) { delete_transient($transient_key); return array( 'success' => false, 'error' => !empty($url_result['error']) ? $url_result['error'] : __('Author rights purchase is not available right now. Ask the site owner to confirm plugin authentication in Settings and try again.', '2waymicropay') ); } if (!empty($payload['email_replaced'])) { $original = isset($payload['email_original']) ? sanitize_email($payload['email_original']) : ''; $placeholder = sanitize_email($payload['email']); $this->log_duplicate_email_replacement($payload['username'], $original, $placeholder); $this->notify_admins_duplicate_email_replaced($payload['username'], $original, $placeholder); } return array( 'success' => true, 'purchase_url' => $url_result['url'], 'signup_token' => $signup_token, ); } public function get_author_qixit_id($user_id) { global $wpdb; $table_name = esc_sql($wpdb->prefix . QIXIT_AUTHOR_SETTINGS); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted plugin table name from $wpdb->prefix. $row = $wpdb->get_row( $wpdb->prepare("SELECT qixit_id FROM {$table_name} WHERE wp_user_id = %d ORDER BY id DESC LIMIT 1", $user_id) ); if (!empty($row->qixit_id)) { return sanitize_text_field($row->qixit_id); } // Fallback to common user meta keys used in legacy setups. $meta_keys = array('qixit_id', 'qixit_user_id', 'qixit_username'); foreach ($meta_keys as $key) { $value = get_user_meta($user_id, $key, true); if (!empty($value)) { return sanitize_text_field($value); } } return ''; } /** * Update user meta + author settings table mapping. * * @param int $user_id * @param string $qixit_id * @param bool $activate_entitlement * @return void */ public function sync_author_identity($user_id, $qixit_id, $activate_entitlement = false) { $user_id = intval($user_id); if ($user_id <= 0) { return; } $qixit_id = sanitize_text_field($qixit_id); if (!empty($qixit_id)) { update_user_meta($user_id, 'qixit_id', $qixit_id); update_user_meta($user_id, 'qixit_user_id', $qixit_id); update_user_meta($user_id, 'qixit_username', $qixit_id); } global $wpdb; $table_name = esc_sql($wpdb->prefix . QIXIT_AUTHOR_SETTINGS); $now_mysql = current_time('mysql'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted plugin table name from $wpdb->prefix. $existing = $wpdb->get_row( $wpdb->prepare("SELECT id FROM {$table_name} WHERE wp_user_id = %d ORDER BY id DESC LIMIT 1", $user_id) ); $data = array( 'wp_user_id' => $user_id, 'qixit_id' => $qixit_id, 'date_updated' => $now_mysql, ); if ($activate_entitlement) { $data['entitlement_status'] = 'active'; $data['entitlement_purchased_at'] = $now_mysql; $data['entitlement_expires_at'] = null; } if ($existing) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- direct write to plugin-owned settings table. $wpdb->update($table_name, $data, array('id' => intval($existing->id))); } else { $data['date_created'] = $now_mysql; if (!isset($data['entitlement_status'])) { $data['entitlement_status'] = 'inactive'; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- direct write to plugin-owned settings table. $wpdb->insert($table_name, $data); } } public function user_has_author_entitlement($user_id) { if (!$this->is_enabled()) { return true; } if (user_can($user_id, 'manage_options') || user_can($user_id, 'edit_others_posts')) { return true; } global $wpdb; $table_name = esc_sql($wpdb->prefix . QIXIT_AUTHOR_SETTINGS); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted plugin table name from $wpdb->prefix. $row = $wpdb->get_row( $wpdb->prepare( "SELECT entitlement_status, entitlement_expires_at FROM {$table_name} WHERE wp_user_id = %d ORDER BY id DESC LIMIT 1", $user_id ) ); if (!$row) { if ($this->restore_author_entitlement_from_payment($user_id)) { return true; } return false; } if (($row->entitlement_status ?? '') !== 'active') { if ($this->restore_author_entitlement_from_payment($user_id)) { return true; } return false; } if (!empty($row->entitlement_expires_at)) { return strtotime($row->entitlement_expires_at) > current_time('timestamp'); } return true; } /** * Restore active author entitlement when payment evidence exists but * author-settings state is missing/stale. * * @param int $user_id * @return bool */ private function restore_author_entitlement_from_payment($user_id) { $user_id = intval($user_id); if ($user_id <= 0) { return false; } global $wpdb; $payments_table = esc_sql($wpdb->prefix . QIXIT_PAYMENT_DETAILS); $author_table = esc_sql($wpdb->prefix . QIXIT_AUTHOR_SETTINGS); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted plugin table name from $wpdb->prefix. $has_payment = intval($wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$payments_table} WHERE wp_user_id = %d AND payment_for = %s", $user_id, 'author_registration' ))) > 0; if (!$has_payment) { $qixit_id = $this->get_author_qixit_id($user_id); if (!empty($qixit_id)) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted plugin table name from $wpdb->prefix. $has_payment = intval($wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$payments_table} WHERE qixit_user_id = %s AND payment_for = %s", $qixit_id, 'author_registration' ))) > 0; } } if (!$has_payment) { return false; } $now_mysql = current_time('mysql'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted plugin table name from $wpdb->prefix. $existing_id = intval($wpdb->get_var($wpdb->prepare( "SELECT id FROM {$author_table} WHERE wp_user_id = %d ORDER BY id DESC LIMIT 1", $user_id ))); if ($existing_id > 0) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- direct write to plugin-owned settings table. $wpdb->update( $author_table, array( 'entitlement_status' => 'active', 'entitlement_purchased_at' => $now_mysql, 'entitlement_expires_at' => null, 'date_updated' => $now_mysql, ), array('id' => $existing_id) ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- direct write to plugin-owned settings table. $wpdb->insert( $author_table, array( 'wp_user_id' => $user_id, 'qixit_id' => $this->get_author_qixit_id($user_id), 'entitlement_status' => 'active', 'entitlement_purchased_at' => $now_mysql, 'entitlement_expires_at' => null, 'date_created' => $now_mysql, 'date_updated' => $now_mysql, ) ); } $this->logger->log('AuthorCommerce restored active entitlement from payment evidence. user=' . $user_id, 'warning'); return true; } public function get_split_payload_for_post($post_id, $percent_to_author = 0) { $percent = intval($percent_to_author); if ($percent <= 0) { return array(); } $post = get_post($post_id); if (!$post || empty($post->post_author)) { return array(); } $author_qixit_id = $this->get_author_qixit_id(intval($post->post_author)); if (empty($author_qixit_id)) { return array(); } return array( 'affiliateUserId' => $author_qixit_id, 'affiliatePercentage' => $percent, ); } public function gate_author_publish($data, $postarr) { if (!$this->is_enabled()) { return $data; } $target_status = is_array($data) ? ($data['post_status'] ?? '') : ''; if (!in_array($target_status, array('publish', 'pending'), true)) { return $data; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $data; } $user_id = get_current_user_id(); if (!$user_id) { return $data; } // Owners/editors are not pay-gated. if (current_user_can('manage_options') || current_user_can('edit_others_posts')) { return $data; } // Only gate users in author/contributor scope. if (!current_user_can('edit_posts')) { return $data; } $post_id = isset($postarr['ID']) ? intval($postarr['ID']) : 0; $requirement = $this->get_submission_payment_requirement($post_id, $target_status, $user_id); if (!empty($requirement['required'])) { $this->logger->log( 'AuthorCommerce gate forced draft. post=' . $post_id . ' status=' . $target_status . ' user=' . $user_id . ' type=' . (isset($requirement['type']) ? $requirement['type'] : ''), 'warning' ); $this->set_notice( $user_id, isset($requirement['message']) ? $requirement['message'] : __('Publishing blocked until required payment is completed.', '2waymicropay'), isset($requirement['url']) ? $requirement['url'] : '' ); $data['post_status'] = 'draft'; } return $data; } /** * Determine whether a post submission requires author-commerce payment. * * @param int $post_id * @param string $target_status publish|pending * @param int $user_id * @return array{required:bool,url:string,message:string,type:string} */ public function get_submission_payment_requirement($post_id, $target_status = 'publish', $user_id = 0) { $post_id = intval($post_id); $target_status = sanitize_key($target_status); $user_id = intval($user_id ?: get_current_user_id()); $result = array( 'required' => false, 'url' => '', 'message' => '', 'type' => '', ); if (!$this->is_enabled() || !$user_id) { $this->logger->log('AuthorCommerce requirement check skipped: disabled/invalid context. post=' . $post_id . ' status=' . $target_status . ' user=' . $user_id, 'info'); return $result; } if (!in_array($target_status, array('publish', 'pending'), true)) { $this->logger->log('AuthorCommerce requirement check skipped: unsupported target status ' . $target_status . ' for post ' . $post_id, 'info'); return $result; } if (user_can($user_id, 'manage_options') || user_can($user_id, 'edit_others_posts')) { $this->logger->log('AuthorCommerce requirement bypassed for owner/editor. post=' . $post_id . ' user=' . $user_id, 'info'); return $result; } if (!user_can($user_id, 'edit_posts')) { $this->logger->log('AuthorCommerce requirement skipped: user cannot edit posts. post=' . $post_id . ' user=' . $user_id, 'info'); return $result; } if (!$this->user_has_author_entitlement($user_id) && $this->get_onboarding_fee() > 0) { $result['required'] = true; $result['type'] = 'author_rights'; $result['url'] = $this->get_or_create_onboarding_purchase_url(); $result['message'] = __('Publishing blocked: this site requires author-rights purchase before posting.', '2waymicropay'); $this->logger->log('AuthorCommerce requirement=author_rights post=' . $post_id . ' status=' . $target_status . ' user=' . $user_id . ' url=' . $result['url'], 'info'); return $result; } // For brand-new posts without an ID, only enforce save-first if publish fee is enabled. if ($post_id <= 0) { if ($this->get_publish_fee() > 0) { $result['required'] = true; $result['type'] = 'save_first'; $result['url'] = ''; $result['message'] = __('Publishing blocked: save this post as draft first, then complete required publication payment.', '2waymicropay'); $this->logger->log('AuthorCommerce requirement=save_first post=0 status=' . $target_status . ' user=' . $user_id, 'info'); } else { $this->logger->log('AuthorCommerce new post with no publish fee: allowing submit directly. status=' . $target_status . ' user=' . $user_id, 'info'); } return $result; } // Revision-fee gating intentionally disabled. // Once a post has been published, later edits should not require another fee. $existing_post = get_post($post_id); if ($existing_post && $existing_post->post_status === 'publish') { $this->logger->log('AuthorCommerce publish fee waived: post already published. post=' . $post_id . ' user=' . $user_id, 'info'); return $result; } if (intval(get_post_meta($post_id, '_qixit_publish_fee_paid', true)) === 1) { $this->logger->log('AuthorCommerce publish fee already satisfied permanently. post=' . $post_id . ' user=' . $user_id, 'info'); return $result; } $publish_fee = $this->get_publish_fee(); if ($publish_fee <= 0) { $this->logger->log('AuthorCommerce no publish fee configured. post=' . $post_id . ' status=' . $target_status . ' user=' . $user_id, 'info'); return $result; } $paid_until = intval(get_post_meta($post_id, '_qixit_publish_fee_paid_until', true)); if ($paid_until > current_time('timestamp')) { $this->logger->log('AuthorCommerce publish fee already paid. post=' . $post_id . ' status=' . $target_status . ' user=' . $user_id . ' paid_until=' . $paid_until, 'info'); return $result; } $result['required'] = true; $result['type'] = 'publication_fee'; $result['url'] = $this->get_or_create_publication_fee_purchase_url($post_id, $target_status); $result['message'] = ($target_status === 'pending') ? __('Submitting for review blocked: this post requires publication fee payment first.', '2waymicropay') : __('Publishing blocked: this post requires a publication fee payment.', '2waymicropay'); $this->logger->log('AuthorCommerce requirement=publication_fee post=' . $post_id . ' status=' . $target_status . ' user=' . $user_id . ' paid_until=' . $paid_until . ' url=' . $result['url'], 'info'); return $result; } public function render_admin_notice() { $user_id = get_current_user_id(); if (!$user_id) { return; } $payload = get_transient('qixit_author_commerce_notice_' . $user_id); if (empty($payload) || !is_array($payload)) { return; } delete_transient('qixit_author_commerce_notice_' . $user_id); echo '

'; echo esc_html($payload['message']); if (!empty($payload['url'])) { echo ' '; echo esc_html__('Pay with 2WayMicropay', '2waymicropay'); echo ''; } echo '

'; } private function set_notice($user_id, $message, $url = '') { set_transient( 'qixit_author_commerce_notice_' . intval($user_id), array( 'message' => $message, 'url' => $url, ), 300 ); } private function get_or_create_onboarding_purchase_url() { $this->set_last_provision_error(''); $guid = get_option('qixit_author_onboarding_product_guid', ''); $fee = $this->get_onboarding_fee(); if ($fee <= 0) { return ''; } $delivery_url = add_query_arg( array( 'qixit_author_onboard_paid' => '1', 'qixit_verified' => '1', 'qixit_cb' => function_exists('qixit_issue_callback_token') ? qixit_issue_callback_token('author_onboarding') : '', ), home_url('/') ); $site_name = get_bloginfo('name'); // Allow publisher-selected access mode (including pay-per-play) when // they intentionally configure repeat author-rights purchases. $access_hours = $this->resolve_existing_access_hours($guid, -1); $rights_label = function_exists('qixit_get_onboarding_rights_label') ? qixit_get_onboarding_rights_label() : __('Author', '2waymicropay'); $api_data = array( // translators: 1: Author or Contributor, 2: site name 'description' => sprintf(__('Purchase of %1$s Rights - %2$s', '2waymicropay'), $rights_label, $site_name), 'cost' => $fee, 'pitchUrl' => home_url('/'), 'deliveryUrl' => $delivery_url, 'commercialCode' => get_option('qixit_default_commercial_category', 'CONTENT'), // Preserve manual Access Duration changes made in Products Portal. 'accessHours' => $access_hours, 'available' => 1, 'newBrowser' => 0, ); if (function_exists('qixit_price_opt_section_fixed') && function_exists('qixit_apply_price_opt_section_to_api_data')) { $api_data = qixit_apply_price_opt_section_to_api_data($api_data, qixit_price_opt_section_fixed('author_rights')); } if (function_exists('qixit_apply_forwarder_to_api_data')) { $api_data = qixit_apply_forwarder_to_api_data($api_data); } if (!empty($guid)) { $update = $this->api->update_product($guid, $api_data); if (!$update['success']) { $error_text = $update['error'] ?? ''; $this->set_last_provision_error($error_text); if ($this->should_recreate_product_from_error($error_text)) { // Stale GUID (deleted product) - clear and recreate. $guid = ''; update_option('qixit_author_onboarding_product_guid', ''); } // Keep existing GUID as fallback even if update failed. // A transient API/auth issue should not break checkout links // for an already provisioned onboarding product. if (!empty($guid)) { $this->logger->log( 'Onboarding product update failed; using existing GUID fallback: ' . ($update['error'] ?? 'unknown'), 'error' ); $purchase_url = $this->api->get_purchase_url($guid); if (!empty($purchase_url)) { return $purchase_url; } } } } if (empty($guid)) { $create = $this->api->create_product($api_data); if ($create['success'] && !empty($create['data']['productKeyId'])) { $guid = $create['data']['productKeyId']; update_option('qixit_author_onboarding_product_guid', $guid); } else { $this->set_last_provision_error($create['error'] ?? ''); } } if (empty($guid)) { return ''; } return $this->api->get_purchase_url($guid); } private function get_or_create_publication_fee_purchase_url($post_id, $submit_intent = 'publish') { $this->set_last_provision_error(''); $fee = $this->get_publish_fee(); if ($fee <= 0) { return ''; } $guid = get_option('qixit_author_publication_product_guid', ''); $post_id = intval($post_id); $has_post_context = ($post_id > 0); $delivery_fallback = admin_url('edit.php'); if ($has_post_context) { $callback_token = function_exists('qixit_issue_callback_token') ? qixit_issue_callback_token( 'author_publish_fee', array( 'post_id' => $post_id, 'submit_intent' => sanitize_key($submit_intent), ) ) : ''; // Return to the post editor after checkout so the callback runs in wp-admin // (draft permalinks are unreliable for payment verification callbacks). $delivery_url = add_query_arg( array( 'qixit_author_publish_paid' => '1', 'qixit_verified' => '1', 'post_id' => $post_id, 'submit_intent' => sanitize_key($submit_intent), 'qixit_cb' => $callback_token, ), get_edit_post_link($post_id, 'raw') ); } else { // Provisioning context (settings save): do not stamp post_id=0 callbacks. $delivery_url = $this->resolve_existing_delivery_url($guid, $delivery_fallback); } $site_name = get_bloginfo('name'); $api_data = array( // translators: %s: site name 'description' => sprintf(__('Payment for Publication of Article - %s', '2waymicropay'), $site_name), 'cost' => $fee, 'pitchUrl' => $post_id > 0 ? get_edit_post_link($post_id, 'raw') : home_url('/'), 'deliveryUrl' => $delivery_url, 'commercialCode' => get_option('qixit_default_commercial_category', 'CONTENT'), 'accessHours' => -2, 'available' => 1, 'newBrowser' => 0, ); if (function_exists('qixit_price_opt_section_fixed') && function_exists('qixit_apply_price_opt_section_to_api_data')) { $api_data = qixit_apply_price_opt_section_to_api_data($api_data, qixit_price_opt_section_fixed('author_rights')); } if (function_exists('qixit_apply_forwarder_to_api_data')) { $api_data = qixit_apply_forwarder_to_api_data($api_data); } if (!empty($guid)) { $update = $this->api->update_product($guid, $api_data); if (!$update['success']) { $error_text = $update['error'] ?? ''; $this->set_last_provision_error($error_text); if ($this->should_recreate_product_from_error($error_text)) { // Stale GUID (deleted product) - clear and recreate. $guid = ''; update_option('qixit_author_publication_product_guid', ''); } if (!empty($guid)) { $this->logger->log('Publication product update failed: ' . ($update['error'] ?? 'unknown'), 'error'); $purchase_url = $this->api->get_purchase_url($guid); if (!empty($purchase_url)) { return $this->append_admin_checkout_flag($purchase_url); } } } } if (empty($guid)) { $create = $this->api->create_product($api_data); if ($create['success'] && !empty($create['data']['productKeyId'])) { $guid = $create['data']['productKeyId']; update_option('qixit_author_publication_product_guid', $guid); } else { $this->set_last_provision_error($create['error'] ?? ''); } } if (empty($guid)) { return ''; } return $this->append_admin_checkout_flag($this->api->get_purchase_url($guid)); } private function get_or_create_revision_fee_purchase_url($post_id, $submit_intent = 'publish') { $this->set_last_provision_error(''); $fee = $this->get_revision_fee(); if ($fee <= 0) { return ''; } $guid = get_option('qixit_author_revision_product_guid', ''); $post_id = intval($post_id); $has_post_context = ($post_id > 0); $delivery_fallback = admin_url('edit.php'); if ($has_post_context) { $callback_token = function_exists('qixit_issue_callback_token') ? qixit_issue_callback_token( 'author_revision_fee', array( 'post_id' => $post_id, 'submit_intent' => sanitize_key($submit_intent), ) ) : ''; $delivery_url = add_query_arg( array( 'qixit_author_revision_paid' => '1', 'qixit_verified' => '1', 'post_id' => $post_id, 'submit_intent' => sanitize_key($submit_intent), 'qixit_cb' => $callback_token, ), get_permalink($post_id) ); } else { // Provisioning context (settings save): do not stamp post_id=0 callbacks. $delivery_url = $this->resolve_existing_delivery_url($guid, $delivery_fallback); } $site_name = get_bloginfo('name'); $api_data = array( // translators: %s: site name 'description' => sprintf(__('Payment for Revision of Published Article - %s', '2waymicropay'), $site_name), 'cost' => $fee, 'pitchUrl' => $post_id > 0 ? get_edit_post_link($post_id, 'raw') : home_url('/'), 'deliveryUrl' => $delivery_url, 'commercialCode' => get_option('qixit_default_commercial_category', 'CONTENT'), 'accessHours' => -2, 'available' => 1, 'newBrowser' => 0, ); if (function_exists('qixit_price_opt_section_fixed') && function_exists('qixit_apply_price_opt_section_to_api_data')) { $api_data = qixit_apply_price_opt_section_to_api_data($api_data, qixit_price_opt_section_fixed('author_rights')); } if (function_exists('qixit_apply_forwarder_to_api_data')) { $api_data = qixit_apply_forwarder_to_api_data($api_data); } if (!empty($guid)) { $update = $this->api->update_product($guid, $api_data); if (!$update['success']) { $error_text = $update['error'] ?? ''; $this->set_last_provision_error($error_text); if ($this->should_recreate_product_from_error($error_text)) { // Stale GUID (deleted product) - clear and recreate. $guid = ''; update_option('qixit_author_revision_product_guid', ''); } if (!empty($guid)) { $this->logger->log('Revision product update failed: ' . ($update['error'] ?? 'unknown'), 'error'); $purchase_url = $this->api->get_purchase_url($guid); if (!empty($purchase_url)) { return $this->append_admin_checkout_flag($purchase_url); } } } } if (empty($guid)) { $create = $this->api->create_product($api_data); if ($create['success'] && !empty($create['data']['productKeyId'])) { $guid = $create['data']['productKeyId']; update_option('qixit_author_revision_product_guid', $guid); } else { $this->set_last_provision_error($create['error'] ?? ''); } } if (empty($guid)) { return ''; } return $this->append_admin_checkout_flag($this->api->get_purchase_url($guid)); } public function handle_purchase_callbacks() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (isset($_GET['qixit_author_onboard_paid']) && isset($_GET['qixit_verified'])) { $this->handle_onboarding_callback(); return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (isset($_GET['qixit_author_publish_paid']) && isset($_GET['qixit_verified'])) { $this->handle_publish_fee_callback(); return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (isset($_GET['qixit_author_revision_paid']) && isset($_GET['qixit_verified'])) { $this->handle_revision_fee_callback(); } } /** * Handle publish/revision callbacks that return to wp-admin after checkout. */ public function handle_admin_purchase_callbacks() { if (!is_admin()) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (isset($_GET['qixit_author_publish_paid']) && isset($_GET['qixit_verified'])) { $this->handle_publish_fee_callback(); return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (isset($_GET['qixit_author_revision_paid']) && isset($_GET['qixit_verified'])) { $this->handle_revision_fee_callback(); } } /** * Verify a paid author-signup callback using the portal transaction record. * * Signup uses pay-per-checkout products and login aliases, so verification trusts * the transaction ID and portal buyer username instead of strict amount/alias checks. * * @param string $expected_product_guid Product GUID stored with the signup transient. * @return array { success: bool, data?: array, message?: string } */ private function verify_author_signup_payment($expected_product_guid) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $txn_id = isset($_GET['txn']) ? sanitize_text_field(wp_unslash($_GET['txn'])) : ''; if ($txn_id === '') { return array('success' => false, 'message' => 'Missing transaction ID'); } $verify = qixit_verify_purchase_with_portal($txn_id, '', '', null); if (empty($verify['success']) || empty($verify['data'])) { return !empty($verify['success']) ? array('success' => false, 'message' => 'Transaction verification failed') : $verify; } $txn_product = isset($verify['data']['productGuid']) ? (string) $verify['data']['productGuid'] : ''; $allowed_products = array(); if ($expected_product_guid !== '') { $allowed_products[] = $expected_product_guid; } $onboarding_guid = get_option('qixit_author_onboarding_product_guid', ''); if ($onboarding_guid !== '') { $allowed_products[] = $onboarding_guid; } $allowed_products = array_values(array_unique(array_filter($allowed_products))); if ($txn_product !== '' && !empty($allowed_products)) { $product_ok = false; foreach ($allowed_products as $allowed_guid) { if (strcasecmp($txn_product, $allowed_guid) === 0) { $product_ok = true; break; } } if (!$product_ok) { $this->logger->warning( 'Author signup payment product mismatch for txn ' . $txn_id . ' (txn product ' . $txn_product . ')' ); return array('success' => false, 'message' => 'Product mismatch'); } } return $verify; } /** * Verify a paid author publish/revision callback using the portal transaction record. * * @param string $expected_product_guid Product GUID from callback context. * @param string $option_product_key WordPress option key for the provisioned product GUID. * @return array { success: bool, data?: array, message?: string } */ private function verify_author_fee_payment($expected_product_guid, $option_product_key) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $txn_id = isset($_GET['txn']) ? sanitize_text_field(wp_unslash($_GET['txn'])) : ''; if ($txn_id === '') { return array('success' => false, 'message' => 'Missing transaction ID'); } $verify = qixit_verify_purchase_with_portal($txn_id, '', '', null); if (empty($verify['success']) || empty($verify['data'])) { return !empty($verify['success']) ? array('success' => false, 'message' => 'Transaction verification failed') : $verify; } $txn_product = isset($verify['data']['productGuid']) ? (string) $verify['data']['productGuid'] : ''; $allowed_products = array(); if ($expected_product_guid !== '') { $allowed_products[] = $expected_product_guid; } $option_guid = get_option($option_product_key, ''); if ($option_guid !== '') { $allowed_products[] = $option_guid; } $allowed_products = array_values(array_unique(array_filter($allowed_products))); if ($txn_product !== '' && !empty($allowed_products)) { $product_ok = false; foreach ($allowed_products as $allowed_guid) { if (strcasecmp($txn_product, $allowed_guid) === 0) { $product_ok = true; break; } } if (!$product_ok) { $this->logger->warning( 'Author fee payment product mismatch for txn ' . $txn_id . ' (txn product ' . $txn_product . ')' ); return array('success' => false, 'message' => 'Product mismatch'); } } return $verify; } /** * Require a verified Products Portal transaction before author-commerce state changes. * * @param string $product_guid Product GUID for the paid action. * @param string $qixit_user Expected Qixit username from callback. * @param float $amount Expected purchase amount. * @return bool */ private function verify_author_callback_transaction($product_guid, $qixit_user, $amount) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $txn_id = isset($_GET['txn']) ? sanitize_text_field(wp_unslash($_GET['txn'])) : ''; if ($txn_id === '') { return false; } $verify = qixit_verify_purchase_with_portal($txn_id, $product_guid, $qixit_user, $amount); return !empty($verify['success']); } private function handle_onboarding_callback() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $callback_token = isset($_GET['qixit_cb']) ? sanitize_text_field(wp_unslash($_GET['qixit_cb'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (isset($_GET['qixit_author_signup'])) { $this->handle_signup_onboarding_callback(); return; } if (!qixit_require_callback_token($callback_token, 'author_onboarding', array(), true)) { wp_safe_redirect(add_query_arg('qixit_author_signup', 'invalid_callback', home_url('/'))); exit; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $qixit_user = isset($_GET['qixit_user']) ? sanitize_text_field(wp_unslash($_GET['qixit_user'])) : ''; $onboarding_guid = get_option('qixit_author_onboarding_product_guid', ''); if (!$this->verify_author_callback_transaction($onboarding_guid, $qixit_user, $this->get_onboarding_fee())) { wp_safe_redirect(add_query_arg('qixit_author_signup', 'invalid_payment', home_url('/'))); exit; } $user_id = $this->resolve_callback_user_id(); if (!$user_id) { wp_safe_redirect(add_query_arg('qixit_author_signup', 'no_callback_user', home_url('/'))); exit; return; } $this->sync_author_identity($user_id, $qixit_user, true); // Record onboarding payment event for reporting parity. // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $qixit_user_id = isset($_GET['qixit_user']) ? sanitize_text_field(wp_unslash($_GET['qixit_user'])) : ''; Qixit_Payment::get_instance()->record_payment(array( 'product_id' => 0, 'qixit_PID_guid' => $onboarding_guid, 'qixit_user_id' => $qixit_user_id, // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. 'txn_id' => isset($_GET['txn']) ? sanitize_text_field(wp_unslash($_GET['txn'])) : '', 'total' => $this->get_onboarding_fee(), 'payment_for' => 'author_registration', 'wp_user_id' => $user_id )); $requires_moderation = $this->requires_author_approval(); $target_role = $requires_moderation ? 'contributor' : 'author'; // Apply configured role model for users who purchased author rights. $user = get_user_by('id', $user_id); if ($user) { $user->set_role($target_role); } if ($requires_moderation) { $this->set_notice( $user_id, __('Author rights purchase confirmed. Your account is set to Contributor. An Editor or Admin must approve your posts before publication.', '2waymicropay') ); } else { $this->set_notice($user_id, __('Author rights purchase confirmed. Your author account is ready.', '2waymicropay')); } wp_safe_redirect($this->get_immediate_access_redirect_url()); exit; } /** * Handle onboarding callback for shortcode-based "become an author" signup. * * @return void */ private function handle_signup_onboarding_callback() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $signup_token = isset($_GET['signup_token']) ? sanitize_text_field(wp_unslash($_GET['signup_token'])) : ''; if (empty($signup_token)) { wp_safe_redirect(add_query_arg('qixit_author_signup', 'missing_context', home_url('/'))); exit; return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $callback_token = isset($_GET['qixit_cb']) ? sanitize_text_field(wp_unslash($_GET['qixit_cb'])) : ''; if (!qixit_require_callback_token($callback_token, 'author_signup_onboarding', array('signup_token' => $signup_token), true)) { wp_safe_redirect(add_query_arg('qixit_author_signup', 'invalid_callback', home_url('/'))); exit; } $qixit_user = $this->resolve_signup_callback_identity(); $this->process_signup_onboarding_callback($signup_token, $qixit_user); } /** * Resolve identity from callback using multiple provider field names. * * @return string */ private function resolve_signup_callback_identity() { $keys = array('qixit_user', 'qixitUser', 'username', 'userName', 'user_id', 'userId'); foreach ($keys as $key) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (!isset($_GET[$key])) { continue; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $value = sanitize_text_field(wp_unslash($_GET[$key])); if (!empty($value)) { return $value; } } // Fallback if browser-side redirect provided a first-party purchaser cookie. if (!empty($_COOKIE['qixit_purchaser'])) { $cookie_user = sanitize_text_field(wp_unslash($_COOKIE['qixit_purchaser'])); if (!empty($cookie_user)) { return $cookie_user; } } return ''; } /** * Finalize signup callback and create/activate WP user. * * @param string $signup_token * @param string $qixit_user_id * @return void */ private function process_signup_onboarding_callback($signup_token, $qixit_user_id = '') { $signup_token = sanitize_text_field($signup_token); $qixit_user_id = sanitize_text_field($qixit_user_id); if (empty($signup_token)) { return; } $transient_key = 'qixit_author_signup_' . $signup_token; $payload = get_transient($transient_key); if (empty($payload) || !is_array($payload)) { wp_safe_redirect(add_query_arg('qixit_author_signup', 'expired', home_url('/'))); exit; } $requires_moderation = $this->requires_author_approval(); $new_user_role = $requires_moderation ? 'contributor' : 'author'; $product_guid = isset($payload['product_guid']) ? sanitize_text_field($payload['product_guid']) : get_option('qixit_author_onboarding_product_guid', ''); $verify = $this->verify_author_signup_payment($product_guid); if (empty($verify['success'])) { $this->logger->warning( 'Author signup payment verification failed for token ' . $signup_token . ': ' . (isset($verify['message']) ? $verify['message'] : 'unknown') ); wp_safe_redirect(add_query_arg('qixit_author_signup', 'invalid_payment', $this->get_signup_return_url($payload))); exit; } $portal_username = !empty($verify['data']['qixitUsername']) ? trim((string) $verify['data']['qixitUsername']) : ''; if ($portal_username !== '') { $qixit_user_id = $portal_username; } // Security note for reviewers: // This callback-based account creation is intentionally not a generic public // signup endpoint. It is the final step of a paid financial onboarding flow: // 1) user submits local form; 2) plugin stores short-lived transient payload; // 3) user is redirected to Qixit checkout; 4) only successful Qixit callback // with signup token + Qixit identity can finalize account creation. // // We cannot rely on WordPress username/session alone for this financial flow. // The authoritative identity for payment ownership is the Qixit username/userId // returned from checkout. That identity is persisted to WP user meta and // author settings for traceable reconciliation and owner transparency. // Signup transients are only created for new usernames. If a race creates the // account before callback, refuse to modify an existing user from this public flow. $existing_user = get_user_by('login', $payload['username']); if ($existing_user) { delete_transient($transient_key); wp_safe_redirect(add_query_arg('qixit_author_signup', 'username_taken', $this->get_signup_return_url($payload))); exit; } $password = Qixit_Auth::get_instance()->decrypt_password($payload['password_encrypted']); if (empty($password)) { delete_transient($transient_key); wp_safe_redirect(add_query_arg('qixit_author_signup', 'invalid_password', $this->get_signup_return_url($payload))); exit; } $qixit_identity = !empty($qixit_user_id) ? $qixit_user_id : ''; if (empty($qixit_identity)) { delete_transient($transient_key); $this->notify_missing_signup_identity($payload); wp_safe_redirect(add_query_arg('qixit_author_signup', 'missing_identity', $this->get_signup_return_url($payload))); exit; } // Create WP user only at the end of successful paid onboarding callback. // This avoids exposing an unauthenticated "create user" endpoint and ensures // account creation is tied to a verifiable external financial identity. $user_id = wp_insert_user(array( 'user_login' => $payload['username'], 'user_pass' => $password, 'user_email' => $payload['email'], 'display_name' => $payload['display_name'], 'first_name' => $payload['first_name'], 'last_name' => $payload['last_name'], 'role' => $new_user_role, )); if (is_wp_error($user_id)) { delete_transient($transient_key); wp_safe_redirect(add_query_arg('qixit_author_signup', 'create_failed', $this->get_signup_return_url($payload))); exit; } $this->sync_author_identity($user_id, $qixit_identity, true); delete_user_meta($user_id, 'qixit_author_mapping_pending'); delete_user_meta($user_id, 'qixit_author_approval_pending'); Qixit_Payment::get_instance()->record_payment(array( 'product_id' => 0, 'qixit_PID_guid' => isset($payload['product_guid']) ? $payload['product_guid'] : '', 'qixit_user_id' => $qixit_identity, // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. 'txn_id' => isset($_GET['txn']) ? sanitize_text_field(wp_unslash($_GET['txn'])) : '', 'total' => $this->get_onboarding_fee(), 'payment_for' => 'author_registration', 'wp_user_id' => intval($user_id) )); delete_transient($transient_key); $email_replaced = !empty($payload['email_replaced']); $placeholder = $email_replaced ? sanitize_email($payload['email']) : ''; $this->set_notice( $user_id, $this->get_onboarding_success_notice($requires_moderation, $email_replaced, $placeholder) ); wp_safe_redirect($this->get_immediate_access_redirect_url()); exit; } private function handle_publish_fee_callback() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $post_id = isset($_GET['post_id']) ? intval(wp_unslash($_GET['post_id'])) : 0; if (!$post_id) { return; } $edit_link = get_edit_post_link($post_id, 'raw'); if (empty($edit_link)) { $edit_link = admin_url('post.php?post=' . $post_id . '&action=edit'); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $callback_token = isset($_GET['qixit_cb']) ? sanitize_text_field(wp_unslash($_GET['qixit_cb'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $submit_intent_context = isset($_GET['submit_intent']) ? sanitize_key(wp_unslash($_GET['submit_intent'])) : 'publish'; if (!qixit_require_callback_token( $callback_token, 'author_publish_fee', array( 'post_id' => $post_id, 'submit_intent' => $submit_intent_context, ), true )) { $this->logger->warning('Publish fee callback rejected: invalid callback token for post ' . $post_id); wp_safe_redirect(add_query_arg('qixit_publish_error', 'invalid_callback', $edit_link)); exit; } $publish_guid = get_option('qixit_author_publication_product_guid', ''); $verify = $this->verify_author_fee_payment($publish_guid, 'qixit_author_publication_product_guid'); if (empty($verify['success'])) { $this->logger->warning( 'Publish fee payment verification failed for post ' . $post_id . ': ' . (isset($verify['message']) ? $verify['message'] : 'unknown') ); $user_id = $this->resolve_callback_user_for_post($post_id, $verify); if ($user_id) { $this->set_notice( $user_id, __('Publication payment could not be verified. Please contact the site owner or retry checkout.', '2waymicropay') ); } wp_safe_redirect(add_query_arg('qixit_publish_error', 'invalid_payment', $edit_link)); exit; } $user_id = $this->resolve_callback_user_for_post($post_id, $verify); if (!$this->is_callback_actor_authorized_for_post($user_id, $post_id)) { $this->logger->warning('Publish fee callback rejected: actor not authorized for post ' . $post_id . ' user=' . $user_id); if ($user_id) { $this->set_notice( $user_id, __('Publication payment was received but could not be applied to this post.', '2waymicropay') ); } wp_safe_redirect(add_query_arg('qixit_publish_error', 'unauthorized', $edit_link)); exit; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $qixit_user_id = isset($_GET['qixit_user']) ? sanitize_text_field(wp_unslash($_GET['qixit_user'])) : ''; $portal_username = !empty($verify['data']['qixitUsername']) ? trim((string) $verify['data']['qixitUsername']) : ''; if ($portal_username !== '') { $qixit_user_id = $portal_username; } $valid_for_seconds = 900; // 15 minutes to complete publish action. update_post_meta($post_id, '_qixit_publish_fee_paid_until', current_time('timestamp') + $valid_for_seconds); update_post_meta($post_id, '_qixit_publish_fee_paid', 1); if ($user_id) { update_post_meta($post_id, '_qixit_publish_fee_paid_by', $user_id); } // Record publish-fee payment event for reporting. Qixit_Payment::get_instance()->record_payment(array( 'product_id' => 0, 'qixit_PID_guid' => $publish_guid, 'qixit_user_id' => $qixit_user_id, // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. 'txn_id' => isset($_GET['txn']) ? sanitize_text_field(wp_unslash($_GET['txn'])) : '', 'total' => $this->get_publish_fee(), 'payment_for' => 'add_post', 'wp_user_id' => intval($user_id) )); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $submit_intent = isset($_GET['submit_intent']) ? sanitize_key(wp_unslash($_GET['submit_intent'])) : 'publish'; if (!in_array($submit_intent, array('publish', 'pending'), true)) { $submit_intent = 'publish'; } // Enforce moderation policy for non-privileged users even in callback flow. // wp_update_post() executes server-side and can bypass role-based UI limits, // so we explicitly force Contributor-mode submissions to pending. $effective_intent = $submit_intent; if ($this->requires_author_approval() && $user_id > 0 && !user_can($user_id, 'edit_others_posts')) { $effective_intent = 'pending'; } // Server-side fail-safe: apply the intended status directly for the // specific post tied to this payment callback. This prevents cases where // editor-side JS handoff is missed and the post remains draft after payment. $post = get_post($post_id); if ($post && in_array($post->post_status, array('draft', 'auto-draft', 'pending'), true)) { $target_status = ($effective_intent === 'pending') ? 'pending' : 'publish'; $update_payload = array( 'ID' => $post_id, 'post_status' => $target_status, ); $updated = wp_update_post($update_payload, true); if (is_wp_error($updated)) { $this->logger->log( 'Publish callback status update failed. post=' . $post_id . ' target=' . $target_status . ' error=' . $updated->get_error_message(), 'error' ); } else { $this->logger->log( 'Publish callback applied status update. post=' . $post_id . ' target=' . $target_status, 'warning' ); } } if ($user_id) { $notice_message = ($effective_intent === 'pending') ? __('Publish fee confirmed. Your post was submitted for editor/admin review.', '2waymicropay') : __('Publish fee confirmed. Finalizing your post publication now.', '2waymicropay'); $this->set_notice($user_id, $notice_message); } wp_safe_redirect(add_query_arg(array( 'qixit_autosubmit' => $effective_intent, 'qixit_autosubmit_post' => $post_id, ), $edit_link)); exit; } private function handle_revision_fee_callback() { $user_id = $this->resolve_callback_user_id(); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $post_id = isset($_GET['post_id']) ? intval(wp_unslash($_GET['post_id'])) : 0; if (!$post_id) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $callback_token = isset($_GET['qixit_cb']) ? sanitize_text_field(wp_unslash($_GET['qixit_cb'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $submit_intent_context = isset($_GET['submit_intent']) ? sanitize_key(wp_unslash($_GET['submit_intent'])) : 'publish'; if (!qixit_require_callback_token( $callback_token, 'author_revision_fee', array( 'post_id' => $post_id, 'submit_intent' => $submit_intent_context, ), true )) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $qixit_user_id = isset($_GET['qixit_user']) ? sanitize_text_field(wp_unslash($_GET['qixit_user'])) : ''; $revision_guid = get_option('qixit_author_revision_product_guid', ''); if (!$this->verify_author_callback_transaction($revision_guid, $qixit_user_id, $this->get_revision_fee())) { return; } if (!$this->is_callback_actor_authorized_for_post($user_id, $post_id)) { return; } $valid_for_seconds = 900; update_post_meta($post_id, '_qixit_revision_fee_paid_until', current_time('timestamp') + $valid_for_seconds); if ($user_id) { update_post_meta($post_id, '_qixit_revision_fee_paid_by', $user_id); } Qixit_Payment::get_instance()->record_payment(array( 'product_id' => 0, 'qixit_PID_guid' => $revision_guid, 'qixit_user_id' => $qixit_user_id, // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. 'txn_id' => isset($_GET['txn']) ? sanitize_text_field(wp_unslash($_GET['txn'])) : '', 'total' => $this->get_revision_fee(), 'payment_for' => 'add_post', 'wp_user_id' => intval($user_id) )); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $submit_intent = isset($_GET['submit_intent']) ? sanitize_key(wp_unslash($_GET['submit_intent'])) : 'publish'; if (!in_array($submit_intent, array('publish', 'pending'), true)) { $submit_intent = 'publish'; } if ($user_id) { $this->set_notice( $user_id, __('Revision fee confirmed. Finalizing your post submission now.', '2waymicropay') ); } wp_safe_redirect(add_query_arg(array( 'qixit_autosubmit' => $submit_intent, 'qixit_autosubmit_post' => $post_id, ), get_edit_post_link($post_id, 'raw'))); exit; } private function resolve_callback_user_for_post($post_id, $verify = array()) { $user_id = $this->resolve_callback_user_id(); if ($user_id > 0) { return $user_id; } if (!empty($verify['data']['qixitUsername'])) { $user_id = $this->resolve_user_id_by_qixit_identity((string) $verify['data']['qixitUsername']); if ($user_id > 0) { return $user_id; } } $post = get_post(intval($post_id)); if ($post) { return intval($post->post_author); } return 0; } private function resolve_callback_user_id() { $user_id = get_current_user_id(); if ($user_id) { return $user_id; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. if (!isset($_GET['qixit_user'])) { return 0; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- external payment callback URL cannot carry WP nonce. $qixit_user = sanitize_text_field(wp_unslash($_GET['qixit_user'])); if (empty($qixit_user)) { return 0; } return $this->resolve_user_id_by_qixit_identity($qixit_user); } /** * Resolve WP user by authoritative Qixit identity first, then legacy login fallback. * * @param string $qixit_user * @return int */ private function resolve_user_id_by_qixit_identity($qixit_user) { global $wpdb; $qixit_user = sanitize_text_field($qixit_user); if ($qixit_user === '') { return 0; } // Primary lookup: plugin author settings table by qixit_id. $author_table = esc_sql($wpdb->prefix . QIXIT_AUTHOR_SETTINGS); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted plugin table name from $wpdb->prefix. $mapped_user_id = intval($wpdb->get_var($wpdb->prepare( "SELECT wp_user_id FROM {$author_table} WHERE qixit_id = %s ORDER BY id DESC LIMIT 1", $qixit_user ))); if ($mapped_user_id > 0) { return $mapped_user_id; } // Secondary lookup: user meta keys used by historical plugin versions. $usermeta_table = esc_sql($wpdb->usermeta); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- bounded legacy-ID lookup after author-table miss. $mapped_from_meta = intval($wpdb->get_var($wpdb->prepare( "SELECT user_id FROM {$usermeta_table} WHERE meta_key IN ('qixit_id', 'qixit_user_id', 'qixit_username') AND meta_value = %s LIMIT 1", $qixit_user ))); if ($mapped_from_meta > 0) { return $mapped_from_meta; } // Legacy compatibility fallback: direct WP login name match. $candidate = get_user_by('login', $qixit_user); return $candidate ? intval($candidate->ID) : 0; } /** * Authorize callback actor for post transition. * * @param int $user_id * @param int $post_id * @return bool */ private function is_callback_actor_authorized_for_post($user_id, $post_id) { $post_id = intval($post_id); if ($post_id <= 0) { return false; } if ($user_id > 0 && current_user_can('edit_post', $post_id)) { return true; } $post = get_post($post_id); if ($post && $user_id > 0 && intval($post->post_author) === intval($user_id)) { return true; } return false; } /** * Validate and normalize signup form payload. * * @param array $raw_input * @return array */ private function normalize_signup_payload($raw_input) { $username = sanitize_user($raw_input['username'] ?? '', true); $email = sanitize_email($raw_input['email'] ?? ''); $email_original = ''; $email_replaced = false; $email_mode = sanitize_text_field($raw_input['email_mode'] ?? get_option('qixit_author_signup_email_mode', 'required')); $display_name = sanitize_text_field($raw_input['display_name'] ?? ''); $first_name = sanitize_text_field($raw_input['first_name'] ?? ''); $last_name = sanitize_text_field($raw_input['last_name'] ?? ''); $password = (string)($raw_input['password'] ?? ''); $password_confirm = (string)($raw_input['password_confirm'] ?? ''); $ack_password_differs = !empty($raw_input['ack_password_differs']); if (empty($username) || empty($password)) { return array('success' => false, 'error' => __('Please complete all required fields.', '2waymicropay')); } if (!in_array($email_mode, array('required', 'optional', 'hidden'), true)) { $email_mode = 'required'; } if ($email_mode === 'required') { if (empty($email)) { return array('success' => false, 'error' => __('Email is required.', '2waymicropay')); } if (!is_email($email)) { return array('success' => false, 'error' => __('Please enter a valid email address.', '2waymicropay')); } } elseif ($email_mode === 'optional') { if (!empty($email) && !is_email($email)) { return array('success' => false, 'error' => __('Please enter a valid email address.', '2waymicropay')); } } else { // hidden $email = ''; } if (empty($email)) { $email = $this->build_placeholder_signup_email($username, 'missing'); } if (username_exists($username)) { return array( 'success' => false, 'error' => __('That WordPress username is already in use. Choose a different username, then try Purchase again.', '2waymicropay') ); } if (email_exists($email)) { $email_original = $email; $email = $this->build_placeholder_signup_email($username, 'duplicate', $email_original); $email_replaced = true; } if ($password !== $password_confirm) { return array('success' => false, 'error' => __('Password confirmation does not match.', '2waymicropay')); } if (strlen($password) < 8) { return array('success' => false, 'error' => __('Please use a password with at least 8 characters.', '2waymicropay')); } if (!$ack_password_differs) { return array('success' => false, 'error' => __('Please confirm your WordPress password is different from your 2WayMicropay password.', '2waymicropay')); } if (empty($display_name)) { $display_name = $username; } return array( 'success' => true, 'username' => $username, 'email' => $email, 'display_name' => $display_name, 'first_name' => $first_name, 'last_name' => $last_name, 'password' => $password, 'email_mode' => $email_mode, 'email_replaced' => $email_replaced, 'email_original' => $email_original, ); } /** * Build deterministic placeholder email for hidden/optional empty-email mode. * * @param string $username * @return string */ private function build_placeholder_signup_email($username, $reason = 'missing', $original_email = '') { $base = sanitize_user($username, true); if (empty($base)) { $base = 'author'; } $seed = strtolower($base); $prefix = ($reason === 'duplicate') ? 'donotduplicate' : $seed; $material = ($reason === 'duplicate' && !empty($original_email)) ? strtolower($seed . '|' . sanitize_email($original_email)) : strtolower($seed); $candidate = $prefix . '+' . substr(md5($material), 0, 8) . '@no-email.qixit.local'; $i = 1; while (email_exists($candidate)) { $candidate = $prefix . '+' . substr(md5($material . '|' . $i), 0, 8) . '@no-email.qixit.local'; $i++; } return $candidate; } private function get_onboarding_success_notice($requires_moderation, $email_replaced, $placeholder_email = '') { if ($requires_moderation) { $message = __('Author rights purchase confirmed. Your account is set to Contributor. An Editor or Admin must approve your posts before publication.', '2waymicropay'); } else { $message = __('Author rights purchase confirmed. Your author account is ready.', '2waymicropay'); } if ($email_replaced) { $message .= ' ' . sprintf( // translators: %s: placeholder email used when duplicate email is detected __('To protect site login/password recovery, your WordPress email was set to %s because that email was already in use.', '2waymicropay'), $placeholder_email ); } return $message; } private function log_duplicate_email_replacement($username, $original_email, $placeholder_email) { $this->logger->log( 'Duplicate signup email replaced for username=' . sanitize_user($username, true) . ' original=' . sanitize_email($original_email) . ' placeholder=' . sanitize_email($placeholder_email), 'warning' ); } private function notify_admins_duplicate_email_replaced($username, $original_email, $placeholder_email) { $message = sprintf( /* translators: 1: WordPress username, 2: original duplicate email, 3: replacement placeholder email */ __('Author signup email conflict resolved for %1$s. Duplicate email %2$s was replaced with %3$s to protect account recovery.', '2waymicropay'), sanitize_text_field($username), sanitize_email($original_email), sanitize_email($placeholder_email) ); $admins = get_users(array('role' => 'administrator', 'fields' => array('ID'))); if (is_array($admins)) { foreach ($admins as $admin) { if (!empty($admin->ID)) { $this->set_notice(intval($admin->ID), $message); } } } } /** * Build safe return URL for signup status redirects. * * @param array $payload * @return string */ private function get_signup_return_url($payload) { if (!is_array($payload)) { return home_url('/'); } $url = isset($payload['source_page_url']) ? esc_url_raw($payload['source_page_url']) : ''; if (!empty($url)) { return $url; } return home_url('/'); } /** * Notify site owner and applicant when callback is missing Qixit identity. * * @param array $payload * @return void */ private function notify_missing_signup_identity($payload) { $site_name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES); $username = isset($payload['username']) ? sanitize_text_field($payload['username']) : __('Unknown', '2waymicropay'); $message = sprintf( /* translators: %s: attempted signup username */ __('Author signup payment was received but Qixit identity was missing in callback. Account was not created for %s.', '2waymicropay'), $username ); $admins = get_users(array('role' => 'administrator', 'fields' => array('ID'))); if (is_array($admins)) { foreach ($admins as $admin) { if (!empty($admin->ID)) { $this->set_notice(intval($admin->ID), $message); } } } $owner_email = get_option('admin_email'); if (!empty($owner_email) && is_email($owner_email)) { @wp_mail( $owner_email, // translators: %s: site name sprintf(__('[%s] Author signup needs review', '2waymicropay'), $site_name), $message ); } $applicant_email = isset($payload['email']) ? sanitize_email($payload['email']) : ''; if (!empty($applicant_email) && is_email($applicant_email) && strpos($applicant_email, '@no-email.qixit.local') === false) { @wp_mail( $applicant_email, // translators: %s: site name sprintf(__('[%s] Author signup needs retry', '2waymicropay'), $site_name), __('We received your payment attempt, but your Qixit identity was not returned by callback. Please contact the site owner to retry your author signup.', '2waymicropay') ); } } /** * Backward-compatible alias for legacy pending-review redirect option. * New model always uses the Author Instructions URL destination. * * @return string */ private function get_pending_review_redirect_url() { return $this->get_immediate_access_redirect_url(); } /** * Get immediate-access redirect URL for approved-on-payment flow. * * @return string */ private function get_immediate_access_redirect_url() { $configured = esc_url_raw(get_option('qixit_author_immediate_access_redirect_url', '')); if (!empty($configured)) { return $configured; } $fallback = $this->ensure_immediate_access_page(); if (!empty($fallback['url'])) { return $fallback['url']; } return wp_login_url(admin_url()); } /** * Backward-compatible destination accessor for legacy integrations. * * @return string */ public function get_pending_review_destination_url() { return $this->get_pending_review_redirect_url(); } /** * Public helper to resolve immediate-access destination for settings display. * * @return string */ public function get_immediate_access_destination_url() { return $this->get_immediate_access_redirect_url(); } /** * Ensure a friendly pending-review landing page exists when moderation is enabled. * * @return array{url:string,created:bool} */ private function ensure_pending_review_page() { $configured = esc_url_raw(get_option('qixit_author_pending_review_redirect_url', '')); $required_sentence = 'The site owner will contact you by either email or with a Qixit message regarding how to sign in and create articles once your application has been approved.'; if (!empty($configured)) { $configured_page_id = function_exists('url_to_postid') ? intval(url_to_postid($configured)) : 0; if ($configured_page_id <= 0 && strpos($configured, '/author-request-received') !== false) { $configured_page = get_page_by_path('author-request-received', OBJECT, 'page'); if ($configured_page && !empty($configured_page->ID)) { $configured_page_id = intval($configured_page->ID); } } if ($configured_page_id > 0) { $this->ensure_pending_review_copy($configured_page_id, $required_sentence); } return array('url' => $configured, 'created' => false); } $slug = 'author-request-received'; $created = false; $page = get_page_by_path($slug, OBJECT, 'page'); if (!$page) { $content = "

Thank you. Your author request was received.

\n" . "

Your author-rights payment was successful and your request is now pending publisher review.

\n" . "

" . esc_html($required_sentence) . "

\n" . "

Site Owner: Edit this page to customize your own review-pending message.

"; $page_id = wp_insert_post(array( 'post_title' => 'Author Request Received', 'post_name' => $slug, 'post_type' => 'page', 'post_status' => 'publish', 'post_content' => $content, )); if (!is_wp_error($page_id) && !empty($page_id)) { $page = get_post($page_id); $created = true; } } if ($page && !empty($page->ID)) { $this->ensure_pending_review_copy(intval($page->ID), $required_sentence); $url = get_permalink($page->ID); if (!empty($url)) { update_option('qixit_author_pending_review_redirect_url', esc_url_raw($url)); return array('url' => $url, 'created' => $created); } } return array('url' => '', 'created' => false); } /** * Ensure required pending-review sentence exists on destination page. * * @param int $page_id * @param string $required_sentence * @return void */ private function ensure_pending_review_copy($page_id, $required_sentence) { $page_id = intval($page_id); if ($page_id <= 0) { return; } $post = get_post($page_id); if (!$post || $post->post_type !== 'page') { return; } $content = (string)$post->post_content; if (stripos($content, $required_sentence) !== false) { return; } $updated_content = $content . "\n

" . esc_html($required_sentence) . "

"; wp_update_post(array( 'ID' => $page_id, 'post_content' => $updated_content, )); } /** * Ensure immediate-access onboarding page exists. * * @return array{url:string,created:bool} */ private function ensure_immediate_access_page() { $configured = esc_url_raw(get_option('qixit_author_immediate_access_redirect_url', '')); if (!empty($configured)) { return array('url' => $configured, 'created' => false); } $slug = 'author-login-instructions'; $created = false; $page = get_page_by_path($slug, OBJECT, 'page'); if (!$page) { $login_url = wp_login_url(admin_url()); $content = "

Logging into your author account

\n" . "

Use the WordPress username you entered during author signup.

\n" . "

Use the password you created when your account was created.

\n" . "

Open WordPress Author Login

\n" . "

Important: Save these instructions for future reference.

\n" . "

Site Owner: Edit this page to include your own onboarding terms, provisions, or contract requirements.

"; $page_id = wp_insert_post(array( 'post_title' => 'Logging into your author account', 'post_name' => $slug, 'post_type' => 'page', 'post_status' => 'publish', 'post_content' => $content, )); if (!is_wp_error($page_id) && !empty($page_id)) { $page = get_post($page_id); $created = true; } } if ($page && !empty($page->ID)) { $url = get_permalink($page->ID); if (!empty($url)) { update_option('qixit_author_immediate_access_redirect_url', esc_url_raw($url)); return array('url' => $url, 'created' => $created); } } return array('url' => '', 'created' => false); } /** * Prepare shared onboarding checkout URL for signup callbacks. * * @param string $signup_token * @param array $payload * @return array */ private function create_onboarding_purchase_url_for_signup($signup_token, $payload) { $fee = $this->get_onboarding_fee(); if ($fee <= 0) { return array('success' => false, 'error' => __('Author-rights purchase is disabled.', '2waymicropay')); } $delivery_url = add_query_arg( array( 'qixit_author_onboard_paid' => '1', 'qixit_verified' => '1', 'qixit_author_signup' => '1', 'signup_token' => $signup_token, 'qixit_cb' => function_exists('qixit_issue_callback_token') ? qixit_issue_callback_token('author_signup_onboarding', array('signup_token' => $signup_token)) : '', ), home_url('/') ); $rights_label = function_exists('qixit_get_onboarding_rights_label') ? qixit_get_onboarding_rights_label() : __('Author', '2waymicropay'); // translators: 1: Author or Contributor, 2: site name. $description = sprintf(__('Purchase of %1$s Rights - %2$s', '2waymicropay'), $rights_label, get_bloginfo('name')); $product_guid = get_option('qixit_author_onboarding_product_guid', ''); // Author signup is pay-per-checkout: each new account must pay even if the // same Qixit buyer previously purchased author rights for another WP user. $access_hours = -2; $api_data = array( 'description' => $description, 'cost' => $fee, 'pitchUrl' => home_url('/'), 'deliveryUrl' => $delivery_url, 'commercialCode' => get_option('qixit_default_commercial_category', 'CONTENT'), 'accessHours' => $access_hours, 'available' => 1, 'newBrowser' => 0, ); if (function_exists('qixit_price_opt_section_fixed') && function_exists('qixit_apply_price_opt_section_to_api_data')) { $api_data = qixit_apply_price_opt_section_to_api_data($api_data, qixit_price_opt_section_fixed('author_rights')); } if (function_exists('qixit_apply_forwarder_to_api_data')) { $api_data = qixit_apply_forwarder_to_api_data($api_data); } if (!empty($product_guid)) { $update = $this->api->update_product($product_guid, $api_data); if (!$update['success']) { return array( 'success' => false, 'error' => __('Unable to update author-rights checkout product. Please verify plugin API login and Site API Key in Settings.', '2waymicropay') ); } } else { $create = $this->api->create_product($api_data); if (!$create['success'] || empty($create['data']['productKeyId'])) { return array( 'success' => false, 'error' => __('Unable to create author-rights checkout product. Please verify plugin API login and Site API Key in Settings.', '2waymicropay') ); } $product_guid = $create['data']['productKeyId']; update_option('qixit_author_onboarding_product_guid', $product_guid); } $transient_key = 'qixit_author_signup_' . $signup_token; $cached = get_transient($transient_key); if (is_array($cached)) { $cached['product_guid'] = $product_guid; set_transient($transient_key, $cached, 2 * HOUR_IN_SECONDS); } return array( 'success' => true, 'url' => $this->append_force_login_flag($this->api->get_purchase_url($product_guid)), 'product_guid' => $product_guid, ); } /** * Keep existing product accessHours unless this is a new product. * * @param string $product_guid * @param int $fallback * @return int */ private function resolve_existing_access_hours($product_guid, $fallback = -1) { if (empty($product_guid)) { return intval($fallback); } $existing = $this->api->get_public_product($product_guid); if (!empty($existing['success']) && isset($existing['data']['accessHours'])) { return intval($existing['data']['accessHours']); } return intval($fallback); } /** * Keep existing deliveryUrl when updating shared reusable products without * a specific post context (e.g., settings save provisioning). * * @param string $product_guid * @param string $fallback * @return string */ private function resolve_existing_delivery_url($product_guid, $fallback = '') { $fallback = trim((string)$fallback); if (empty($product_guid)) { return $fallback; } $existing = $this->api->get_public_product($product_guid); if (!empty($existing['success']) && !empty($existing['data']['deliveryUrl'])) { return esc_url_raw($existing['data']['deliveryUrl']); } return $fallback; } /** * Detect stale/deleted product errors that should trigger GUID reset + recreate. * * @param string $error_text * @return bool */ private function should_recreate_product_from_error($error_text) { $error_text = strtolower(trim((string)$error_text)); if ($error_text === '') { return false; } if (strpos($error_text, '404') !== false) { return true; } if (strpos($error_text, 'not found') !== false) { return true; } if (strpos($error_text, 'product not found') !== false) { return true; } return false; } /** * Force author onboarding checkout links to prompt for login. * Prevents stale remembered sessions from auto-skipping to owned state. * * @param string $url * @return string */ private function append_force_login_flag($url) { $url = trim((string)$url); if ($url === '') { return ''; } if (preg_match('/[?&]qixit_force_login=/i', $url)) { return $url; } // Avoid add_query_arg(): it rewrites empty &fwd= into bare &fwd, which breaks some clients. $sep = (strpos($url, '?') !== false) ? '&' : '?'; return $url . $sep . 'qixit_force_login=1'; } /** * Flag checkout links created for wp-admin author submit/review flow so * purchasefast treats popup as standalone callback flow (no opener messaging). * * @param string $url * @return string */ private function append_admin_checkout_flag($url) { $url = trim((string)$url); if ($url === '') { return ''; } if (preg_match('/[?&]qixit_admin_flow=/i', $url)) { return $url; } $sep = (strpos($url, '?') !== false) ? '&' : '?'; return $url . $sep . 'qixit_admin_flow=1'; } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.NoCaching } Qixit_Author_Commerce::get_instance();