如何从WooCommerce订单项生成产品ID与数量数组对接外部API
WooCommerce订单同步到外部API完整实现
以下是补全后的完整代码,完全匹配你需要的API数据格式:
add_action( 'woocommerce_new_order', 'send_order_to_api', 10, 2 ); function send_order_to_api( $order_id, $order ){ // 1. 获取订单联系电话 $customer_phone = $order->get_billing_phone(); // 如果需要统一格式(比如带国际区号),可以在这里处理,示例: // $customer_phone = '+86' . $customer_phone; // 2. 初始化商品数组 $products_data = []; // 3. 遍历订单商品,组装商品数据 $order_items = $order->get_items(); foreach( $order_items as $item ) { // 获取商品ID和购买数量 $product_id = $item->get_product_id(); $product_count = $item->get_quantity(); // 将单条商品数据加入数组 $products_data[] = [ 'product_id' => $product_id, 'count' => $product_count ]; } // 4. 组装API要求的完整数据结构 $incoming_order = [ 'spot_id' => 1, // 这里的spot_id如果是固定值就写死,动态的话可以从订单或设置中获取 'phone' => $customer_phone, 'products' => $products_data, ]; // 5. 发送请求到外部API $api_url = 'https://your-external-api-url.com/endpoint'; // 替换为实际API地址 $response = wp_remote_post( $api_url, [ 'headers' => [ 'Content-Type' => 'application/json', // 多数API要求JSON格式 ], 'body' => json_encode( $incoming_order ), 'timeout' => 15, // 设置超时时间 ] ); // 6. 可选:处理API响应,排查问题用 if ( is_wp_error( $response ) ) { // 请求失败,记录错误日志 error_log( 'API请求失败: ' . $response->get_error_message() ); } else { $response_code = wp_remote_retrieve_response_code( $response ); $response_body = wp_remote_retrieve_body( $response ); // 可以根据响应码判断是否成功,比如200为成功 if ( $response_code !== 200 ) { error_log( 'API返回错误,状态码: ' . $response_code . ', 响应内容: ' . $response_body ); } } }
关键说明:
- 电话格式处理:如果API要求固定带国际区号,可在获取
$customer_phone后手动拼接,比如国内订单加+86 - spot_id动态化:如果这个值不是固定的1,可从订单自定义字段、店铺设置或用户信息中获取,比如
$order->get_meta('spot_id')(假设订单有这个自定义字段) - 错误日志:代码中加入了错误日志记录,方便你在WP后台的
工具->站点健康->日志中排查请求问题 - API认证:如果API需要密钥或认证,可在
headers中添加,比如'Authorization' => 'Bearer your-api-token'
内容的提问来源于stack exchange,提问作者Shtarley
相关产品推荐
相关产品推荐

