如果希望通过编程创建订单,需要用到的代码如下:
|
<?php
function generate_order() {
global $woocommerce;
// 用于存储订单中的用户信息
$address = array(
‘first_name’ => ‘111Joe’,
‘last_name’ => ‘Conlin’,
‘company’ => ‘Speed Society’,
’email’ => ‘joe@testing.com’,
‘phone’ => ‘760-555-1212’,
‘address_1’ => ‘123 Main st.’,
‘address_2’ => ‘104’,
‘city’ => ‘San Diego’,
‘state’ => ‘Ca’,
‘postcode’ => ‘92121’,
‘country’ => ‘US’
);
$order = wc_create_order();
$order->add_product( get_product(‘10235’), 1 ); // ‘10235’ 是产品 id,1 是产品数量
$order->set_address($address, ‘billing’); // 设置订单地址
$order->calculate_totals();
update_post_meta( $order->id, ‘_payment_method’, ‘codetutor-alipay-for-wc’ ); // ‘codetutor-alipay-for-wc’ 是 payment_method
update_post_meta( $order->id, ‘_payment_method_title’, ‘ 支付宝’ ); // ‘ 支付宝’ 是 payment_method_title
// Store Order ID in session so it can be re-used after payment failure
WC()->session->order_awaiting_payment = $order->id;
// Process Payment
$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
$result = $available_gateways[ ‘codetutor-alipay-for-wc’ ]->process_payment( $order->id );
// Redirect to success/confirmation/payment page
if ( $result[‘result’] == ‘success’ ) {
$result = apply_filters( ‘woocommerce_payment_successful_result’, $result, $order->id );
wp_redirect( $result[‘redirect’] );
exit;
}
}
generate_order();
?>
|
运行上面的代码,会创建一个新的订单,并且重定向到支付宝网关(这个支付宝网关是通过插件 Codetutor Alipay for WooCommerce 实现的)。在支付完成之后会跳转到 thank you 页面。
然后在 WP 后台的 WooCommerce-> 订单中进行查看,可以看到这个新创建的订单。
原文来自:victoriawy.com 感谢作者提供又一个支付宝解决方案。