自定义woocommerce付款网关

时间:2019-03-16 15:59:12

标签: php woocommerce

让此自定义插件正常工作,但是当您按绿色mmomey按钮时,iframe会弹出一个我想要做的事情,是当在结帐页面上按黑色mmoney按钮时,它会拉起绿色mmoney按钮或更好的是弹出相同的iframe。您可以将以下代码压缩后,作为插件安装在测试电子商务平台中。

<?php
/*
 * Plugin Name: WooCommerce Mmoney Payment Gateway
 * Plugin URI: https://nnbtechnologies.com
 * Description: Take mMoney payments on your store.
 * Author: NNBCONSULTING BDS LTD
* Author URI: https://nnbtechnologies.com
 * Version: 1.0.1
 *
/

/*
 * This action hook registers our PHP class as a WooCommerce payment gateway
 */


add_filter( 'woocommerce_payment_gateways', 'mmoney_add_gateway_class' );
function mmoney_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Money_Gateway'; // your class name is here
	return $gateways;
}

function mmoney_enqueue_script() {
	wp_enqueue_script( 'payment-js', 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', false);
?>
<script>
     


    function renderMMoneyPaymentButton(amount, merchantOrderId, apiKey) {
      let paymentParams = {
        amount: amount,
        api_key: apiKey,
        currency: 'BBD',
        merchant_order_id: merchantOrderId,
        onCancel: function () { console.log('Modal closed'); },
        onError: function(error) { console.log('Error', error); },
        onPaid: function (invoice) { console.log('Payment complete', invoice); }
      };

      // "mMoney" window global provided by sourcing mmoney-payment.js script.
      // Attach the button to the empty element.
      mMoney.payment.button.render(paymentParams, '#mmoney-payment-button');
	  

    }
	
  </script>
  
  
<?php }
add_action( 'wp_enqueue_scripts', 'mmoney_enqueue_script');
add_action ('woocommerce_checkout_place_order', 'renderMMoneyPaymentButton');
/*
 * The class itself, please note that it is inside plugins_loaded action hook
 */
add_action( 'plugins_loaded', 'money_init_gateway_class' );
function money_init_gateway_class() {
 
	class WC_Money_Gateway extends WC_Payment_Gateway {
 
 		/**
 		 * Class constructor, more about it in Step 3
 		 */
 		public function __construct() {
 
	$this->id = 'mmoney'; // payment gateway plugin ID
	$this->icon = ''; // URL of the icon that will be displayed on checkout page near your gateway name
	$this->has_fields = false; // in case you need a custom credit card form
	$this->method_title = 'mMoney Gateway BARBADOS ONLY';
	$this->method_description = 'mMoney payment gateway redirects customers to enter payment information'; // will be displayed on the options page
 
	// gateways can support subscriptions, refunds, saved payment methods,
	// but in this tutorial we begin with simple payments
	$this->supports = array(
		'products'
	);
 
	// Method with all the options fields
	$this->init_form_fields();
 
	// Load the settings.
	$this->init_settings();
	$this->title = $this->get_option( 'title' );
	$this->description = $this->get_option( 'description' );
	$this->publishable_key = $this->get_option( 'publishable_key' );
 
	// This action hook saves the settings
	add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
	// This action activates the 
	
 
	// We need custom JavaScript to obtain a token
	
	add_action( 'render_mmoney_payment_button_script_js' );
	  
 
	// You can also register a webhook here
	
       add_action( 'woocommerce_api_{event}', array( $this, 'webhook' ) );
 		}
 
		/**
 		 * Plugin options, we deal with it in Step 3 too
 		 */
 		public function init_form_fields(){
 
		$this->form_fields = array(
		'enabled' => array(
			'title'       => 'Enable/Disable',
			'label'       => 'Enable Mmoney',
			'type'        => 'checkbox',
			'description' => '',
			'default'     => 'no'
		),
		'title' => array(
			'title'       => 'Title',
			'type'        => 'text',
			'description' => 'This controls the title which the user sees during checkout.',
			'default'     => 'mMoney',
			'desc_tip'    => true,
		),
		'description' => array(
			'title'       => 'Description',
			'type'        => 'textarea',
			'description' => 'This controls the description which the user sees during checkout.',
			'default'     => 'Pay with your mMoney Account.',
		),
		
		
		'publishable_key' => array(
			'title'       => 'Live API Key',
			'description' => 'Enter the API generated from your merchant account here.',
			'type'        => 'text'
		),
		
	);
 
	 	}

public function validate_fields(){
 
	if( empty( $_POST[ 'billing_first_name' ]) ) {
		wc_add_notice(  'First name is required!', 'error' );
		return false;
	}
	return true;
 
}


		
 
 public function payment_fields() {
 
	// ok, let's display some description before the payment form
	if ( $this->description ) {
		// you can instructions for test mode, I mean test card numbers etc.
		
		// display the description with <p> tags etc.
		echo wpautop( wp_kses_post( $this->description ) );
		
		
		
		
		
		
		
	}

add_filter( 'woocommerce_checkout_fields' , 'misha_not_required_fields', 9999 );
 

	
?>	

      
    <!-- Insert the mMoney button in your website, where you want it to be seen -->
    <div id='mmoney-payment-button'>     </div>


<script>

    // Provide values from the current cart order
	var amount = <?php global $woocommerce; print WC()->cart->total; ?>;
    var merchantOrderId = '<?php print time(); ?>';
    var apiKey = 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t';

    renderMMoneyPaymentButton(amount, merchantOrderId, apiKey);
	
	
	
</script>
<?php echo  $order_id = str_pad($order_id, 10, '0', STR_PAD_LEFT); ?>

<?php  
 do_action( 'woocommerce_credit_card_form_end', $this->id );
 
	echo '<div class="clear"></div></fieldset>';
 
}

 public function render_mmoney_payment_button_script_js(){
    // Only on Order received page
    if( is_wc_endpoint_url('order-processing') ) :

    // get order ID
    $order_id = get_query_var('order-processing');

    // Format order ID to 4 digits
    $order_id = str_pad($order_id, 4, '0', STR_PAD_LEFT); 

    // Get the order Object
    $order    = wc_get_order( $order_id );

    // Get order total amount
    $total    = $order->get_total()
 ?>   
	<script type="text/javascript">
    var apiKey = 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t';
    renderMMoneyPaymentButton(<?php global $woocommerce; print WC()->cart->total; ?>, <?php print time(); ?>, apiKey)
    </script>
<?php	
	endif;
}
  public function process_payment( $order_id ) {
 
	
    
	// we need it to get any order detailes
	 $order = wc_get_order( $order_id );
 
 
	/*
 	 * Array with parameters for API interaction
	 */
	$args = array(
        'amount'            => $order->get_total(),
        'merchant_order_id' => $order_id,
        'api_Key'           => 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t',
        'currency'          => 'BBD',
    );
	/*
	 * Your API interaction could be built with wp_remote_post()
 	 */
	 $response = wp_remote_post( 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', $args );
 
 
	 if( !is_wp_error( $response ) ) {
 
		 $body = json_decode( $response['body'], true );
 
		 // it could be different depending on your payment processor
		 if ( $body ['$response'] == 'APPROVED') {
 
			// we received the payment
			$order->payment_complete();
			$order->reduce_order_stock();
 
			// some notes to customer (replace true with false to make it private)
			$order->add_order_note( 'Thanks for your payment!!!!', true );
 
			// Empty cart
			$woocommerce->cart->empty_cart();
 
			// Redirect to the thank you page
			return array(
				'result' => 'success',
				'redirect' => $this->get_return_url( $order )
			);
 
		 } else {
			wc_add_notice(  'Please try again.', 'error' );
			return;
		}
 
	} else {
		wc_add_notice(  'Connection error.', 'error' );
		return;
	}
 
}

  
  //creating webhook
public function webhook() {
 
	$order = wc_get_order( $_GET['id'] );
	$order->payment_complete();
	$order->reduce_order_stock();
 
	update_option('webhook_debug', $_GET);
}


      

		
 
		
 	}
	
	
	
}

0 个答案:

没有答案