Files
code-bang/backend/application/api/controller/Order.php
T

309 lines
11 KiB
PHP
Raw Normal View History

2026-09-17 16:25:31 +08:00
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\service\OrderService;
use app\common\service\ToolService;
use think\Exception;
use think\exception\HttpResponseException;
use think\Log;
class Order extends Api
{
protected $noNeedLogin = ['payNotify', 'detail'];
protected $noNeedRight = ['*'];
/**
* 列表
*
* @ApiMethod (POST)
* @param string $desc 需求描述
* @param array $images 图片数组
* @param array $files 文件数组
* @param string $contact 联系方式
*/
public function list()
{
try {
$user_id = $this->auth->id ?? -1;
$params = $this->request->param('parameter/a', []);
$page = $params['pageNum'] ?? 1;
$page_size = $params['pageSize'] ?? 10;
$order_status = $params['orderStatus'] ?? null;
$order_type = $params['orderType'] ?? 0;
$keywords = $params['keywords'] ?? '';
$where = [
'user_id' => $user_id,
];
if ($keywords) {
$where['order_no'] = $keywords;
}
if ($order_type) {
$where['order_type'] = $order_type;
}
if (!is_null($order_status)) {
$where['order_status'] = $order_status;
}
$list = OrderService::getList($where, $page_size, 'id desc', '', ['orderGoods', 'orderPayment'], ['config' => ['page' => $page]]);
$pageList = $list->toArray();
$pageList['data'] = convert_keys_to_camelcase($pageList['data']);
foreach ($pageList['data'] as &$item) {
$item['status'] = $item['orderStatus'];
$item['statusName'] = OrderService::ORDER_STATUS_MAP[$item['orderStatus']] ?? '';
$item['buttonVOs'] = OrderService::getOrderButtons($item['orderStatus']);
$item['groupInfoVo'] = [];
$item['freightFee'] = 0;
}
$this->success('', $pageList);
} catch (\Exception $e) {
if ($e instanceof HttpResponseException) {
throw $e;
}
$this->error($e->getMessage());
}
}
public function count()
{
try {
$data = OrderService::getOrderCount($this->auth->id ?? 0);
$this->success('', $data);
} catch (\Exception $e) {
if ($e instanceof HttpResponseException) {
throw $e;
}
$this->error($e->getMessage());
}
}
public function detail()
{
try {
$orderNo = $this->request->get('order_no', 0);
$where = [
'order_no' => $orderNo
];
$info = OrderService::getOne($where, ['orderPayment', 'orderShip', 'orderGoods'=>function($query){
$query->with('goodsInfo');
}]);
if (!$info) {
throw new Exception('该订单不存在或已删除');
}
//格式转换
$info = convert_keys_to_camelcase($info->toArray());
$info['orderStatusName'] = $info['orderStatusText'];
$info['orderStatusRemark'] = '';
$info['storeName'] = '商品信息';
$info['invoiceStatus'] = 3;
$info['invoiceDesc'] = '';
$info['formatCreateTime'] = date('Y-m-d H:i', $info['createtime']);
$info['buttonVOs'] = []; // [['primary' => true, 'type' => 1, 'name' => '付款']],
$this->success('', $info);
} catch (\Exception $e) {
if ($e instanceof HttpResponseException) {
throw $e;
}
$this->error($e->getMessage());
}
}
public function settleDetail()
{
try {
$goodsRequestList = $this->request->post('goodsRequestList/a', []);
$storeInfoList = $this->request->post('storeInfoList/a', []);
$couponList = $this->request->post('couponList/a', []);
$totalSalePrice = 0;
$totalPayAmount = 0;
$totalGoodsCount = 0;
$storeGoodsList = [];
$goodsList = [];
foreach ($goodsRequestList as $goods) {
$totalGoodsCount += $goods['quantity'];
$totalSalePrice += $goods['quantity'] * $goods['price'];
$goodsList[] = [
'storeId' => $goods['storeId'], // 假设这是从其他地方获取的数据
'spuId' => $goods['spuId'],
'skuId' => 0,
'goodsName' => $goods['goodsName'],
'image' => $goods['primaryImage'],
'quantity' => $goods['quantity'],
'price' => $goods['price'],
'settlePrice' => $goods['price'],
'originPrice' => $goods['price'],
'specInfo' => [
],
'roomId' => ''
];
$storeGoodsList[] = [
'storeId' => $goods['storeId'],
'storeName' => '',
'remark' => null,
'goodsCount' => $goods['quantity'],
'deliveryFee' => '0',
'deliveryWords' => null,
'storeTotalAmount' => $totalSalePrice,
'storeTotalPayAmount' => $totalSalePrice,
'storeTotalDiscountAmount' => '0',
'storeTotalCouponAmount' => '0',
'skuDetailVos' => $goodsList,
'couponList' => [
],
];
}
$resp = [
'settleType' => 1, // 0不可结算 1可结算
'userAddress' => null,
'totalGoodsCount' => $totalGoodsCount,
'packageCount' => 1,
'totalAmount' => $totalSalePrice,
'totalPayAmount' => $totalSalePrice,
'totalDiscountAmount' => 0,
'totalPromotionAmount' => 0,
'totalCouponAmount' => '0',
'totalSalePrice' => $totalSalePrice,
'totalGoodsAmount' => $totalSalePrice,
'totalDeliveryFee' => '0',
'invoiceRequest' => null,
'skuImages' => null,
'deliveryFeeList' => null,
'storeGoodsList' => $storeGoodsList,
'inValidGoodsList' => null,
'outOfStockGoodsList' => null,
'limitGoodsList' => null,
'abnormalDeliveryGoodsList' => null,
'invoiceSupport' => 1,
2026-10-14 16:26:41 +08:00
// 订单类型:未传 orderNo 为新建软件订单;带 orderNo 为已有订单(需求首付款/尾款或软件订单重新支付)
'orderType' => OrderService::ORDER_TYPE_SOFTWARE,
2026-09-17 16:25:31 +08:00
];
2026-10-14 16:26:41 +08:00
$orderNo = $this->request->post('orderNo', '');
if ($orderNo) {
$order = OrderService::getOne(['order_no' => $orderNo, 'user_id' => $this->auth->id]);
if (!$order) {
$this->error('订单不存在');
}
$resp['orderType'] = (int)$order->order_type;
}
2026-09-17 16:25:31 +08:00
$this->success('', $resp);
} catch (\Exception $e) {
if ($e instanceof HttpResponseException) {
throw $e;
}
$this->error($e->getMessage());
}
}
public function commitPay()
{
try {
$param = $this->request->param();
$param['userInfo'] = $this->auth->getUserinfo();
$res = !empty($param['orderNo']) ? OrderService::orderPay($param) : OrderService::createOrder($param);
$this->success('', $res);
} catch (\Exception $e) {
if ($e instanceof HttpResponseException) {
throw $e;
}
$this->error($e->getMessage());
}
}
/**
* 订单取消
* @return void
*/
public function cancelOrder()
{
try {
$orderId = $this->request->param('order_id', 0);
$userId = $this->auth->id ?? 0;
$res = OrderService::cancelOrder($orderId, $userId);
$this->success('', $res);
} catch (\Exception $e) {
if ($e instanceof HttpResponseException) {
throw $e;
}
$this->error($e->getMessage());
}
}
/**
* @param
*/
public function orderOperate()
{
try {
$param = $this->request->param();
$userId = $this->auth->id ?? 0;
$res = OrderService::orderOperate($param, $userId);
$this->success('', $res);
} catch (\Exception $e) {
if ($e instanceof HttpResponseException) {
throw $e;
}
$this->error($e->getMessage());
}
}
/**
2026-09-21 14:57:50 +08:00
* 支付回调(微信支付 v3: 返回 JSON,失败时微信将按频率重试)
2026-09-17 16:25:31 +08:00
* @return void
* @throws \Exception
*/
public function payNotify()
{
2026-09-21 14:57:50 +08:00
header('Content-Type: application/json; charset=utf-8');
2026-09-23 14:46:56 +08:00
// 原始报文(用于排查微信是否真的回调到本地址)
$rawBody = file_get_contents('php://input');
$notifyHeaders = [];
foreach ($_SERVER as $key => $value) {
if (stripos($key, 'HTTP_WECHATPAY') !== false || in_array($key, ['CONTENT_TYPE', 'REQUEST_METHOD'])) {
$notifyHeaders[$key] = $value;
}
}
Log::info('微信支付回调[进入] uri=' . ($_SERVER['REQUEST_URI'] ?? '') . ' ' . json_encode([
'headers' => $notifyHeaders,
'body' => is_string($rawBody) ? $rawBody : '',
], JSON_UNESCAPED_UNICODE));
2026-09-17 16:25:31 +08:00
try {
2026-09-21 14:57:50 +08:00
// PSR-7 响应(SDK 已完成验签/解密,业务失败返回 500 由微信重试)
$response = OrderService::payNotify();
http_response_code($response->getStatusCode());
foreach ($response->getHeaders() as $name => $values) {
header($name . ': ' . implode(', ', $values));
}
2026-09-23 14:46:56 +08:00
$body = $response->getBody()->getContents();
Log::info('微信支付回调[应答] http_code=' . $response->getStatusCode() . ' body=' . $body);
echo $body;
2026-09-17 16:25:31 +08:00
exit;
2026-09-23 14:46:56 +08:00
} catch (\Throwable $e) {
// 注意:EasyWeChat 的 serve() 只捕获 Exception,TypeError/Error 会冒泡到这里
Log::error('微信回调信息_result_error:' . json_encode([
'msg' => $e->getMessage(),
'file' => $e->getFile() . ':' . $e->getLine(),
], JSON_UNESCAPED_UNICODE));
2026-09-21 14:57:50 +08:00
http_response_code(500);
echo json_encode(['code' => 'FAIL', 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
2026-09-17 16:25:31 +08:00
exit;
}
}
public function businessTime()
{
$res = [
'businessTime' => ['周一,周二,周三,周四,周五:00:20:00-08:00:00'],
'telphone' => '18565372257',
'saasId' => '88888',
];
$this->success('Success', $res);
}
}