get_the_ID(), 'text' => __('Buy Now', '2waymicropay'), 'class' => 'qixit-buy-button' ), $atts); $product = new Qixit_Product($atts['post_id']); if (!$product->is_premium()) { return ''; } $cost = $product->get_cost(); $purchase_url = $product->get_purchase_url(); if (empty($purchase_url)) { return '

' . esc_html__('Product not configured', '2waymicropay') . '

'; } // Format price for display $price_display = '$' . number_format($cost, 2); if ($cost < 0.10) { $cents = intval($cost * 100); $price_display = $cents . ' cent' . ($cents != 1 ? 's' : ''); } /* translators: 1: button text, 2: price display */ $button_text = sprintf(__('%1$s - %2$s', '2waymicropay'), $atts['text'], $price_display); // Use micro-frame trigger instead of direct link return sprintf( '%s', esc_attr($atts['class']), esc_url($purchase_url), esc_attr($price_display), intval($atts['post_id']), esc_attr($price_display), esc_html($button_text) ); } add_shortcode('qixit_buy_button', 'qixit_buy_button_shortcode'); /** * Read More link shortcode (inline, with micro-frame and tooltip) * Usage: [qixit_readmore post_id="123"] or [qixit_readmore text="Continue reading..."] */ function qixit_readmore_shortcode($atts) { $atts = shortcode_atts(array( 'post_id' => get_the_ID(), 'text' => __('Read more...', '2waymicropay') ), $atts); $product = new Qixit_Product($atts['post_id']); if (!$product->is_premium()) { return ''; } // Check if user already purchased if ($product->has_user_purchased()) { return ''; } $cost = $product->get_cost(); $purchase_url = $product->get_purchase_url(); if (empty($purchase_url)) { return ''; } // Format price for display $price_display = '$' . number_format($cost, 2); if ($cost < 0.10) { $cents = intval($cost * 100); $price_display = $cents . ' cent' . ($cents != 1 ? 's' : ''); } ob_start(); ?> to continue reading', '2waymicropay'), esc_html($price_display))); ?> get_the_ID(), 'show_paywall' => 'yes' ), $atts); $product = new Qixit_Product($atts['post_id']); if (!$product->is_premium()) { return wp_kses_post(do_shortcode((string) $content)); } if ($product->has_user_purchased()) { return '
' . wp_kses_post(do_shortcode((string) $content)) . '
'; } // Not purchased - show paywall or hide content if ($atts['show_paywall'] === 'yes') { $frontend = qixit_shortcode_get_frontend_instance(); if ($frontend) { return $frontend->get_paywall_for_post($atts['post_id']); } return '
' . '

๐Ÿ”’ ' . esc_html__('This content is for premium members only.', '2waymicropay') . '

' . '
'; } return '
' . '

๐Ÿ”’ ' . esc_html__('This content is for premium members only.', '2waymicropay') . '

' . '
'; } add_shortcode('qixit_premium', 'qixit_premium_content_shortcode'); add_shortcode('qixit_premium_content', 'qixit_premium_content_shortcode'); /** * Paywall shortcode (display paywall only) * Usage: [qixit_paywall post_id="123"] */ function qixit_paywall_shortcode($atts) { $atts = shortcode_atts(array( 'post_id' => get_the_ID() ), $atts); $frontend = qixit_shortcode_get_frontend_instance(); if (!$frontend) { return '
' . '

๐Ÿ”’ ' . esc_html__('This content is for premium members only.', '2waymicropay') . '

' . '
'; } return $frontend->get_paywall_for_post($atts['post_id']); } add_shortcode('qixit_paywall', 'qixit_paywall_shortcode'); /** * Purchase status shortcode * Usage: [qixit_status post_id="123"] */ function qixit_status_shortcode($atts) { $atts = shortcode_atts(array( 'post_id' => get_the_ID() ), $atts); $product = new Qixit_Product($atts['post_id']); if (!$product->is_premium()) { return '' . esc_html__('Free Content', '2waymicropay') . ''; } if ($product->has_user_purchased()) { return 'โœ“ ' . esc_html__('Purchased', '2waymicropay') . ''; } $cost = $product->get_cost(); return '๐Ÿ”’ $' . number_format($cost, 2) . ''; } add_shortcode('qixit_status', 'qixit_status_shortcode'); /** * Product price shortcode * Usage: [qixit_price post_id="123"] */ function qixit_price_shortcode($atts) { $atts = shortcode_atts(array( 'post_id' => get_the_ID(), 'format' => '$%s' ), $atts); $product = new Qixit_Product($atts['post_id']); $cost = $product->get_cost(); return sprintf($atts['format'], number_format($cost, 2)); } add_shortcode('qixit_price', 'qixit_price_shortcode'); /** * Pay-Per-Play shortcode for games, songs, videos * Shows a placeholder image with "Play" button. Each play requires a new payment. * No cookies are set - payment is required every time. * * Usage: [qixit_payperplay pid="PRODUCT-GUID" image="URL" price="0.05" button_text="Play Now"] * Your game/video embed code here * [/qixit_payperplay] * * Attributes: * - pid: Product GUID from the Products Portal (required) * - image: URL of placeholder image/screenshot (required) * - price: Price to display (e.g., "0.05" or "5 cents") - for display only * - button_text: Text on the play button (default: "Play Now") * - button_again_text: Text after first play (default: "Play Again") * - width: Container width (default: 100%) * - height: Container height (default: 400px) */ /** * Format a dollar amount for pay-per-play / overlay labels. * * @param float $price Amount in dollars. * @return string */ function qixit_format_pay_amount_display($price) { $price = floatval($price); if ($price <= 0) { return ''; } if ($price < 1.00) { $cents = intval(round($price * 100)); return $cents . ' cent' . ($cents != 1 ? 's' : ''); } return '$' . number_format($price, 2); } /** * Parse a shortcode price= attribute ("0.02", "2 cents", etc.). * * @param string $raw Raw attribute value. * @return float|null */ function qixit_parse_price_attr($raw) { if ($raw === null || $raw === '') { return null; } $raw = trim((string) $raw); if (preg_match('/^\s*(\d+(?:\.\d+)?)\s*cents?\s*$/i', $raw, $m)) { return floatval($m[1]) / 100.0; } if (preg_match('/^\s*\$?\s*(\d+(?:\.\d+)?)\s*$/', $raw, $m)) { $v = floatval($m[1]); return $v > 0 ? $v : null; } $v = floatval($raw); return $v > 0 ? $v : null; } /** * Sticky A/B session id from the first-party cookie (mirrored by frontend JS). * * @return string */ function qixit_price_session_id() { if (empty($_COOKIE['qixit_price_session'])) { return ''; } $sid = sanitize_text_field(wp_unslash($_COOKIE['qixit_price_session'])); // UUID or opaque token; keep conservative length. if ($sid === '' || strlen($sid) > 128 || !preg_match('/^[A-Za-z0-9._\-]+$/', $sid)) { return ''; } return $sid; } function qixit_payperplay_shortcode($atts, $content = null) { qixit_shortcode_require_assets(); static $instance_id = 0; $instance_id++; $atts = shortcode_atts(array( 'pid' => '', 'image' => '', 'price' => '0.01', 'button_text' => __('Play Now', '2waymicropay'), 'button_again_text' => __('Play Again', '2waymicropay'), 'width' => '100%', 'height' => '400px', 'title' => '' ), $atts); // Validate required attributes if (empty($atts['pid'])) { return '

โš ๏ธ ' . __('Pay-Per-Play: Missing product ID (pid attribute)', '2waymicropay') . '

'; } if (empty($atts['image'])) { return '

โš ๏ธ ' . __('Pay-Per-Play: Missing placeholder image (image attribute)', '2waymicropay') . '

'; } // Prefer live catalog / A/B price; shortcode price= is fallback only. $live_price = function_exists('qixit_get_product_price') ? floatval(qixit_get_product_price($atts['pid'])) : 0.0; $fallback_price = qixit_parse_price_attr($atts['price']); $price = $live_price > 0 ? $live_price : ($fallback_price !== null ? $fallback_price : 0.01); $price_display = qixit_format_pay_amount_display($price); if ($price_display === '') { $price_display = qixit_format_pay_amount_display(0.01); } // If button_text baked in an old amount (e.g. "Listen Now. 2ยข"), refresh it. $button_text = $atts['button_text']; if ($price_display !== '' && preg_match('/(\$?\d+(?:\.\d+)?\s*(?:ยข|cents?|cent)|\$\d+\.\d{2}|\d+\s*ยข)/iu', $button_text)) { $compact = ($price < 1.00) ? (intval(round($price * 100)) . 'ยข') : ('$' . number_format($price, 2)); $button_text = preg_replace( '/(\$?\d+(?:\.\d+)?\s*(?:ยข|cents?|cent)|\$\d+\.\d{2}|\d+\s*ยข)/iu', $compact, $button_text, 1 ); } // Get Products Web URL from centralized function (always HTTPS in production) $products_web_url = qixit_get_products_web_url(); $purchase_url = rtrim($products_web_url, '/') . '/purchasefast?PID=' . urlencode($atts['pid']); if (function_exists('qixit_append_referral_param')) { $purchase_url = qixit_append_referral_param($purchase_url); } // Generate unique container ID $container_id = 'qixit-payperplay-' . $instance_id; // Store the actual content (game/video embed) for JavaScript $game_content = $content ? trim($content) : ''; ob_start(); ?>
<?php echo esc_attr($atts['title'] ?: __('Click to Play', '2waymicropay')); ?>
[/qixit_image] * * Attributes: * - link: The purchase or payment URL from Products Portal (required) * - src: Image source URL (required if not using enclosed img tag) * - alt: Alt text for the image * - width: Image width (optional) * - height: Image height (optional) * - max_width: Maximum container width (optional) * - align: Image alignment โ€” left, right, center (optional; use editor alignment in Block editor) * - class: Additional CSS classes (optional) * - price: Override price display (optional, auto-fetched from API if not provided) * - type: Deprecated. Ignored when the URL contains PID/PYID; type is detected from the link. */ function qixit_image_shortcode($atts, $content = null) { qixit_shortcode_require_assets(); $atts = shortcode_atts(array( 'link' => '', 'src' => '', 'alt' => '', 'width' => '', // Image width (e.g., "300px", "50%", "auto") 'height' => '', // Image height (e.g., "200px", "auto") 'max_width' => '', // Maximum width (e.g., "500px") 'align' => '', // Alignment: left, right, center, none 'class' => '', // Additional CSS classes 'price' => '', 'type' => '' // 'purchase' (debit, red) or 'payment' (credit, green) ), $atts); // Validate link is provided if (empty($atts['link'])) { return '

โš ๏ธ ' . __('2WayMicropay Image: Missing purchase/payment link', '2waymicropay') . '

'; } // IMPORTANT: Force HTTPS for non-local URLs to prevent mixed content blocking. // Keep localhost links untouched for local development/testing. $link = $atts['link']; $parsed_link = wp_parse_url($link); $link_scheme = isset($parsed_link['scheme']) ? strtolower((string) $parsed_link['scheme']) : ''; $link_host = isset($parsed_link['host']) ? strtolower((string) $parsed_link['host']) : ''; if ($link_scheme === 'http' && !in_array($link_host, array('localhost', '127.0.0.1'), true)) { $link = preg_replace('/^http:\/\//i', 'https://', $link); } // Build container class/style via shared helper (align + max_width on outer wrapper only) $container_attrs = function_exists('qixit_build_micropay_image_container_attrs') ? qixit_build_micropay_image_container_attrs(array( 'align' => $atts['align'], 'max_width' => $atts['max_width'], )) : array( 'class' => 'qixit-image-container', 'style' => '', ); if (!empty($atts['class'])) { $extra_classes = array_filter(array_map('sanitize_html_class', preg_split('/\s+/', (string) $atts['class']))); if (!empty($extra_classes)) { $container_attrs['class'] = trim($container_attrs['class'] . ' ' . implode(' ', $extra_classes)); } } $container_class = $container_attrs['class']; $container_style = $container_attrs['style']; $align = !empty($atts['align']) ? sanitize_key($atts['align']) : ''; $is_floating = in_array($align, array('left', 'right'), true); // Determine image source - either from src attribute or from enclosed content $image_html = ''; if (!empty($atts['src'])) { // Build image styles $img_style = 'display: block;'; if (!empty($atts['width'])) { $img_style .= ' width: ' . esc_attr($atts['width']) . ';'; } elseif ($is_floating) { $img_style .= ' max-width: 100%; height: auto;'; } else { $img_style .= ' width: 100%;'; } if (!empty($atts['height'])) { $img_style .= ' height: ' . esc_attr($atts['height']) . ';'; } else { $img_style .= ' height: auto;'; } $img_attrs = 'src="' . esc_url($atts['src']) . '"'; if (!empty($atts['alt'])) $img_attrs .= ' alt="' . esc_attr($atts['alt']) . '"'; $img_attrs .= ' style="' . $img_style . '"'; $image_html = ''; } elseif (!empty($content)) { // Use enclosed content (should be an img tag) $image_html = do_shortcode($content); } else { return '

โš ๏ธ ' . __('2WayMicropay Image: Missing image (use src attribute or enclose img tag)', '2waymicropay') . '

'; } // Parse the URL to extract product/payment GUID and determine type $product_guid = ''; $is_payment = false; // false = purchase (debit), true = payment (credit) // Check for PurchaseFast URL pattern (uses PID parameter) if (preg_match('/purchasefast\?PID=([a-f0-9\-]+)/i', $link, $matches)) { $product_guid = $matches[1]; $is_payment = false; // Purchase = debit (user pays) } // Check for PaymentFast URL pattern (uses PYID parameter for payout ID) elseif (preg_match('/paymentfast\?PYID=([a-f0-9\-]+)/i', $link, $matches)) { $product_guid = $matches[1]; $is_payment = true; // Payment = credit (user receives money) } // Also check for PID in any position (purchase) elseif (preg_match('/[?&]PID=([a-f0-9\-]+)/i', $link, $matches)) { $product_guid = $matches[1]; $is_payment = false; } // Also check for PYID in any position (payment/payout) elseif (preg_match('/[?&]PYID=([a-f0-9\-]+)/i', $link, $matches)) { $product_guid = $matches[1]; $is_payment = true; } // type= is deprecated. Only use it when the URL has no PID/PYID so publishers // cannot force the wrong purchase vs payment behavior for a real portal link. $url_identified_type = ($product_guid !== ''); if (!$url_identified_type && !empty($atts['type'])) { $is_payment = ($atts['type'] === 'payment' || $atts['type'] === 'credit'); } // Get price and payment type - either from attribute or fetch from API $price_display = ''; $price_value = 0; $payment_type = 0; // 0 = real funds, 1 = promo credits $is_promo = false; $payout_available = true; // Assume available unless we check and find otherwise $payout_unavailable_reason = ''; if (!empty($atts['price'])) { // Use provided price $price_value = floatval($atts['price']); } elseif (!empty($product_guid)) { // Try to fetch price from API based on type if ($is_payment) { // For payment links, FIRST check if payout is available (vendor has funds, not expired) // This prevents showing a payment offer that can't be fulfilled $availability = qixit_check_payout_availability($product_guid); $payout_available = $availability['available']; $payout_unavailable_reason = $availability['reason']; $payment_type = $availability['paymentType']; $is_promo = ($payment_type === 1); if ($payout_available) { // Use availability response for price (it includes all info we need) $price_value = $availability['payAmount']; // Payout is globally active โ€” also check whether the current logged-in // user is personally eligible (has not already claimed their quota). // This prevents showing a payment offer to someone who already received it. // The check reads $qixit_auth cookie server-side (no CORS needed). $user_eligibility = qixit_check_user_payout_eligibility($product_guid); if (!$user_eligibility['eligible']) { // User has already claimed and isn't eligible again yet. // Treat exactly like an inactive payout: plain link, no overlay. $payout_available = false; $payout_unavailable_reason = $user_eligibility['reason']; $price_value = 0; // Prefer the delivery URL from the eligibility response; fall back to // the one from the availability response. $delivery = !empty($user_eligibility['deliveryUrl']) ? $user_eligibility['deliveryUrl'] : (!empty($availability['deliveryUrl']) ? $availability['deliveryUrl'] : ''); if (!empty($delivery)) { $link = $delivery; } } } else { // Payout is inactive โ€” redirect to delivery URL if available so the // image still links somewhere useful without implying a payment offer if (!empty($availability['deliveryUrl'])) { $link = $availability['deliveryUrl']; } // price_value stays 0 so no overlay is shown } } else { // For purchase links, get product price $price_value = qixit_get_product_price($product_guid); } } // Format price display (use HTML entity for cent symbol to avoid encoding issues) if ($price_value > 0) { if ($price_value < 1.00) { $cents = intval($price_value * 100); $price_display = $cents . '¢'; } else { $price_display = '$' . number_format($price_value, 2); } // Add +/- prefix based on type if ($is_payment) { $price_display = '+ ' . $price_display; // Add "vendor credits" suffix for vendor-credit payouts if ($is_promo) { $price_display .= ' vendor credits'; } } else { $price_display = '- ' . $price_display; } } // Resolve logo from manifest contract only. $logo_url = function_exists('qixit_get_branding_logo_url') ? qixit_get_branding_logo_url() : ''; if (empty($logo_url) && defined('QIXIT_PLUGIN_URL')) { $logo_url = QIXIT_PLUGIN_URL . '/images/overlay-logo.svg'; } // CSS class for credit/debit styling - promo credits get special styling $overlay_class = $is_payment ? 'qixit-image-overlay credit' : 'qixit-image-overlay debit'; if ($is_promo) { $overlay_class .= ' promo'; } // Determine the link type and behavior: // - Purchase links (debit): use micro-frame popup // - Payment links (credit): open in new tab with timer overlay on destination $link_type = $is_payment ? 'payment' : 'purchase'; $tooltip_line_1 = $is_payment ? ($is_promo ? __('Click to earn', '2waymicropay') : __('Click to earn credits', '2waymicropay')) : __('Click to purchase', '2waymicropay'); $tooltip_line_2 = !empty($price_display) ? wp_strip_all_tags($price_display) : ''; $tooltip_html = !empty($tooltip_line_2) ? ($tooltip_line_1 . '
' . $tooltip_line_2) : $tooltip_line_1; $tooltip_aria = !empty($tooltip_line_2) ? ($tooltip_line_1 . ' ' . $tooltip_line_2) : $tooltip_line_1; ob_start(); ?>
style="">
array())); ?>
is_enabled()) { return ''; } $terms = get_option('qixit_author_terms_text', ''); if (empty(trim((string)$terms))) { return ''; } ob_start(); ?>
is_enabled()) { return ''; } $fee = $commerce->get_onboarding_fee(); if ($fee <= 0) { return '

' . esc_html__('Author signup is currently unavailable.', '2waymicropay') . '

'; } $email_mode = get_option('qixit_author_signup_email_mode', 'required'); $errors = array(); $values = array( 'username' => '', 'email' => '', 'display_name' => '', 'first_name' => '', 'last_name' => '', ); if (!empty($_GET['qixit_author_signup'])) { $status = sanitize_text_field(wp_unslash($_GET['qixit_author_signup'])); $status_messages = array( 'expired' => __('Your signup session expired. Please submit the form again.', '2waymicropay'), 'duplicate' => __('That username or email already exists. Please use different account details.', '2waymicropay'), 'invalid_password' => __('Could not validate your signup password. Please resubmit the form.', '2waymicropay'), 'create_failed' => __('Unable to create the WordPress author account. Please contact the site owner.', '2waymicropay'), 'missing_context' => __('Signup callback context was missing. Please submit the form again.', '2waymicropay'), 'no_callback_user' => __('Unable to map the callback to a user. Please contact the site owner to verify payment callback settings.', '2waymicropay'), 'missing_identity' => __('Payment callback did not return your Qixit identity. Your account was not created. Please contact the site owner and try again.', '2waymicropay'), 'invalid_callback' => __('Callback validation failed. Please retry from a fresh checkout session.', '2waymicropay'), 'invalid_payment' => __('Payment could not be verified. Please retry checkout or contact the site owner.', '2waymicropay'), 'username_taken' => __('That WordPress username is already in use. Log in with your existing account and purchase author rights from your profile instead.', '2waymicropay'), ); if (isset($status_messages[$status])) { $errors[] = $status_messages[$status]; } } if (isset($_POST['qixit_become_author_submit'])) { $nonce = isset($_POST['qixit_become_author_nonce']) ? sanitize_text_field(wp_unslash($_POST['qixit_become_author_nonce'])) : ''; if (!wp_verify_nonce($nonce, 'qixit_become_author')) { $errors[] = __('Security check failed. Please try again.', '2waymicropay'); } else { $values['username'] = sanitize_user(wp_unslash($_POST['qixit_signup_username'] ?? ''), true); $values['email'] = sanitize_email(wp_unslash($_POST['qixit_signup_email'] ?? '')); $values['display_name'] = sanitize_text_field(wp_unslash($_POST['qixit_signup_display_name'] ?? '')); $values['first_name'] = sanitize_text_field(wp_unslash($_POST['qixit_signup_first_name'] ?? '')); $values['last_name'] = sanitize_text_field(wp_unslash($_POST['qixit_signup_last_name'] ?? '')); $source_page_url = get_permalink(); if (empty($source_page_url) && isset($_SERVER['REQUEST_URI'])) { $source_page_url = home_url(sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']))); } // Intentionally keep raw password strings (unslashed only) for account creation. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be text-sanitized. $signup_password = isset($_POST['qixit_signup_password']) ? (string) wp_unslash($_POST['qixit_signup_password']) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be text-sanitized. $signup_password_confirm = isset($_POST['qixit_signup_password_confirm']) ? (string) wp_unslash($_POST['qixit_signup_password_confirm']) : ''; $signup = $commerce->create_signup_checkout_url(array( 'username' => $values['username'], 'email' => $values['email'], 'email_mode' => $email_mode, 'display_name' => $values['display_name'], 'first_name' => $values['first_name'], 'last_name' => $values['last_name'], 'source_page_url' => $source_page_url, 'password' => $signup_password, 'password_confirm' => $signup_password_confirm, 'ack_password_differs' => !empty($_POST['qixit_signup_password_differs']), )); if (!empty($signup['success']) && !empty($signup['purchase_url'])) { $checkout_url = esc_url_raw($signup['purchase_url']); // Allow Products Portal hosts for this checkout redirect only. $allow_products_host = static function ($hosts) { $hosts[] = 'products.qixit.com'; $hosts[] = 'stproducts.qixit.com'; return $hosts; }; add_filter('allowed_redirect_hosts', $allow_products_host); $redirected = wp_safe_redirect($checkout_url, 302, '2WayMicropay'); remove_filter('allowed_redirect_hosts', $allow_products_host); if (!$redirected) { // Last resort if headers already sent. echo ''; echo '

