文件
mashangyoujiu/Application/SmallProgramApi/Controller/WxStoreOrderController.class.php

121 行
3.6 KiB
PHP

<?php
namespace SmallProgramApi\Controller;
use Think\Controller;
header('Content-Type: text/html; charset=utf-8');
class WxStoreOrderController extends Controller
{
private $merchant_id = 1;
// 微信小商店接口基础URL
const WX_API_BASE = 'https://api.weixin.qq.com/';
/**
* 定时任务入口 - 每天凌晨1点执行
*/
public function autoDeliveryOrder()
{
try {
// 获取订单列表
$orders = $this->getOrderList();
if (empty($orders)) {
return;
}
// 处理待发货订单
foreach ($orders as $order) {
$this->sendDelivery($order);
}
} catch (\Exception $e) {
var_dump($e->getMessage());
\Think\Log::write("自动发货任务异常:" . $e->getMessage(), 'ERROR');
}
}
/**
* 获取订单列表
*/
private function getOrderList()
{
$url = self::WX_API_BASE . "wxa/sec/order/get_order_list?access_token=" . get_authorizer_access_tokens($this->merchant_id);
$params = [
'order_state' => 1, // 待发货
];
$response = $this->curl_post($url, $params);
$result = json_decode($response, true);
if ($result['errcode'] == 0) {
return $result['order_list'];
}
\Think\Log::write("获取订单列表失败:" . $response, 'ERROR');
return [];
}
/**
* 发货处理
*/
private function sendDelivery($order)
{
$url = self::WX_API_BASE . "wxa/sec/order/upload_shipping_info?access_token=" . get_authorizer_access_tokens($this->merchant_id);
$params = [
'order_key' => [
'order_number_type' => 2,
'transaction_id' => $order['transaction_id'],
],
'logistics_type' => 2,
'delivery_mode' => 1,
'shipping_list' => [
[ 'item_desc' => empty($order['description']) ? '同城配送' : $order['description'] ]
],
'upload_time' => str_replace(' ', 'T', date('Y-m-d H:i:s.120+08:00')),
'payer' => [
'openid' => $order['openid']
]
];
$response = $this->curl_post($url, $params);
$result = json_decode($response, true);
if ($result['errcode'] != 0) {
\Think\Log::write("订单{$order['transaction_id']}发货失败:" . $response, 'ERROR');
}
}
/**
* POST请求方法
*/
private function curl_post($url, $params = array())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($params, JSON_UNESCAPED_UNICODE))
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
\Think\Log::write("HTTP请求失败,状态码: {$httpCode}, 响应: {$response}", 'ERROR');
}
return $response;
}
}