447 lines
16 KiB
PHP
447 lines
16 KiB
PHP
<?php
|
||
|
||
namespace app\api\controller;
|
||
|
||
use app\common\controller\Api;
|
||
use app\common\service\OrderService;
|
||
use app\common\service\ToolService;
|
||
use app\common\service\VirtualPayService;
|
||
use think\Exception;
|
||
use think\exception\HttpResponseException;
|
||
use think\Log;
|
||
|
||
class Order extends Api
|
||
{
|
||
protected $noNeedLogin = ['payNotify', 'virtualPayNotify', '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,
|
||
// 订单类型:未传 orderNo 为新建软件订单;带 orderNo 为已有订单(需求首付款/尾款或软件订单重新支付)
|
||
'orderType' => OrderService::ORDER_TYPE_SOFTWARE,
|
||
];
|
||
$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;
|
||
}
|
||
$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());
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 支付回调(微信支付 v3: 返回 JSON,失败时微信将按频率重试)
|
||
* @return void
|
||
* @throws \Exception
|
||
*/
|
||
public function payNotify()
|
||
{
|
||
header('Content-Type: application/json; charset=utf-8');
|
||
// 原始报文(用于排查微信是否真的回调到本地址)
|
||
$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));
|
||
|
||
try {
|
||
// PSR-7 响应(SDK 已完成验签/解密,业务失败返回 500 由微信重试)
|
||
$response = OrderService::payNotify();
|
||
http_response_code($response->getStatusCode());
|
||
foreach ($response->getHeaders() as $name => $values) {
|
||
header($name . ': ' . implode(', ', $values));
|
||
}
|
||
$body = $response->getBody()->getContents();
|
||
Log::info('微信支付回调[应答] http_code=' . $response->getStatusCode() . ' body=' . $body);
|
||
echo $body;
|
||
exit;
|
||
} 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));
|
||
http_response_code(500);
|
||
echo json_encode(['code' => 'FAIL', 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 虚拟支付收银台成功后确认入账
|
||
* @ApiMethod (POST)
|
||
*/
|
||
public function virtualPayConfirm()
|
||
{
|
||
try {
|
||
$orderNo = $this->request->post('orderNo', '');
|
||
if (!$orderNo) {
|
||
$this->error('订单号不能为空');
|
||
}
|
||
$res = OrderService::confirmVirtualPay($orderNo, $this->auth->id);
|
||
$this->success('支付成功', $res);
|
||
} catch (\Exception $e) {
|
||
if ($e instanceof HttpResponseException) {
|
||
throw $e;
|
||
}
|
||
$this->error($e->getMessage());
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 虚拟支付消息推送。MP 后台消息推送 URL 填本接口,明文模式即可
|
||
*/
|
||
public function virtualPayNotify()
|
||
{
|
||
$echostr = (string)$this->request->get('echostr', '');
|
||
if ($echostr !== '') {
|
||
try {
|
||
$this->assertVirtualPaySignature();
|
||
} catch (\Exception $e) {
|
||
Log::error('虚拟支付消息验签失败 ' . $e->getMessage());
|
||
http_response_code(403);
|
||
exit;
|
||
}
|
||
echo $echostr;
|
||
exit;
|
||
}
|
||
|
||
$raw = trim((string)$this->request->getInput());
|
||
$asJson = strpos($raw, '{') === 0;
|
||
Log::info('虚拟支付推送[进入] ' . $raw);
|
||
try {
|
||
$payload = $this->parseVirtualPayBody($raw);
|
||
if (!empty($payload['Encrypt'])) {
|
||
$plain = VirtualPayService::decryptMessage(
|
||
(string)$payload['Encrypt'],
|
||
(string)$this->request->get('msg_signature', ''),
|
||
(string)$this->request->get('nonce', ''),
|
||
(string)$this->request->get('timestamp', '')
|
||
);
|
||
$payload = $this->parseVirtualPayBody($plain);
|
||
} else {
|
||
$this->assertVirtualPaySignature();
|
||
}
|
||
$reply = VirtualPayService::handleMessage($payload);
|
||
} catch (\Exception $e) {
|
||
Log::error('虚拟支付推送处理失败 ' . $e->getMessage());
|
||
$message = $e->getMessage();
|
||
if (strpos($message, '订单不存在') !== false || strpos($message, '获取订单数据失败') !== false) {
|
||
$reply = ['ErrCode' => 0, 'ErrMsg' => 'success'];
|
||
} else {
|
||
$reply = ['ErrCode' => 1, 'ErrMsg' => $message];
|
||
}
|
||
}
|
||
$this->replyVirtualPay(isset($reply) ? $reply : ['ErrCode' => 1, 'ErrMsg' => 'fail'], $asJson);
|
||
}
|
||
|
||
/**
|
||
* 校验消息推送签名
|
||
* @throws \Exception
|
||
*/
|
||
private function assertVirtualPaySignature()
|
||
{
|
||
$token = (string)config('common.virtual_pay.msg_token');
|
||
if ($token === '') {
|
||
throw new \Exception('未配置虚拟支付消息令牌');
|
||
}
|
||
$parts = [
|
||
$token,
|
||
(string)$this->request->get('timestamp', ''),
|
||
(string)$this->request->get('nonce', ''),
|
||
];
|
||
sort($parts, SORT_STRING);
|
||
if (sha1(implode($parts)) !== (string)$this->request->get('signature', '')) {
|
||
throw new \Exception('消息签名校验失败');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @param string $raw
|
||
* @return array
|
||
*/
|
||
private function parseVirtualPayBody($raw)
|
||
{
|
||
$raw = trim((string)$raw);
|
||
if ($raw === '') {
|
||
return [];
|
||
}
|
||
if ($raw[0] === '{') {
|
||
$data = json_decode($raw, true);
|
||
return is_array($data) ? $data : [];
|
||
}
|
||
$xml = simplexml_load_string($raw, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NONET);
|
||
if (!$xml) {
|
||
return [];
|
||
}
|
||
$data = json_decode(json_encode($xml), true);
|
||
|
||
return is_array($data) ? $data : [];
|
||
}
|
||
|
||
/**
|
||
* @param array $data
|
||
* @param bool $asJson
|
||
*/
|
||
private function replyVirtualPay(array $data, $asJson)
|
||
{
|
||
if ($asJson) {
|
||
header('Content-Type: application/json; charset=utf-8');
|
||
echo json_encode($data, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
header('Content-Type: text/xml; charset=utf-8');
|
||
$xml = '<xml>';
|
||
foreach ($data as $key => $value) {
|
||
if (is_int($value) || is_float($value)) {
|
||
$xml .= '<' . $key . '>' . $value . '</' . $key . '>';
|
||
} else {
|
||
$xml .= '<' . $key . '><![CDATA[' . $value . ']]></' . $key . '>';
|
||
}
|
||
}
|
||
$xml .= '</xml>';
|
||
echo $xml;
|
||
exit;
|
||
}
|
||
|
||
public function businessTime()
|
||
{
|
||
$res = [
|
||
'businessTime' => ['周一,周二,周三,周四,周五:00:20:00-08:00:00'],
|
||
'telphone' => '18565372257',
|
||
'saasId' => '88888',
|
||
];
|
||
$this->success('Success', $res);
|
||
}
|
||
|
||
}
|