' . esc_html__('Continue to checkout', '2waymicropay') . '

'; } exit; } $errors[] = !empty($signup['error']) ? $signup['error'] : __('Unable to start author-rights checkout right now.', '2waymicropay'); } } $default_purchase_url = $commerce->get_onboarding_purchase_url(); $site_label = get_bloginfo('name'); if (empty($site_label)) { $site_label = wp_parse_url(home_url('/'), PHP_URL_HOST); } if (empty($site_label)) { $site_label = __('Site', '2waymicropay'); } $username_label = sprintf( /* translators: %s: site/blog label */ __('%s Username *', '2waymicropay'), $site_label ); ob_start(); ?>



/>






' + text + '

'; } } function clearRefusalBlockIfUsernameChanged() { if (!blockedUntilUsernameChange) return; if (currentUsername().toLowerCase() !== blockedUsername.toLowerCase()) { blockedUntilUsernameChange = false; blockedUsername = ''; setStatus('', ''); var topErr = form.parentElement ? form.parentElement.querySelector('.qixit-error') : null; if (topErr) topErr.innerHTML = ''; } } function setCheckoutEnabled(enabled) { if (!checkoutLink) return; if (enabled) { checkoutLink.style.pointerEvents = ''; checkoutLink.style.opacity = ''; checkoutLink.classList.remove('is-disabled'); checkoutLink.setAttribute('aria-disabled', 'false'); } else { checkoutLink.style.pointerEvents = 'none'; checkoutLink.style.opacity = '0.55'; checkoutLink.classList.add('is-disabled'); checkoutLink.setAttribute('aria-disabled', 'true'); } } function formIsReady() { if (!requiredFields.length) return true; for (var i = 0; i < requiredFields.length; i++) { var field = requiredFields[i]; if (typeof field.checkValidity === 'function') { if (!field.checkValidity()) return false; } else { var value = (field.value || '').trim(); if (!value) return false; } } return true; } function passwordsMatch() { var a = form.querySelector('[name=\"qixit_signup_password\"]'); var b = form.querySelector('[name=\"qixit_signup_password_confirm\"]'); if (!a || !b) return true; return String(a.value || '') === String(b.value || ''); } function updateCheckoutState() { clearRefusalBlockIfUsernameChanged(); var ready = formIsReady() && passwordsMatch() && !blockedUntilUsernameChange; setCheckoutEnabled(ready); if (blockedUntilUsernameChange) { return; } if (!formIsReady()) { setStatus('Complete the required fields above to enable purchase.', 'hint'); return; } if (!passwordsMatch()) { setStatus('Password and confirmation must match.', 'error'); return; } // Keep any existing server-rendered error; otherwise clear hints. if (statusEl && statusEl.classList.contains('is-hint')) { setStatus('', ''); } else if (statusEl && !statusEl.classList.contains('is-error')) { setStatus('', ''); } else if (statusEl && statusEl.classList.contains('is-error') && !statusEl.textContent.trim()) { setStatus('', ''); } } if (!checkoutLink) return; checkoutLink.addEventListener('click', function(e) { e.preventDefault(); if (typeof e.stopPropagation === 'function') e.stopPropagation(); if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); if (!formIsReady() || !passwordsMatch() || blockedUntilUsernameChange) { if (!passwordsMatch()) { setStatus('Password and confirmation must match.', 'error'); } else if (blockedUntilUsernameChange) { setStatus('That username is already taken. Choose a different WordPress username, then try again.', 'error'); } else if (form.reportValidity) { form.reportValidity(); setStatus('Complete the required fields above to enable purchase.', 'hint'); } updateCheckoutState(); return; } checkoutLink.style.pointerEvents = 'none'; checkoutLink.style.opacity = '0.7'; checkoutLink.classList.add('is-disabled'); if (msg) msg.style.display = 'inline'; setStatus('', ''); // Center checkout in the viewport (long posts put the button far below the fold). var clickX = window.innerWidth / 2; var clickY = (window.pageYOffset || document.documentElement.scrollTop || 0) + (window.innerHeight / 2); var frontendCfg = window.qixitFrontend || {}; var ajaxUrl = frontendCfg.ajaxUrl || ''; var nonce = frontendCfg.nonce || ''; if (!ajaxUrl || !nonce) { if (fallbackSubmit) fallbackSubmit.click(); return; } var payload = new URLSearchParams(); payload.set('action', 'qixit_author_signup_checkout'); payload.set('nonce', nonce); payload.set('qixit_signup_username', (form.querySelector('[name=\"qixit_signup_username\"]') || {}).value || ''); payload.set('qixit_signup_email', (form.querySelector('[name=\"qixit_signup_email\"]') || {}).value || ''); payload.set('qixit_signup_display_name', (form.querySelector('[name=\"qixit_signup_display_name\"]') || {}).value || ''); payload.set('qixit_signup_first_name', (form.querySelector('[name=\"qixit_signup_first_name\"]') || {}).value || ''); payload.set('qixit_signup_last_name', (form.querySelector('[name=\"qixit_signup_last_name\"]') || {}).value || ''); payload.set('qixit_signup_password', (form.querySelector('[name=\"qixit_signup_password\"]') || {}).value || ''); payload.set('qixit_signup_password_confirm', (form.querySelector('[name=\"qixit_signup_password_confirm\"]') || {}).value || ''); payload.set('qixit_signup_password_differs', (form.querySelector('[name=\"qixit_signup_password_differs\"]') || {}).checked ? '1' : ''); payload.set('source_page_url', window.location.href); fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: payload.toString() }) .then(function(r) { return r.json(); }) .then(function(json) { if (!json || !json.success || !json.data || !json.data.purchase_url) { throw new Error((json && json.data && json.data.message) ? json.data.message : 'Unable to start author-rights checkout right now.'); } var purchaseUrl = json.data.purchase_url; checkoutLink.setAttribute('href', purchaseUrl); checkoutLink.setAttribute('data-purchase-url', purchaseUrl); if (window.jQuery) { window.jQuery(checkoutLink).removeData('purchaseUrl'); window.jQuery(checkoutLink).removeData('purchase-url'); window.jQuery(checkoutLink).data('purchase-url', purchaseUrl); window.jQuery(checkoutLink).attr('data-purchase-url', purchaseUrl); } checkoutLink.setAttribute('data-force-fresh-login', 'true'); checkoutLink.setAttribute('data-link-type', 'purchase'); var pid = extractPid(purchaseUrl); if (pid) checkoutLink.setAttribute('data-product-guid', pid); // Prefer plugin overlay (iframe). Do not rely on auto-enhanced microframe-trigger. if (window.QixitFrontend && typeof window.QixitFrontend.openMicroFrame === 'function') { window.QixitFrontend.openMicroFrame(checkoutLink, false, clickX, clickY); } else { window.location.href = purchaseUrl; } }) .catch(function(err) { var message = err && err.message ? err.message : 'Unable to start author-rights checkout right now.'; showError(message); if (/already in use|username.*taken|username_taken|duplicate/i.test(message)) { blockedUntilUsernameChange = true; blockedUsername = currentUsername(); setCheckoutEnabled(false); var userField = form.querySelector('[name=\"qixit_signup_username\"]'); if (userField && typeof userField.focus === 'function') userField.focus(); } if (fallbackSubmit) { fallbackSubmit.style.setProperty('display', 'none', 'important'); } }) .finally(function() { if (msg) msg.style.display = 'none'; updateCheckoutState(); }); }); form.addEventListener('input', updateCheckoutState); form.addEventListener('change', updateCheckoutState); updateCheckoutState(); })(); JS ); ?>
__('Security check failed. Please refresh and try again.', '2waymicropay'))); } if (!class_exists('Qixit_Author_Commerce')) { wp_send_json_error(array('message' => __('Author signup is not available.', '2waymicropay'))); } $commerce = Qixit_Author_Commerce::get_instance(); if (!$commerce->is_enabled()) { wp_send_json_error(array('message' => __('Author signup is currently disabled.', '2waymicropay'))); } $email_mode = get_option('qixit_author_signup_email_mode', 'required'); // Intentionally keep raw password strings (unslashed only) for account creation. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be text-sanitized. $signup_password = isset($_POST['qixit_signup_password']) ? (string) wp_unslash($_POST['qixit_signup_password']) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be text-sanitized. $signup_password_confirm = isset($_POST['qixit_signup_password_confirm']) ? (string) wp_unslash($_POST['qixit_signup_password_confirm']) : ''; $signup = $commerce->create_signup_checkout_url(array( 'username' => sanitize_user(wp_unslash($_POST['qixit_signup_username'] ?? ''), true), 'email' => sanitize_email(wp_unslash($_POST['qixit_signup_email'] ?? '')), 'email_mode' => $email_mode, 'display_name' => sanitize_text_field(wp_unslash($_POST['qixit_signup_display_name'] ?? '')), 'first_name' => sanitize_text_field(wp_unslash($_POST['qixit_signup_first_name'] ?? '')), 'last_name' => sanitize_text_field(wp_unslash($_POST['qixit_signup_last_name'] ?? '')), 'source_page_url' => esc_url_raw(wp_unslash($_POST['source_page_url'] ?? home_url('/'))), 'password' => $signup_password, 'password_confirm' => $signup_password_confirm, 'ack_password_differs' => !empty($_POST['qixit_signup_password_differs']), )); if (!empty($signup['success']) && !empty($signup['purchase_url'])) { wp_send_json_success(array( 'purchase_url' => $signup['purchase_url'], 'message' => __('Processing... redirecting to checkout.', '2waymicropay'), )); } wp_send_json_error(array( 'message' => !empty($signup['error']) ? $signup['error'] : __('Unable to start author-rights checkout right now.', '2waymicropay'), )); } add_action('wp_ajax_qixit_author_signup_checkout', 'qixit_ajax_author_signup_checkout'); add_action('wp_ajax_nopriv_qixit_author_signup_checkout', 'qixit_ajax_author_signup_checkout'); /** * Helper function to get product price from API (uses public endpoint, no auth required). * Passes sticky A/B session when the qixit_price_session cookie is present so SSR * matches the JS overlay / checkout arm (avoids catalog-era flash). */ function qixit_get_product_price($product_guid) { $session = function_exists('qixit_price_session_id') ? qixit_price_session_id() : ''; // v2 prefix retires pre-A/B catalog transients (e.g. stale $0.02). $cache_key = 'qixit_pp_v2_' . md5($product_guid . '|' . ($session !== '' ? $session : 'anon')); $cached_price = get_transient($cache_key); if ($cached_price !== false) { return floatval($cached_price); } // Fetch from public API (no authentication required) try { $api = Qixit_API::get_instance(); $result = $api->get_public_product($product_guid, $session !== '' ? $session : null); if ($result['success'] && isset($result['data']['cost'])) { $price = floatval($result['data']['cost']); // Short TTL: A/B / Apply can change cost; session arms are sticky via session id. $ttl = $session !== '' ? MINUTE_IN_SECONDS : 60; set_transient($cache_key, $price, $ttl); return $price; } } catch (Exception $e) { // Log error but don't break the page if (class_exists('Qixit_Logger')) { Qixit_Logger::get_instance()->log('Error fetching product price: ' . $e->getMessage(), 'error'); } } return 0; } /** * Helper function to get payout/payment info from API * For payment links where users receive money (credits) * * @param string $payout_guid Payout GUID * @return array ['price' => float, 'paymentType' => int (0=real, 1=promo), 'vendorName' => string] */ function qixit_get_payout_info($payout_guid) { // Try to get cached info first $cache_key = 'qixit_payout_info_' . $payout_guid; $cached_info = get_transient($cache_key); if ($cached_info !== false) { return $cached_info; } // Default result $result = array( 'price' => 0, 'paymentType' => 0, // 0 = real funds, 1 = promo credits 'vendorName' => '', 'sellerAlias' => '', 'vendorId' => 0 ); // Fetch from public API (no authentication required) try { $api = Qixit_API::get_instance(); $response = $api->get_public_payout($payout_guid); if ($response['success'] && isset($response['data']['payAmount'])) { $result = array( 'price' => floatval($response['data']['payAmount']), 'paymentType' => isset($response['data']['paymentType']) ? intval($response['data']['paymentType']) : 0, 'vendorName' => isset($response['data']['vendorDisplayName']) ? $response['data']['vendorDisplayName'] : (isset($response['data']['vendorUserName']) ? $response['data']['vendorUserName'] : ''), 'sellerAlias' => isset($response['data']['sellerAlias']) ? $response['data']['sellerAlias'] : '', 'vendorId' => isset($response['data']['vendorId']) ? intval($response['data']['vendorId']) : 0 ); // Cache for 5 minutes set_transient($cache_key, $result, 5 * MINUTE_IN_SECONDS); } } catch (Exception $e) { // Log error but don't break the page if (class_exists('Qixit_Logger')) { Qixit_Logger::get_instance()->log('Error fetching payout info: ' . $e->getMessage(), 'error'); } } return $result; } /** * Helper function to get payout/payment price from API (backward compatible) * For payment links where users receive money (credits) */ function qixit_get_payout_price($payout_guid) { $info = qixit_get_payout_info($payout_guid); return $info['price']; } /** * Helper function to check if a payout is available (has budget, not expired) * If not available, we should NOT show the payment overlay (would be a false promise) * Now includes payment type (real vs promo) for display purposes * * @param string $payout_guid Payout GUID * @return array ['available' => bool, 'payAmount' => float, 'reason' => string, 'paymentType' => int, 'vendorName' => string] */ function qixit_check_payout_availability($payout_guid) { // Try to get cached availability first (cache for shorter time - 1 minute) $cache_key = 'qixit_payout_avail_' . $payout_guid; $cached = get_transient($cache_key); if ($cached !== false) { return $cached; } // Default to available (graceful degradation if API fails) $result = array( 'available' => true, 'payAmount' => 0, 'reason' => '', 'paymentType' => 0, // 0 = real funds, 1 = promo credits 'vendorName' => '' ); try { $api = Qixit_API::get_instance(); $response = $api->check_payout_availability($payout_guid); if ($response['success'] && isset($response['data'])) { $result = array( 'available' => !empty($response['data']['available']), 'payAmount' => isset($response['data']['payAmount']) ? floatval($response['data']['payAmount']) : 0, 'reason' => isset($response['data']['reason']) ? $response['data']['reason'] : '', 'paymentType' => isset($response['data']['paymentType']) ? intval($response['data']['paymentType']) : 0, 'vendorName' => isset($response['data']['vendorName']) ? $response['data']['vendorName'] : '' ); } } catch (Exception $e) { // Log error but assume available (graceful degradation) if (class_exists('Qixit_Logger')) { Qixit_Logger::get_instance()->log('Error checking payout availability: ' . $e->getMessage(), 'error'); } } // Cache for 1 minute (shorter than price cache since availability can change faster) set_transient($cache_key, $result, MINUTE_IN_SECONDS); return $result; } /** * Check whether a specific logged-in user is personally eligible to claim a payout. * Reads the user ID from the qixit_auth cookie if available, then calls the * /api/payment/user-eligible/ endpoint server-to-server (no CORS issues). * * Returns an array: ['eligible' => bool, 'reason' => string|null, 'deliveryUrl' => string] * Defaults to eligible=true on error or if the user is not logged in. * * @param string $payout_guid Payout GUID * @return array */ function qixit_check_user_payout_eligibility($payout_guid) { // Read the qixit_auth cookie set by the 2WayMicropay/qixit.com login if (empty($_COOKIE['qixit_auth'])) { return array('eligible' => true, 'reason' => null, 'deliveryUrl' => ''); } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- cookie JSON must remain raw for decode. $auth_cookie_raw = isset($_COOKIE['qixit_auth']) ? sanitize_text_field(wp_unslash($_COOKIE['qixit_auth'])) : ''; $auth_data = json_decode($auth_cookie_raw, true); if (!is_array($auth_data) || empty($auth_data['userId'])) { return array('eligible' => true, 'reason' => null, 'deliveryUrl' => ''); } $user_id = sanitize_text_field($auth_data['userId']); $auth_token = !empty($auth_data['token']) ? sanitize_text_field($auth_data['token']) : null; // Per-user eligibility is not cached โ€” it must be checked fresh each request // since the user may have just claimed the payout on another tab. try { $api = Qixit_API::get_instance(); $result = $api->check_user_payout_eligibility($payout_guid, $user_id, $auth_token); return $result; } catch (Exception $e) { if (class_exists('Qixit_Logger')) { Qixit_Logger::get_instance()->log('Error checking user payout eligibility: ' . $e->getMessage(), 'error'); } return array('eligible' => true, 'reason' => null, 'deliveryUrl' => ''); } }