Woocommerce API соединение для размещения кнопки заказа - PullRequest
1 голос
/ 15 марта 2019

Я пытаюсь подключиться к API с помощью приведенного ниже кода, поэтому, когда клиент нажимает кнопку «разместить заказ» на странице оформления заказа в Woocommerce, я получаю «повторите попытку» ошибка :

var amount = <?php global $woocommerce; print WC()->cart->total; ?>;
var merchantOrderId = '<?php echo print time(); ?>';
var apiKey = 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t';

renderMMoneyPaymentButton(amount, merchantOrderId, apiKey);

Я пытаюсь передать эту информацию в API через эту функцию, но я не получаю успешного соединения.

public function process_payment( $order_id ) {

    global $woocommerce;

    // we need it to get any order detailes
    $order = new WC_Order($order_id);


    /*
     * Array with parameters for API interaction
     */
    $args = array(
     'amount' => '<?php global $woocommerce; print WC()->cart->total; ?>',
     'merchant_order_id' => '<?php print time(); ?>',
     '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;
    }

}

дайте мне знать, что я делаю неправильно, высоко ценится, и это также другой сценарий

 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');


}

1 Ответ

0 голосов
/ 16 марта 2019

1) В своем первом фрагменте кода вы используете javascript, и вам необходимо получить идентификатор заказа , а затем общая сумма заказа … Вы можете получить идентификатор заказа только после заказа помещается ...

Пример ответа здесь .

2) Ваша вторая публичная функция включает только PHP ... В этом коде есть некоторые ошибки и ошибки. Попробуйте вместо этого следующий код:

public function process_payment( $order_id ) {

    // Get The WC_Order Object instance
    $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'          => $order->get_currency(),
    );

    /*
     * 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;
    }

}

Должно работать лучше.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...