如何在woocommerce 訂單完成後進行 api 呼叫?以速買配電子發票為例

我將提供你一個可以使用 openpos 來觸發電子發票生成的功能。每次pos結帳完成後,會自動把訂單變更為完成,因此我們只要等訂單變更為完成狀態時,就會觸發對API cURL 的呼叫 https://ssl.smse.com.tw/api_test/SPEinvoice_Storage.asp,並將資料傳送給速買配並獲得電子發票。

以下為php語法可以供各位先進後輩參考。


function call_api_after_order_completion( $order_id ) {


// 定義訂單來源
$order = wc_get_order( $order_id );

// 取得訂單資料
$order_total = $order->get_total();
$order_date = $order->get_date_created();
$order_items = $order->get_items();
$product_names = array();
$quantities = array();
$unit_prices = array();
$units = array();
$amounts = array();

// 整理產品資料
foreach ( $order_items as $item ) {
$product_names[] = $item->get_name();
$quantities[] = $item->get_quantity();
$unit_prices[] = $item->get_total() / $item->get_quantity();
$units[] = '件'; // Modify this as per your requirement
$amounts[] = $item->get_total();
}

// 串接api
$params = array(
'Grvc' => 'SEI1000034',
'Verify_key' => '9D73935693EE0237FABA6AB744E48661',
'CompanyName'=> $order->get_order_number(),
'Phone' => $order->get_billing_phone(),
'Email' => $order->get_billing_email(),
'Intype' => '07', // Modify this as per your requirement
'TaxType' => '1', // Modify this as per your requirement
'LoveKey' => '', // Modify this as per your requirement
'DonateMark' => '0', // Modify this as per your requirement
'Description' => implode( '|', $product_names ),
'Quantity' => implode( '|', $quantities ),
'UnitPrice' => implode( '|', $unit_prices ),
'Unit' => implode( '|', $units ),
'Amount' => implode( '|', $amounts ),
'ALLAmount' => $order_total,
'InvoiceDate' => $order_date->format( 'Y/m/d' ),
'InvoiceTime' => $order_date->format( 'H:i:s' ),
'Buyer_id'=> $order->get_billing_address_2(),
'orderid'=> $order->get_order_number(),
'data_id'=> $order->get_order_number(),
'Certificate_Remark'=> $order->get_order_number(),
);

// 依據上面的元素建立 API URL 
$url = 'https://ssl.smse.com.tw/api_test/SPEinvoice_Storage.asp?' . http_build_query( $params );

// 呼叫 API cURL
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec( $ch );
curl_close( $ch );

// Log API 回應
error_log( 'API response: ' . print_r( $result, true ) );
}

add_action( 'woocommerce_order_status_completed', 'call_api_after_order_completion', 10, 1 );