diff --git a/class-wc-gateway-paybear.php b/class-wc-gateway-paybear.php index a25baaf..83af9f5 100644 --- a/class-wc-gateway-paybear.php +++ b/class-wc-gateway-paybear.php @@ -1,5 +1,6 @@ array( - 'name' => __( 'Paybear Payment' ), - 'singular_name' => __( 'Paybear Payment' ) + 'name' => __('Paybear Payment'), + 'singular_name' => __('Paybear Payment') ), 'public' => true, 'has_archive' => false, @@ -45,14 +48,14 @@ function create_paybear_post_type() { 'show_in_admin_bar' => false, 'show_in_rest' => false, 'hierarchical' => false, - 'supports' => array( 'title' ), + 'supports' => array('title'), // 'rewrite' => array('slug' => 'checkout') ) ); flush_rewrite_rules(); } -function paybear_payment_widget_shortcode($atts = [], $content = null, $tag = '') +function paybear_payment_widget_shortcode($atts = array(), $content = null, $tag = '') { wp_enqueue_style('paybear-css', plugin_dir_url(__FILE__) . 'assets/form/paybear.css'); wp_enqueue_script('paybear-js', plugin_dir_url(__FILE__) . 'assets/form/paybear.js', array('jquery')); @@ -87,11 +90,11 @@ function paybear_payment_widget_shortcode($atts = [], $content = null, $tag = '' $currencies = $gateway->get_currency_json($order_id); if ($token = get_post_meta($order_id, 'Token Selected', true)) { - $payments_unconfirmed = $gateway->get_unconfirmed_payments( $order_id, $token); + $payments_unconfirmed = $gateway->get_unconfirmed_payments($order_id, $token); $rate = round($order->get_total() / get_post_meta($order_id, $token . ' total', true), 8); $orderTimestamp = get_post_meta($order_id, $token . ' order timestamp', true); - $deadline = $orderTimestamp + $gateway->get_option('rate_lock_time', 15 )*60; - if (time()>$deadline) { + $deadline = $orderTimestamp + $gateway->get_option('rate_lock_time', 15) * 60; + if (time() > $deadline) { $rate = $gateway->get_exchange_rate($token); } @@ -112,7 +115,7 @@ function paybear_payment_widget_shortcode($atts = [], $content = null, $tag = '' $fiat_value = (float) $order->get_total(); $status_url = $gateway->get_status_link($order_id); - $redirect_url = $gateway->get_return_url( $order ); + $redirect_url = $gateway->get_return_url($order); $status = $order->get_status(); $payment_status = 'pending payment'; @@ -130,7 +133,7 @@ function paybear_payment_widget_shortcode($atts = [], $content = null, $tag = '' $content = '
' . sprintf( __( 'PayBear plugin could not load the conversion rates, please check if your currency (%1$s) is supported.', 'woocommerce' ), get_woocommerce_currency() ) . '
' . sprintf(__('PayBear plugin could not load the conversion rates, please check if your currency (%1$s) is supported.', 'woocommerce'), get_woocommerce_currency()) . '
' . sprintf( __( 'Please set your API keys in PayBear Settings', 'woocommerce' ), $this->get_setting_link() ) . '
' . sprintf(__('Please set your API keys in PayBear Settings', 'woocommerce'), $this->get_setting_link()) . '
' . __( 'Waiting for payment confirmation.', 'woocommerce' ) . '
'; - $str .= '' . __( 'Once your payment is confirmed, your order will be processed automatically.', 'woocommerce' ) . '
'; + $str = ''; - $underpaid = false; - if ($token = get_post_meta($order_id, 'Token Selected', true)) { - $paymentsUnconfirmed = $this->get_unconfirmed_payments( $order_id, $token); - $totalPaid = array_sum($paymentsUnconfirmed); - $toPay = get_post_meta($order_id, $token . ' total', true); - if ($totalPaid<$toPay) { - $underpaid = true; + if ($status == 'on-hold') { + $str .= '' . __('Waiting for payment confirmation.', 'woocommerce') . '
'; + $str .= '' . __('Once your payment is confirmed, your order will be processed automatically.', 'woocommerce') . '
'; + + $underpaid = false; + if ($token = get_post_meta($order_id, 'Token Selected', true)) { + $paymentsUnconfirmed = $this->get_unconfirmed_payments($order_id, $token); + $totalPaid = array_sum($paymentsUnconfirmed); + $toPay = get_post_meta($order_id, $token . ' total', true); + if ($totalPaid < $toPay) { + $underpaid = true; + } } - } - } + } - if ($status=='pending' || $status=='failed') { - $str .= '' . __( 'Once your payment is confirmed, your order will be processed automatically.', 'woocommerce' ) . '
'; + if ($status == 'pending' || $status == 'failed') { + $str .= '' . __('Once your payment is confirmed, your order will be processed automatically.', 'woocommerce') . '
'; + } + + return $str; } - return $str; - } + function order_received_text($str, $order_id) + { + $order = wc_get_order($order_id); + $status = $order->get_status(); + /** @noinspection SuspiciousAssignmentsInspection */ + $str = ''; - function order_received_text( $str, $order_id ) { - $order = wc_get_order($order_id); - $status = $order->get_status(); - /** @noinspection SuspiciousAssignmentsInspection */ - $str = ''; + if ($status == 'pending') { + $str = $str . ' ' . __('Thank you. Please select the option below to pay.'); + } - if ($status=='pending') { - $str = $str . ' ' . __( 'Thank you. Please select the option below to pay.' ); + return $str . $this->thankyou_page2($order->get_id()); } - return $str . $this->thankyou_page2( $order->get_id() ); - } + function process_ipn($order_id, $params) + { + $invoice = $params->invoice; - function process_ipn( $order_id, $params ) { - $invoice = $params->invoice; - - $order_id = intval($order_id); - $order = wc_get_order($order_id); + $order_id = intval($order_id); + $order = wc_get_order($order_id); - self::log('Order status: ' . $order->get_status()); + self::log('Order status: ' . $order->get_status()); - if (!$order || (!in_array($order->get_status(), array('pending', 'on-hold', 'failed', 'cancelled'))) ) wp_send_json($invoice); //stop processing this order + if (!$order || (!in_array($order->get_status(), array('pending', 'on-hold', 'failed', 'cancelled')))) + wp_send_json($invoice); //stop processing this order - self::log(print_r($params, true)); - $currencies = $this->get_currencies(); - $token = $this->sanitize_token($params->blockchain); - $tokenCode = strtoupper($token); - if (isset($currencies[$params->blockchain])) { - $tokenCode = $currencies[$params->blockchain]['code']; - } + self::log(print_r($params, true)); + $currencies = $this->get_currencies(); + $token = $this->sanitize_token($params->blockchain); + $tokenCode = strtoupper($token); + if (isset($currencies[$params->blockchain])) { + $tokenCode = $currencies[$params->blockchain]['code']; + } - update_post_meta( $order_id, 'Token Selected', $token); - $maxConfirmations = $params->maxConfirmations; - if (!is_numeric($maxConfirmations)) $maxConfirmations = $this->get_confirmations($token); - update_post_meta($order_id, $token . ' max_confirmations', $maxConfirmations); + update_post_meta($order_id, 'Token Selected', $token); + $maxConfirmations = $params->maxConfirmations; + if (!is_numeric($maxConfirmations)) + $maxConfirmations = $this->get_confirmations($token); + update_post_meta($order_id, $token . ' max_confirmations', $maxConfirmations); - if ($invoice == get_post_meta($order_id, $token . ' invoice', true)) { - if ($order->get_status()!='on-hold') { - // Mark as on-hold - $order->update_status( 'on-hold', __( 'Awaiting payment confirmation', 'woocommerce' ) ); - } + if ($invoice == get_post_meta($order_id, $token . ' invoice', true)) { + if ($order->get_status() != 'on-hold') { + // Mark as on-hold + $order->update_status('on-hold', __('Awaiting payment confirmation', 'woocommerce')); + } - $hash = $params->inTransaction->hash; + $hash = $params->inTransaction->hash; - $toPay = get_post_meta($order_id, $token . ' total', true); - $maxDifference = $this->get_max_underpayment() / $this->get_exchange_rate($token); - $maxDifference = max($maxDifference, 0.00000001); //always allow rounding errors - $exp = $params->inTransaction->exp; - $amountPaid = $params->inTransaction->amount / pow(10, $exp); //amount in Crypto + $toPay = get_post_meta($order_id, $token . ' total', true); + $maxDifference = $this->get_max_underpayment() / $this->get_exchange_rate($token); + $maxDifference = max($maxDifference, 0.00000001); //always allow rounding errors + $exp = $params->inTransaction->exp; + $amountPaid = $params->inTransaction->amount / pow(10, $exp); //amount in Crypto - $confirmations = json_decode(get_post_meta($order_id, $token . ' confirmation', true), true); - if (!$confirmations) $confirmations = array(); - $paymentsUnconfirmed = $this->get_unconfirmed_payments( $order_id, $token ); + $confirmations = json_decode(get_post_meta($order_id, $token . ' confirmation', true), true); + if (!$confirmations) + $confirmations = array(); + $paymentsUnconfirmed = $this->get_unconfirmed_payments($order_id, $token); + + if (isset($paymentsUnconfirmed[$hash])) { + $transactionIndex = array_search($hash, array_keys($paymentsUnconfirmed)); + if ($transactionIndex > 0) + usleep($transactionIndex * 500); //avoid race conditions + } - if (isset($paymentsUnconfirmed[$hash])) { - $transactionIndex = array_search($hash, array_keys($paymentsUnconfirmed)); - if ($transactionIndex>0) usleep($transactionIndex*500); //avoid race conditions - } + $paymentsConfirmed = $this->get_confirmed_payments($order_id, $token); - $paymentsConfirmed = $this->get_confirmed_payments( $order_id, $token); + $isNewPayment = !isset($paymentsUnconfirmed[$hash]); + $confirmations[$hash] = $params->confirmations; + $paymentsUnconfirmed[$hash] = $amountPaid; - $isNewPayment = !isset($paymentsUnconfirmed[$hash]); - $confirmations[$hash] = $params->confirmations; - $paymentsUnconfirmed[$hash] = $amountPaid; + update_post_meta($order_id, $token . ' confirmation', json_encode($confirmations)); + update_post_meta($order_id, $token . ' unconfirmed balance', json_encode($paymentsUnconfirmed)); - update_post_meta($order_id, $token . ' confirmation', json_encode($confirmations)); - update_post_meta($order_id, $token . ' unconfirmed balance', json_encode($paymentsUnconfirmed)); + $orderTimestamp = get_post_meta($order_id, $token . ' order timestamp', true); + //$paymentTimestamp = get_post_meta($order_id, $token . ' payment timestamp', true); + $deadline = $orderTimestamp + $this->get_option('rate_lock_time', 15) * 60; - $orderTimestamp = get_post_meta($order_id, $token . ' order timestamp', true); - //$paymentTimestamp = get_post_meta($order_id, $token . ' payment timestamp', true); - $deadline = $orderTimestamp + $this->get_option('rate_lock_time', 15 )*60; + //$timestamp = get_post_meta($order_id, $token . ' payment timestamp', true); + if ($isNewPayment) { + if (time() > $deadline) { //rate changed. recalculate crypto total? + self::log("PayBear IPN: late payment [" . $order_id . "]"); + self::log("PayBear IPN: old total [" . $toPay . "]"); - //$timestamp = get_post_meta($order_id, $token . ' payment timestamp', true); - if ($isNewPayment) { - if (time()>$deadline) { //rate changed. recalculate crypto total? - self::log( "PayBear IPN: late payment [" . $order_id . "]" ); - self::log("PayBear IPN: old total [" . $toPay . "]"); + $rate = $this->get_exchange_rate($token); + $fiatTotal = $order->get_total(); + if ($rate && $fiatTotal > 0) { + $newCryptoTotal = round($fiatTotal / $rate, 8); + if (true || $newCryptoTotal > $toPay) { + $toPay = $newCryptoTotal; + $this->update_crypto_total($token, $order_id, $toPay); - $rate = $this->get_exchange_rate($token); - $fiatTotal = $order->get_total(); - if ( $rate && $fiatTotal>0 ) { - $newCryptoTotal = round( $fiatTotal / $rate, 8 ); - if (true || $newCryptoTotal>$toPay) { - $toPay = $newCryptoTotal; - $this->update_crypto_total($token, $order_id, $toPay); - - self::log( "PayBear IPN: new total [" . $toPay . "]" ); + self::log("PayBear IPN: new total [" . $toPay . "]"); + } } } - } - update_post_meta($order_id, $token . ' payment timestamp', time()); - } + update_post_meta($order_id, $token . ' payment timestamp', time()); + } - if ($params->confirmations >= $maxConfirmations) { //enough confirmations for this payment - $paymentsConfirmed[$hash] = $amountPaid; - update_post_meta($order_id, $token . ' confirmed balance', json_encode($paymentsConfirmed)); + if ($params->confirmations >= $maxConfirmations) { //enough confirmations for this payment + $paymentsConfirmed[$hash] = $amountPaid; + update_post_meta($order_id, $token . ' confirmed balance', json_encode($paymentsConfirmed)); - $totalPaid = array_sum($paymentsConfirmed); + $totalPaid = array_sum($paymentsConfirmed); - self::log("PayBear IPN: toPay [" . $toPay . "]"); - self::log("PayBear IPN: paid [" . $amountPaid . "]"); - self::log("PayBear IPN: total paid [" . $totalPaid . "]"); - self::log("PayBear IPN: maxDifference [" . round($maxDifference, 9) . "]"); + self::log("PayBear IPN: toPay [" . $toPay . "]"); + self::log("PayBear IPN: paid [" . $amountPaid . "]"); + self::log("PayBear IPN: total paid [" . $totalPaid . "]"); + self::log("PayBear IPN: maxDifference [" . round($maxDifference, 9) . "]"); - if ($toPay>0 && ($toPay-$totalPaid)<$maxDifference) { //allow loss caused by rounding - self::log( 'Payment complete' ); - $order->payment_complete( $params->inTransaction->hash ); + if ($toPay > 0 && ($toPay - $totalPaid) < $maxDifference) { //allow loss caused by rounding + self::log('Payment complete'); + $order->payment_complete($params->inTransaction->hash); - $overpaidCrypto = $totalPaid-$toPay; - $overpaid = round( $overpaidCrypto * $this->get_exchange_rate( $token ), 2 ); - $minOverpaymentFiat = $this->get_min_overpayment(); - if ($overpaid > $minOverpaymentFiat) { //overpayment - $note = sprintf( - __( ' + $overpaidCrypto = $totalPaid - $toPay; + $overpaid = round($overpaidCrypto * $this->get_exchange_rate($token), 2); + $minOverpaymentFiat = $this->get_min_overpayment(); + if ($overpaid > $minOverpaymentFiat) { //overpayment + $note = sprintf( + __(' Whoops, you overpaid %s %s (%s %s) @@ -795,388 +831,405 @@ function process_ipn( $order_id, $params ) { Tip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees. Tip 3) Be sure to successfully send your payment before the countdown timer expires. -This timer is setup to lock in a fixed rate for your payment. Once it expires, rates may change.', 'woocommerce' ), - $overpaidCrypto, strtoupper( $tokenCode ), get_woocommerce_currency_symbol(), $overpaid, $order_id, strtoupper( $tokenCode ), strtoupper( $tokenCode ), get_woocommerce_currency() ); - $order->add_order_note( $note, 1, false ); - } - } else { //underpayment - self::log("PayBear IPN: underpayment [" . $order_id . "]"); - //if (!empty($this->debug_email)) { mail($this->debug_email, "PayBear IPN: wrong amount [" . $order_id . "]", print_r($params, true)); } - - $order->update_status('on-hold' ); - $underpaidCrypto = $toPay - $totalPaid; - $underpaid = round( $underpaidCrypto * $this->get_exchange_rate($token), 2); - $note = sprintf(__( 'Looks like you underpaid %s %s (%s %s) - +This timer is setup to lock in a fixed rate for your payment. Once it expires, rates may change.', 'woocommerce'), + $overpaidCrypto, strtoupper($tokenCode), get_woocommerce_currency_symbol(), $overpaid, $order_id, strtoupper($tokenCode), strtoupper($tokenCode), get_woocommerce_currency()); + $order->add_order_note($note, 1, false); + } + } else { //underpayment + self::log("PayBear IPN: underpayment [" . $order_id . "]"); + //if (!empty($this->debug_email)) { mail($this->debug_email, "PayBear IPN: wrong amount [" . $order_id . "]", print_r($params, true)); } + + $order->update_status('on-hold'); + $underpaidCrypto = $toPay - $totalPaid; + $underpaid = round($underpaidCrypto * $this->get_exchange_rate($token), 2); + $note = sprintf(__('Looks like you underpaid %s %s (%s %s) + Don\'t worry, here is what to do next: - + Contact the merchant directly and… -Request details on how you can pay the difference. -Request a refund and create a new order. - - + + Tips for Paying with Crypto: - + Tip 1) When paying, ensure you send the correct amount in %s. Do not manually enter the %s Value. - + Tip 2) If you are sending from an exchange, be sure to correctly factor in their withdrawal fees. - + Tip 3) Be sure to successfully send your payment before the countdown timer expires. This timer is setup to lock in a fixed rate for your payment. Once it expires, rates may change.', 'woocommerce'), - $underpaidCrypto, strtoupper($tokenCode), get_woocommerce_currency_symbol(), $underpaid, strtoupper( $tokenCode ), get_woocommerce_currency()); - $order->add_order_note( $note, 1, false ); + $underpaidCrypto, strtoupper($tokenCode), get_woocommerce_currency_symbol(), $underpaid, strtoupper($tokenCode), get_woocommerce_currency()); + $order->add_order_note($note, 1, false); - update_post_meta($order_id, $token . ' order timestamp', time()); //extend payment window + update_post_meta($order_id, $token . ' order timestamp', time()); //extend payment window + } + + wp_send_json($invoice); //stop processing callbacks } - wp_send_json($invoice); //stop processing callbacks + self::log(sprintf('Callback processed: %s/%s', $params->confirmations, $maxConfirmations)); + } else { + self::log("PayBear IPN: wrong invoice [" . $order_id . ' / ' . get_post_meta($order_id, $token . ' invoice', true) . "]"); + if (!empty($this->debug_email)) { + mail($this->debug_email, "PayBear IPN: wrong invoice [" . $invoice . "]", print_r($params, true)); + } } - self::log(sprintf('Callback processed: %s/%s', $params->confirmations, $maxConfirmations)); - } else { - self::log("PayBear IPN: wrong invoice [" . $order_id . ' / ' . get_post_meta($order_id, $token . ' invoice', true) . "]"); - if (!empty($this->debug_email)) { mail($this->debug_email, "PayBear IPN: wrong invoice [" . $invoice . "]", print_r($params, true)); } + wp_send_json('WAITING'); } - wp_send_json('WAITING'); - } + /** + * Check for IPN Response + * + * @access public + * @return void + */ + function check_ipn_response() + { + + @ob_clean(); + if (isset($_GET['address']) && isset($_GET['order_id'])) { //address request + $json = $this->get_currency_json($_GET['order_id'], $_GET['address']); + wp_send_json($json); + } - /** - * Check for IPN Response - * - * @access public - * @return void - */ - function check_ipn_response() { + if (isset($_GET['status'])) { //address request + return $this->get_status($_GET['status']); + } - @ob_clean(); - if (isset($_GET['address']) && isset($_GET['order_id'])) { //address request - $json = $this->get_currency_json($_GET['order_id'], $_GET['address']); - wp_send_json($json); - } + self::log("PayBear IPN:" . print_r($_GET, true) . ' / ' . print_r($_POST, true)); + + if (isset($_GET['order_id'])) { + $order_id = intval($_GET['order_id']); + $data = file_get_contents('php://input'); + self::log("PayBear IPN data:" . $data); + if ($data) { + $params = json_decode($data); + if ($params) { + $this->process_ipn($order_id, $params); + } + } - if (isset($_GET['status'])) { //address request - return $this->get_status($_GET['status']); + } else { + wp_die("PayBear IPN Request Failure"); + } } - self::log("PayBear IPN:" . print_r($_GET, true) . ' / ' . print_r($_POST, true)); + function get_json($order_id) + { + $order_id = intval($order_id); + $order = wc_get_order($order_id); + $value = $order->get_total(); + + $currencies = $this->get_currency_json($order_id); - if ( isset($_GET['order_id']) ) { - $order_id = intval($_GET['order_id']); - $data = file_get_contents('php://input'); - self::log("PayBear IPN data:" . $data); - if ($data) { - $params = json_decode($data); - if ($params) { - $this->process_ipn( $order_id, $params ); + if ($token = get_post_meta($order_id, 'Token Selected', true)) { + $paymentsUnconfirmed = $this->get_unconfirmed_payments($order_id, $token); + $totalPaid = array_sum($paymentsUnconfirmed); + if ($totalPaid > 0) { + $currencies = array($this->get_currency_json($order_id, $token)); } } - } else { - wp_die( "PayBear IPN Request Failure" ); + $response = array( + 'button' => '#paybear-all', + 'modal' => true, + 'currencies' => $currencies, + //'currenciesUrl' => $this->get_address_link($order_id), + 'fiatValue' => doubleval($value), + 'fiatCurrency' => strtoupper(get_woocommerce_currency()), + 'fiatSign' => get_woocommerce_currency_symbol(), + 'maxUnderpaymentFiat' => 1, + 'minOverpaymentFiat' => 10, + 'enableFiatTotal' => true, + 'enablePoweredBy' => false, + 'statusUrl' => $this->get_status_link($order_id), + 'redirectTo' => $this->get_return_url($order), + 'redirectTimeout' => 0, + 'timer' => $this->get_option('rate_lock_time', 15) * 60 + ); + + return $response; } - } - function get_json($order_id) - { - $order_id = intval($order_id); - $order = wc_get_order($order_id); - $value = $order->get_total(); + function get_currency_json($order_id, $token = 'all') + { + $order_id = intval($order_id); + $order = wc_get_order($order_id); + $value = $order->get_total(); + $token = $this->sanitize_token($token); - $currencies = $this->get_currency_json($order_id); + $currencies = array(); - if ($token = get_post_meta($order_id, 'Token Selected', true)) { - $paymentsUnconfirmed = $this->get_unconfirmed_payments( $order_id, $token); - $totalPaid = array_sum($paymentsUnconfirmed); - if ($totalPaid>0) { - $currencies = array($this->get_currency_json($order_id, $token)); + foreach ($this->get_currencies() as $code => $currency) { + $rate = $this->get_exchange_rate($code); + if ($rate) { + $amount = round($value / $rate, 8); + if ($amount >= $currency['minimum']) { + if ($token == 'all') { + $currency['currencyUrl'] = $this->get_address_link($order_id, $code); + $currency['coinsValue'] = $amount; + $currency['rate'] = round($rate, 2); + + $currencies[] = $currency; + } elseif ($token == $code) { + $paymentsUnconfirmed = $this->get_unconfirmed_payments($order_id, $token); + $unconfirmedTotal = array_sum($paymentsUnconfirmed); + + $address = $this->get_address($code, $order_id, $amount); + $currency['coinsValue'] = $amount; + $currency['coinsPaid'] = $unconfirmedTotal; + $currency['rate'] = round($rate, 2); + $currency['maxConfirmations'] = $this->get_confirmations($code); + $currency['address'] = $address; + + $currencies[] = $currency; + } + } + } } - } - $response = array( - 'button' => '#paybear-all', - 'modal' => true, - 'currencies' => $currencies, - //'currenciesUrl' => $this->get_address_link($order_id), - 'fiatValue' => doubleval($value), - 'fiatCurrency' => strtoupper(get_woocommerce_currency()), - 'fiatSign' => get_woocommerce_currency_symbol(), - 'maxUnderpaymentFiat' => 1, - 'minOverpaymentFiat' => 10, - 'enableFiatTotal' => true, - 'enablePoweredBy' => false, - 'statusUrl' => $this->get_status_link($order_id), - 'redirectTo' => $this->get_return_url( $order ), - 'redirectTimeout' => 0, - 'timer' => $this->get_option('rate_lock_time', 15 )*60 - ); - - return $response; - } - function get_currency_json($order_id, $token = 'all') - { - $order_id = intval($order_id); - $order = wc_get_order($order_id); - $value = $order->get_total(); - $token = $this->sanitize_token($token); - - $currencies = array(); - - foreach ($this->get_currencies() as $code => $currency) { - $rate = $this->get_exchange_rate($code); - if ( $rate ) { - $amount = round( $value / $rate, 8 ); - if ( $amount >= $currency['minimum'] ) { - if ($token=='all') { - $currency['currencyUrl'] = $this->get_address_link( $order_id, $code ); - $currency['coinsValue'] = $amount; - $currency['rate'] = round( $rate, 2 ); - - $currencies[] = $currency; - } elseif ( $token == $code ) { - $paymentsUnconfirmed = $this->get_unconfirmed_payments( $order_id, $token); - $unconfirmedTotal = array_sum($paymentsUnconfirmed); - - $address = $this->get_address( $code, $order_id, $amount ); - $currency['coinsValue'] = $amount; - $currency['coinsPaid'] = $unconfirmedTotal; - $currency['rate'] = round( $rate, 2 ); - $currency['maxConfirmations'] = $this->get_confirmations( $code ); - $currency['address'] = $address; - - $currencies[] = $currency; - } - } + if ($token != 'all') { + update_post_meta($order_id, 'Token Selected', $token); + + return count($currencies) > 0 ? current($currencies) : array(); + } else { + return $currencies; } + } + function get_status($order_id) + { + $order_id = intval($order_id); + $order = wc_get_order($order_id); - if ($token!='all') { - update_post_meta( $order_id, 'Token Selected', $token); - return count($currencies)>0 ? current($currencies) : array(); - } else { - return $currencies; - } + $response = array(); - } + $status = $order->get_status(); - function get_status($order_id) - { - $order_id = intval($order_id); - $order = wc_get_order($order_id); + if ($order && ($status == 'on-hold' || $status == 'processing' || $status == 'failed')) { - $response = array(); + $token = get_post_meta($order_id, 'Token Selected', true); + if ($token) { + $toPay = get_post_meta($order_id, $token . ' total', true); - $status = $order->get_status(); + $maxDifference = $this->get_max_underpayment() / $this->get_exchange_rate($token); + $maxDifference = max($maxDifference, 0.00000001); //always allow rounding errors - if ($order && ($status=='on-hold' || $status=='processing' || $status=='failed')) { + $maxConfirmations = get_post_meta($order_id, $token . ' max_confirmations', true); - $token = get_post_meta( $order_id, 'Token Selected', true); - if ($token) { - $toPay = get_post_meta($order_id, $token . ' total', true); + $confirmations = json_decode(get_post_meta($order_id, $token . ' confirmation', true), true); + if (!$confirmations) + $confirmations = array(); + $paymentsUnconfirmed = $this->get_unconfirmed_payments($order_id, $token); + $paymentsConfirmed = $this->get_confirmed_payments($order_id, $token); - $maxDifference = $this->get_max_underpayment() / $this->get_exchange_rate($token); - $maxDifference = max($maxDifference, 0.00000001); //always allow rounding errors + $totalConfirmations = min($confirmations); + $totalUnconfirmed = array_sum($paymentsUnconfirmed); + $totalConfirmed = array_sum($paymentsConfirmed); - $maxConfirmations = get_post_meta( $order_id, $token . ' max_confirmations', true); + $response['success'] = ($totalConfirmations >= $maxConfirmations) && ($totalConfirmed > ($toPay - $maxDifference)); - $confirmations = json_decode(get_post_meta($order_id, $token . ' confirmation', true), true); - if (!$confirmations) $confirmations = array(); - $paymentsUnconfirmed = $this->get_unconfirmed_payments( $order_id, $token); - $paymentsConfirmed = $this->get_confirmed_payments( $order_id, $token); + $response['coinsPaid'] = $totalUnconfirmed; - $totalConfirmations = min($confirmations); - $totalUnconfirmed = array_sum($paymentsUnconfirmed); - $totalConfirmed = array_sum($paymentsConfirmed); + if (!empty($paymentsUnconfirmed)) + $response['confirmations'] = $totalConfirmations; + } + } - $response['success'] = ($totalConfirmations >= $maxConfirmations) && ($totalConfirmed>($toPay-$maxDifference)); + wp_send_json($response); + } - $response['coinsPaid'] = $totalUnconfirmed; - if (!empty($paymentsUnconfirmed)) $response['confirmations'] = $totalConfirmations; + public static function log($message) + { + if (empty(self::$log)) { + self::$log = wc_get_logger(); } + + self::$log->add('woocommerce-gateway-paybear', $message); } - wp_send_json($response); - } + function get_exchange_rate($token) + { + static $cache; + $token = strtolower($token); + if (!$cache || !isset($cache->$token)) { + $currency = strtolower(get_woocommerce_currency()); + $url = $this->api_domain() . sprintf("/v2/exchange/%s/rate", $currency); - public static function log( $message ) { - if ( empty( self::$log ) ) { - self::$log = wc_get_logger(); - } + if ($response = wp_remote_fopen($url)) { + $response = json_decode($response); + if ($response->success) { + $cache = $response->data; + } + } else { + $error = error_get_last(); + self::log("Cannot get rates: " . print_r($error, true)); + } + } - self::$log->add( 'woocommerce-gateway-paybear', $message ); - } + $rate = isset($cache->$token->mid) ? $cache->$token->mid : null; + $shop_currency = strtolower(get_woocommerce_currency()); - function get_exchange_rate( $token ) { - static $cache; + if (isset($cache->$shop_currency)) { + return $cache->$token->mid / $cache->$shop_currency->mid; + } - $token = strtolower($token); + return $rate; + } - if (!$cache || !isset($cache->$token)) { - $currency = strtolower(get_woocommerce_currency()); - $url = $this->api_domain() . sprintf("/v2/exchange/%s/rate", $currency); + public function update_crypto_total($token, $order_id, $total) + { + $token = $this->sanitize_token($token); - if ( $response = wp_remote_fopen( $url ) ) { - $response = json_decode( $response ); - if ( $response->success ) { - $cache = $response->data; + /* + if ($total===false) { + $rate = $this->get_exchange_rate($token); + $order = wc_get_order($order_id); + $value = $order->get_total(); + if ( $rate && $value>0 ) { + $total = round( $value / $rate, 8 ); } - } else { - $error = error_get_last(); - self::log("Cannot get rates: " . print_r($error, true)); } - } + */ - $rate = isset($cache->$token->mid) ? $cache->$token->mid : null; - $shop_currency = strtolower(get_woocommerce_currency()); + if ($total > 0) { + update_post_meta($order_id, $token . ' total', $total); + update_post_meta($order_id, $token . ' order timestamp', time()); + } + + return $total; - if (isset($cache->$shop_currency)) { - return $cache->$token->mid/$cache->$shop_currency->mid; } - return $rate; - } + public function get_address($token, $order_id, $total) + { + $token = $this->sanitize_token($token); - public function update_crypto_total($token, $order_id, $total) - { - $token = $this->sanitize_token($token); + //return '0xTESTJKADHFJKDHFJKSDFSDF'; - /* - if ($total===false) { - $rate = $this->get_exchange_rate($token); - $order = wc_get_order($order_id); - $value = $order->get_total(); - if ( $rate && $value>0 ) { - $total = round( $value / $rate, 8 ); + if ($address = get_post_meta($order_id, $token . ' address', true)) { + $this->update_crypto_total($token, $order_id, $total); + + return $address; } - } - */ - if ($total>0) { - update_post_meta( $order_id, $token . ' total', $total ); - update_post_meta( $order_id, $token . ' order timestamp', time() ); - } + $secret = $this->get_option('api_secret'); - return $total; + $callbackUrl = $this->get_ipn_link($order_id); + //$callbackUrl = 'http://demo.paybear.io/ojosidfjsdf'; - } + $url = sprintf($this->api_domain() . '/v2/%s/payment/%s?token=%s', $token, urlencode($callbackUrl), $secret); + self::log("PayBear address request: " . $url); + if ($contents = wp_remote_fopen($url)) { + $response = json_decode($contents); + self::log("PayBear address response: " . print_r($response, true)); + if (isset($response->data->address)) { + $address = $response->data->address; - public function get_address( $token, $order_id, $total ) - { - $token = $this->sanitize_token($token); + update_post_meta($order_id, $token . ' address', $address); + update_post_meta($order_id, $token . ' invoice', $response->data->invoice); - //return '0xTESTJKADHFJKDHFJKSDFSDF'; + $this->update_crypto_total($token, $order_id, $total); - if ($address = get_post_meta($order_id, $token . ' address', true)) { - $this->update_crypto_total($token, $order_id, $total); - return $address; + return $address; + } else { + self::log("PayBear API responded: " . $contents); + } + } } - $secret = $this->get_option( 'api_secret' ); - - $callbackUrl = $this->get_ipn_link($order_id); - //$callbackUrl = 'http://demo.paybear.io/ojosidfjsdf'; - - $url = sprintf($this->api_domain() . '/v2/%s/payment/%s?token=%s', $token, urlencode($callbackUrl), $secret); - self::log("PayBear address request: " . $url); - if ($contents = wp_remote_fopen($url)) { - $response = json_decode($contents); - self::log("PayBear address response: " . print_r($response, true)); - if (isset($response->data->address)) { - $address = $response->data->address; + public function sanitize_token($token) + { + $token = strtolower($token); + $token = preg_replace('/[^a-z0-9:]/', '', $token); - update_post_meta($order_id, $token . ' address', $address); - update_post_meta($order_id, $token . ' invoice', $response->data->invoice); + return $token; + } - $this->update_crypto_total($token, $order_id, $total); + private function get_min_overpayment() + { + return doubleval($this->get_option('min_overpayment', 1)); + } - return $address; - } else { - self::log("PayBear API responded: " . $contents); - } + private function get_max_underpayment() + { + return doubleval($this->get_option('max_underpayment', 0.01)); } - } - public function sanitize_token( $token ) { - $token = strtolower($token); - $token = preg_replace('/[^a-z0-9:]/', '', $token); - return $token; - } + public static function plugin_activation() + { + $self = self::get_instance(); - private function get_min_overpayment() { - return doubleval($this->get_option( 'min_overpayment', 1 )); - } - private function get_max_underpayment() { - return doubleval($this->get_option( 'max_underpayment', 0.01 )); - } + $self->settings['payment_page_id'] = null; + update_option($self->get_option_key(), apply_filters('woocommerce_settings_api_sanitized_fields_' . $self->id, $self->settings)); - public static function plugin_activation() - { - $self = self::get_instance(); + $page_id = $self->get_option('payment_page_id'); - $self->settings['payment_page_id'] = null; - update_option( $self->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $self->id, $self->settings ) ); + if ($page_id && get_post_type($page_id) != 'paybear_payment') { + wp_delete_post($page_id); + } - $page_id = $self->get_option('payment_page_id'); + if (!$page_id) { + add_action('init', function () use ($self) { + $guid = home_url('/paybear_payment/paybear'); + + $page_id = $self::get_post_id_from_guid($guid); + if (!$page_id) { + $page_data = array( + 'post_status' => 'publish', + 'post_type' => 'paybear_payment', + // 'post_author' => 1, + // 'post_name' => 'paybear', + 'post_title' => 'Paybear', + 'post_content' => '[paybear_payment_widget]', + // 'post_parent' => $parent_id, + 'comment_status' => 'closed', + 'guid' => $guid, + ); + $page_id = wp_insert_post($page_data); + } - if ($page_id && get_post_type($page_id) != 'paybear_payment') { - wp_delete_post($page_id); + $self->settings['payment_page_id'] = $page_id; + update_option($self->get_option_key(), apply_filters('woocommerce_settings_api_sanitized_fields_' . $self->id, $self->settings)); + }); + } } - if (!$page_id) { - add_action('init', function () use ($self) { - $guid = home_url('/paybear_payment/paybear'); - - $page_id = self::get_post_id_from_guid($guid); - if (!$page_id) { - $page_data = array( - 'post_status' => 'publish', - 'post_type' => 'paybear_payment', - // 'post_author' => 1, - // 'post_name' => 'paybear', - 'post_title' => 'Paybear', - 'post_content' => '[paybear_payment_widget]', - // 'post_parent' => $parent_id, - 'comment_status' => 'closed', - 'guid' => $guid, - ); - $page_id = wp_insert_post( $page_data ); - } - $self->settings['payment_page_id'] = $page_id; - update_option( $self->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $self->id, $self->settings ) ); - }); + public static function plugin_deactivation() + { + $post_id = self::get_instance()->get_option('payment_page_id'); + if ($post_id) { + wp_delete_post($post_id, true); + } } - } + public static function get_post_id_from_guid($guid) + { + global $wpdb; - public static function plugin_deactivation() - { - $post_id = self::get_instance()->get_option('payment_page_id'); - if ($post_id) { - wp_delete_post($post_id, true); - } - } + return $wpdb->get_var($wpdb->prepare("SELECT id FROM $wpdb->posts WHERE guid=%s", $guid)); - public static function get_post_id_from_guid( $guid ){ - global $wpdb; - return $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->posts WHERE guid=%s", $guid ) ); + } } -} - -class WC_Paybear extends WC_Gateway_Paybear { - public function __construct() { - _deprecated_function( 'WC_Paybear', '1.4', 'WC_Gateway_Paybear' ); - parent::__construct(); + class WC_Paybear extends WC_Gateway_Paybear + { + public function __construct() + { + _deprecated_function('WC_Paybear', '1.4', 'WC_Gateway_Paybear'); + parent::__construct(); + } } -} $GLOBALS['wc_paybear'] = WC_Gateway_Paybear::get_instance(); }