Платные кредитные карты программно в WooCommerce - PullRequest
1 голос
/ 23 мая 2019

Я создаю заказ программно в WooCommerce, и мне нужно списать со счета сохраненную кредитную карту по умолчанию. Я использую плагин полос WooCommerce и выяснил, как установить правильный способ оплаты, но не могу понять, как на самом деле зарядить карту. Ниже приведен код, который у меня есть.

$order = wc_create_order();

$order->add_product( wc_get_product( 52 ), 1 );
$order->set_address( $shipping_address, 'shipping' );
$order->set_address($user_info, 'billing');

$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method($payment_gateways['stripe']);

$order->calculate_totals(); 
$order->update_status("Completed", 'First Partner Order', TRUE);
$order->save();

1 Ответ

0 голосов
/ 23 мая 2019

Мне удалось найти решение, хотя и не очень элегантное, похоже, работает. Основная предпосылка заключается в том, что мы используем полосовой API для создания начисления, а затем добавляем все пользовательские поля вручную. Это приведет к успешной оплате, которая отражается в WooCommerce и может быть возвращена через администратора позже. Ниже приведен код с комментариями. Я хотел бы знать, нашел ли кто-нибудь лучшее решение.

Примечание: вы должны использовать sripe php api

$order = wc_create_order();

$order->add_product( wc_get_product( 52 ), 1 ); //Add product to order
$order->set_address( $shipping_address, 'shipping' ); //Add shipping address
$order->set_address($user_info, 'billing'); //Add billing address

//Set payment gateways
$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method($payment_gateways['stripe']);

$order->calculate_totals(true); //setting true included tax 
//Try to charge stripe card
try {

  // Get stripe  test or secret key from woocommerce settings
  $options = get_option( 'woocommerce_stripe_settings' );
  $stripeKey = 'yes' === $options['testmode'] ? $options['test_secret_key'] : 
  $options['secret_key'] ;

  //Set the Stripe API Key
  \Stripe\Stripe::setApiKey($stripeKey);

  //Get Stripe customer token that was created when the card was saved in woo
  $tokenString = get_user_meta($user_id, '_stripe_customer_id', true);

  //Get total for the order as a number
  $total = intval($order->get_total());
  $totalNoDec = $total * 100;

  //Charge user via Stripe API
  $charge = \Stripe\Charge::create([
    'amount' => $totalNoDec,
    'currency' => 'usd',
    'customer' => $tokenString,
  ]);

  //Set all the meta data that will be needed
  $order->update_meta_data( '_transaction_id', $charge->id );
  $order->update_meta_data( '_stripe_source_id', $charge->payment_method );
  $order->update_meta_data( '_stripe_charge_captured', 'yes'  );
  $order->update_meta_data( '_stripe_currency', $charge->currancy);
  $order->update_meta_data( '_stripe_customer_id', $charge->customer);

} catch (\Stripe\Error\Base $e) {
  // Code to do something with the $e exception object when an error occurs
  echo($e->getMessage());
} catch (Exception $e) {
  echo($e->getMessage());
  // Catch any other non-Stripe exceptions
}

//Set order status to processing
$order->set_status("processing");
$order->save();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...