Initial commit: 小众厨房项目代码

Co-authored-by: Cursor <cursoragent@cursor.com>
这个提交包含在:
可乐加冰
2026-09-23 17:04:10 +08:00
当前提交 f7d3d7d1bd
共有 1761 个文件被更改,包括 453668 次插入 和 0 次删除

查看文件

@@ -0,0 +1,86 @@
<?php
namespace addons\shopro\job;
use addons\shopro\library\traits\ActivityCache;
use addons\shopro\library\traits\Groupon;
use addons\shopro\library\traits\StockSale;
use addons\shopro\model\Config;
use addons\shopro\model\GoodsComment;
use addons\shopro\model\Order;
use addons\shopro\model\OrderAction;
use addons\shopro\model\OrderItem;
use think\queue\Job;
/**
* 订单支付完成
*/
class OrderPayed extends BaseJob
{
use StockSale, ActivityCache, Groupon;
/**
* 订单支付完成
*/
public function payed(Job $job, $data)
{
try {
$order = $data['order'];
$user = $data['user'];
$order = Order::with('item')->where('id', $order['id'])->find();
// 数据库删订单的问题常见,这里被删的订单直接把队列移除
if ($order) {
\think\Db::transaction(function () use ($order, $user, $data) {
// 订单减库存
$this->realForwardStockSale($order);
// 判断,如果是拼团 真实加入团
if (strpos($order['activity_type'], 'groupon') !== false) {
$this->joinGroupon($order, $user);
}
// 处理发票审核
if ($order->invoice_status == 1) {
$invoice = \addons\shopro\model\OrderInvoice::get(['order_id' => $order->id]);
if ($invoice) {
$invoice->status = 0;
$invoice->save();
}
}
// 处理消费返积分 TODO: 待测试
$scoreConfig = Config::where('name', 'score')->find();
$scoreConfig = json_decode($scoreConfig['value'], true);
if (!empty($scoreConfig['consume_get_score']) && !empty($scoreConfig['consume_get_score_ratio'])) {
$scoreRatio = intval($scoreConfig['consume_get_score_ratio']);
$score = intval($scoreRatio * 0.01 * $order->total_fee);
if ($score > 0) {
\addons\shopro\model\User::score($score, $user['id'], 'consume_get_score', $order['id']);
}
}
// 触发订单支付完成事件, 如果这个订单刚好完成拼团,并且是自动发货订单,则这个订单的自动发货事件会比订单支付之后事件早
$data = ['order' => $order];
\think\Hook::listen('order_payed_after', $data);
// 检测有没有自动发货的商品,有就自动发货
$order->checkDispatchAndSend($order, ['user' => $user]);
});
}
// 删除 job
$job->delete();
} catch (\Exception $e) {
// 队列执行失败
$error = json_encode([
'a' => $e->getLine(),
'b' => $e->getFile(),
'c' => $e->getTrace(),
'd' => $e->getMessage()
], JSON_UNESCAPED_UNICODE);
\think\Log::error('queue-' . get_class() . '-payed' . ':执行失败,错误信息:' . $error);
}
}
}

查看文件

@@ -0,0 +1,136 @@
<?php
namespace addons\shopro\listener\order;
use addons\shopro\exception\Exception;
use addons\shopro\model\Cart;
use addons\shopro\model\Config;
use addons\shopro\model\Order;
use addons\shopro\model\Store;
use addons\shopro\model\User;
use app\common\library\PrinterService;
/**
* 支付成功事件监听
*/
class Payed
{
// 订单支付成功事件
public function orderPayedAfter(&$params) {
// 订单对象
$order = $params["order"];
// 重新查询带明细项的完整订单
$order = Order::with("item")->where("id", $order["id"])->find();
$items = $order ? $order["item"] : [];
// 1. 自动触发芯烨云小票打印
$this->autoPrintOrder($order, $items);
// 2. 门店管理员通知
$storeIds = [];
foreach ($items as $item) {
if (in_array($item["dispatch_type"], ["store", "selfetch"]) && $item["store_id"]) {
$storeIds[] = $item["store_id"];
}
}
$data = [];
if ($storeIds) {
$data = [];
// 存在门店,查询门店管理员
$stores = Store::with(["userStore.user"])->where("id", "in", $storeIds)->select();
foreach ($stores as $key => $store) {
$userStoreList = $store["user_store"] ? : [];
unset($store["user_store"]);
// 当前门店所有用户管理员
$userList = [];
foreach ($userStoreList as $user) {
if ($user["user"]) {
$userList[] = $user["user"];
}
}
// 有用户才能发送消息
if ($userList) {
$data[] = [
"store" => $store,
"userList" => $userList
];
}
}
}
// 存在要通知的门店管理员
if ($data) {
// 按门店为单位发送通知
foreach ($data as $key => $sendData) {
\addons\shopro\library\notify\Notify::send(
$sendData["userList"],
new \addons\shopro\notifications\store\Order([
"store" => $sendData["store"],
"order" => $order,
"event" => "store_order_new"
])
);
}
}
}
/**
* 自动小票打印逻辑
*/
protected function autoPrintOrder($order, $items)
{
if (!$order) {
return;
}
try {
$printer = new PrinterService();
$orderItems = [];
if (!empty($items)) {
foreach ($items as $it) {
$title = isset($it["goods_title"]) ? $it["goods_title"] : (isset($it["title"]) ? $it["title"] : "商品");
$sku = !empty($it["goods_sku_text"]) ? " (" . $it["goods_sku_text"] . ")" : "";
$num = isset($it["goods_num"]) ? $it["goods_num"] : 1;
$price = isset($it["goods_price"]) ? $it["goods_price"] : "0.00";
$orderItems[] = [
"name" => $title . $sku,
"num" => $num,
"price" => $price
];
}
}
$addressStr = "";
if (isset($order["province_name"])) {
$addressStr .= $order["province_name"] . $order["city_name"] . $order["area_name"];
}
if (isset($order["address"])) {
$addressStr .= $order["address"];
}
$orderData = [
"shop_name" => "小众厨房设备商城",
"order_sn" => isset($order["order_sn"]) ? $order["order_sn"] : "",
"createtime" => isset($order["createtime"]) ? $order["createtime"] : time(),
"consignee" => isset($order["consignee"]) ? $order["consignee"] : "客户",
"phone" => isset($order["phone"]) ? $order["phone"] : "",
"address" => $addressStr ? $addressStr : "到店自提/商家配送",
"total_fee" => isset($order["pay_fee"]) ? sprintf("%.2f", $order["pay_fee"]) : (isset($order["total_fee"]) ? $order["total_fee"] : "0.00"),
"items" => $orderItems
];
// 调用芯烨云打单
$printer->printOrder($orderData, 1);
} catch (\Exception $e) {
\think\Log::record("自动打印小票失败: " . $e->getMessage(), "error");
}
}
}

查看文件

@@ -0,0 +1,142 @@
<?php
namespace app\common\library;
/**
* 芯烨云 (Xprinter / xingye) 小票打印机服务类
*/
class PrinterService
{
protected $user;
protected $ukey;
protected $sn;
protected $url = "https://open.xprinter.com/Api/Open/";
public function __construct()
{
$config = [];
if (function_exists("config")) {
$config = config("printer");
}
if (empty($config)) {
$configFile = __DIR__ . "/../../extra/printer.php";
if (file_exists($configFile)) {
$config = include $configFile;
}
}
$this->user = isset($config["client_id"]) ? trim($config["client_id"]) : "";
$this->ukey = isset($config["client_secret"]) ? trim($config["client_secret"]) : "";
$this->sn = isset($config["sn"]) ? trim($config["sn"]) : "";
}
/**
* 查询芯烨云打印机状态
*/
public function queryStatus()
{
$stime = time();
$sig = sha1($this->user . $this->ukey . $stime);
$params = [
"user" => $this->user,
"stime" => $stime,
"sig" => $sig,
"apiname" => "Open_queryPrinterStatus",
"sn" => $this->sn
];
return $this->sendRequest($params);
}
/**
* 打印订单小票
*/
public function printOrder($orderData = [], $times = 1)
{
$stime = time();
$sig = sha1($this->user . $this->ukey . $stime);
$content = $this->buildReceiptContent($orderData);
$params = [
"user" => $this->user,
"stime" => $stime,
"sig" => $sig,
"apiname" => "Open_printMsg",
"sn" => $this->sn,
"content" => $content,
"times" => $times
];
return $this->sendRequest($params);
}
/**
* 拼接排版小票格式
*/
public function buildReceiptContent($order = [])
{
$title = isset($order["shop_name"]) ? $order["shop_name"] : "小众厨房设备商城";
$orderSn = isset($order["order_sn"]) ? $order["order_sn"] : "TEST" . date("YmdHis");
$createTime = isset($order["createtime"]) ? date("Y-m-d H:i:s", $order["createtime"]) : date("Y-m-d H:i:s");
$consignee = isset($order["consignee"]) ? $order["consignee"] : "测试用户";
$phone = isset($order["phone"]) ? $order["phone"] : "138****8888";
$address = isset($order["address"]) ? $order["address"] : "贵州省修文县城内";
$totalAmount = isset($order["total_fee"]) ? $order["total_fee"] : "0.01";
$info = "<CB>{$title}</CB><BR>";
$info .= "<CB>-- 订单小票 --</CB><BR>";
$info .= "--------------------------------<BR>";
$info .= "订单编号:" . $orderSn . "<BR>";
$info .= "下单时间:" . $createTime . "<BR>";
$info .= "--------------------------------<BR>";
$info .= "商品名称 数量 单价<BR>";
if (!empty($order["items"]) && is_array($order["items"])) {
foreach ($order["items"] as $item) {
$info .= $item["name"] . " " . $item["num"] . " ¥" . $item["price"] . "<BR>";
}
} else {
$info .= "测试商品-厨房专用设备 1 ¥" . $totalAmount . "<BR>";
}
$info .= "--------------------------------<BR>";
$info .= "合计金额:¥" . $totalAmount . " 元<BR>";
$info .= "客户姓名:" . $consignee . "<BR>";
$info .= "联系电话:" . $phone . "<BR>";
$info .= "送货地址:" . $address . "<BR>";
$info .= "--------------------------------<BR>";
$info .= "<CB>谢谢惠顾,欢迎再次光临!</CB><BR><BR>";
return $info;
}
/**
* 发送 cURL 请求给芯烨云 API 网关
*/
protected function sendRequest($data)
{
$cookieFile = "/tmp/xprinter_cookie.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Cookie: _gp_pc=1"]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
return json_encode(["ret" => -1, "msg" => "Curl Error: " . $error]);
}
return $result;
}
}

查看文件

@@ -0,0 +1,114 @@
<?php
namespace addons\shopro\listener\order;
use addons\shopro\exception\Exception;
use addons\shopro\model\Cart;
use addons\shopro\model\Config;
use addons\shopro\model\Order;
use addons\shopro\model\Store;
use addons\shopro\model\User;
/**
* 支付成功事件监听
*/
class Payed
{
// 订单支付成功事件
public function orderPayedAfter(&$params) {
// 订单对象
$order = $params["order"];
// 重新查询带明细项的完整订单
$order = Order::with("item")->where("id", $order["id"])->find();
$items = $order ? $order["item"] : [];
// 1. 订单提交后只创建唯一打印任务;实际云打印由独立队列执行。
$this->queuePrintOrder($order);
// 2. 门店管理员通知
$storeIds = [];
foreach ($items as $item) {
if (in_array($item["dispatch_type"], ["store", "selfetch"]) && $item["store_id"]) {
$storeIds[] = $item["store_id"];
}
}
$data = [];
if ($storeIds) {
$data = [];
// 存在门店,查询门店管理员
$stores = Store::with(["userStore.user"])->where("id", "in", $storeIds)->select();
foreach ($stores as $key => $store) {
$userStoreList = $store["user_store"] ? : [];
unset($store["user_store"]);
// 当前门店所有用户管理员
$userList = [];
foreach ($userStoreList as $user) {
if ($user["user"]) {
$userList[] = $user["user"];
}
}
// 有用户才能发送消息
if ($userList) {
$data[] = [
"store" => $store,
"userList" => $userList
];
}
}
}
// 存在要通知的门店管理员
if ($data) {
// 按门店为单位发送通知
foreach ($data as $key => $sendData) {
\addons\shopro\library\notify\Notify::send(
$sendData["userList"],
new \addons\shopro\notifications\store\Order([
"store" => $sendData["store"],
"order" => $order,
"event" => "store_order_new"
])
);
}
}
}
protected function queuePrintOrder($order)
{
if (!$order) {
return;
}
try {
$task = \think\Db::name('shopro_order_print_task')->where('order_id', $order['id'])->find();
if (!$task) {
try {
\think\Db::name('shopro_order_print_task')->insert([
'order_id' => $order['id'],
'order_sn' => $order['order_sn'],
'status' => 0,
'attempts' => 0,
'created_at' => time(),
'updated_at' => time(),
]);
$task = true;
} catch (\Exception $e) {
// 唯一索引冲突表示另一个事件已创建任务,禁止重复入队。
$task = \think\Db::name('shopro_order_print_task')->where('order_id', $order['id'])->find();
}
}
if ($task && (!is_array($task) || (int)$task['status'] !== 1)) {
\think\Queue::push('\\addons\\shopro\\job\\OrderPrint@handle', ['order_id' => $order['id']], 'shopro-high');
}
} catch (\Exception $e) {
\think\Log::record('创建小票打印任务失败,订单ID ' . $order['id'] . ': ' . $e->getMessage(), 'error');
}
}
}

查看文件

@@ -0,0 +1,159 @@
<?php
namespace app\common\library;
class PrinterService
{
protected $user;
protected $ukey;
protected $sn;
protected $url = 'https://open.xpyun.net/api/openapi/xprinter/';
public function __construct()
{
$config = function_exists('config') ? config('printer') : [];
if (empty($config)) {
$configFile = __DIR__ . '/../../extra/printer.php';
$config = file_exists($configFile) ? include $configFile : [];
}
$this->user = isset($config['client_id']) ? trim($config['client_id']) : '';
$this->ukey = isset($config['client_secret']) ? trim($config['client_secret']) : '';
$this->sn = isset($config['sn']) ? trim($config['sn']) : '';
}
public function queryStatus()
{
return $this->sendRequest('queryPrinterStatus', ['sn' => $this->sn]);
}
public function queryOrderState($cloudOrderId)
{
$result = $this->sendRequest('queryOrderState', ['orderId' => (string)$cloudOrderId]);
$result['printed'] = !empty($result['accepted']) && !empty($result['data']);
return $result;
}
public function printOrder($orderData = [], $copies = 1)
{
$content = $this->buildReceiptContent($orderData);
if ($this->gbkLength($content) > 12 * 1024) {
return $this->failure('打印内容超过芯烨云 12KB 限制');
}
$result = $this->sendRequest('print', [
'sn' => $this->sn,
'content' => $content,
'copies' => max(1, min(65535, (int)$copies)),
// 离线时由芯烨云暂存,避免本地重发造成重复小票。
'mode' => 1,
'expiresIn' => 3600,
'idempotent' => isset($orderData['print_idempotent']) ? $orderData['print_idempotent'] : '',
]);
if (!empty($result['accepted']) && !is_scalar($result['data'])) {
return $this->failure('芯烨云未返回打印订单号', $result['response']);
}
if (!empty($result['accepted'])) {
$result['cloud_order_id'] = (string)$result['data'];
}
return $result;
}
public function buildReceiptContent($order = [])
{
$title = $this->cleanText(isset($order['shop_name']) ? $order['shop_name'] : '小众厨房设备商城');
$orderSn = $this->cleanText(isset($order['order_sn']) ? $order['order_sn'] : 'TEST' . date('YmdHis'));
$createTime = isset($order['createtime']) ? date('Y-m-d H:i:s', $order['createtime']) : date('Y-m-d H:i:s');
$consignee = $this->cleanText(isset($order['consignee']) ? $order['consignee'] : '测试用户');
$phone = $this->cleanText(isset($order['phone']) ? $order['phone'] : '138****8888');
$address = $this->cleanText(isset($order['address']) ? $order['address'] : '贵州省修文县城内');
$totalAmount = $this->cleanText(isset($order['total_fee']) ? $order['total_fee'] : '0.01');
$info = '<CB>' . $title . '<BR></CB>';
$info .= '<CB>-- 订单小票 --<BR></CB>';
$info .= '--------------------------------<BR>';
$info .= '订单编号:' . $orderSn . '<BR>';
$info .= '下单时间:' . $createTime . '<BR>';
$info .= '--------------------------------<BR>';
$info .= '商品名称 数量 单价<BR>';
foreach (!empty($order['items']) && is_array($order['items']) ? $order['items'] : [] as $item) {
$info .= $this->cleanText(isset($item['name']) ? $item['name'] : '商品') . ' '
. $this->cleanText(isset($item['num']) ? $item['num'] : 1) . ' ¥'
. $this->cleanText(isset($item['price']) ? $item['price'] : '0.00') . '<BR>';
}
$info .= '--------------------------------<BR>';
$info .= '合计金额:¥' . $totalAmount . ' 元<BR>';
$info .= '客户姓名:' . $consignee . '<BR>';
$info .= '联系电话:' . $phone . '<BR>';
$info .= '送货地址:' . $address . '<BR>';
$info .= '--------------------------------<BR>';
return $info . '<CB>谢谢惠顾,欢迎再次光临!<BR><BR></CB>';
}
protected function sendRequest($endpoint, array $data)
{
if (!$this->user || !$this->ukey || !$this->sn) {
return $this->failure('打印机配置不完整');
}
$timestamp = (string)time();
$payload = array_merge($data, [
'user' => $this->user,
'timestamp' => $timestamp,
'sign' => sha1($this->user . $this->ukey . $timestamp),
]);
$json = json_encode($payload, JSON_UNESCAPED_UNICODE);
if ($json === false) {
return $this->failure('打印请求编码失败');
}
$ch = curl_init($this->url . $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json;charset=UTF-8', 'Accept: application/json']);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$body = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($error) {
return $this->failure('云打印请求失败: ' . $error, '', true);
}
$response = trim((string)$body);
$decoded = json_decode($response, true);
$accepted = $httpCode >= 200 && $httpCode < 300 && is_array($decoded)
&& isset($decoded['code']) && (int)$decoded['code'] === 0;
return [
'accepted' => $accepted,
'data' => is_array($decoded) && array_key_exists('data', $decoded) ? $decoded['data'] : null,
'response' => mb_substr($response, 0, 1000, 'UTF-8'),
'error' => $accepted ? '' : (is_array($decoded) && !empty($decoded['msg']) ? $decoded['msg'] : '云打印未受理,HTTP ' . $httpCode),
'uncertain' => false,
];
}
protected function failure($error, $response = '', $uncertain = false)
{
return ['accepted' => false, 'data' => null, 'response' => $response, 'error' => $error, 'uncertain' => $uncertain];
}
protected function gbkLength($content)
{
$encoded = function_exists('mb_convert_encoding')
? @mb_convert_encoding($content, 'GBK', 'UTF-8')
: @iconv('UTF-8', 'GBK//IGNORE', $content);
return $encoded === false ? strlen($content) : strlen($encoded);
}
protected function cleanText($value)
{
return preg_replace('/[\r\n\t]+/', ' ', strip_tags((string)$value));
}
}

查看文件

@@ -0,0 +1,85 @@
<?php
namespace addons\shopro\job;
use addons\shopro\library\traits\ActivityCache;
use addons\shopro\library\traits\Groupon;
use addons\shopro\library\traits\StockSale;
use addons\shopro\model\Config;
use addons\shopro\model\GoodsComment;
use addons\shopro\model\Order;
use addons\shopro\model\OrderAction;
use addons\shopro\model\OrderItem;
use think\queue\Job;
/**
* 订单支付完成
*/
class OrderPayed extends BaseJob
{
use StockSale, ActivityCache, Groupon;
/**
* 订单支付完成
*/
public function payed(Job $job, $data)
{
try {
$order = $data['order'];
$user = $data['user'];
$order = Order::with('item')->where('id', $order['id'])->find();
// 数据库删订单的问题常见,这里被删的订单直接把队列移除
if ($order) {
\think\Db::transaction(function () use ($order, $user, $data) {
// 订单减库存
$this->realForwardStockSale($order);
// 判断,如果是拼团 真实加入团
if (strpos($order['activity_type'], 'groupon') !== false) {
$this->joinGroupon($order, $user);
}
// 处理发票审核
if ($order->invoice_status == 1) {
$invoice = \addons\shopro\model\OrderInvoice::get(['order_id' => $order->id]);
if ($invoice) {
$invoice->status = 0;
$invoice->save();
}
}
// 处理消费返积分 TODO: 待测试
$scoreConfig = Config::where('name', 'score')->find();
$scoreConfig = json_decode($scoreConfig['value'], true);
if (!empty($scoreConfig['consume_get_score']) && !empty($scoreConfig['consume_get_score_ratio'])) {
$scoreRatio = intval($scoreConfig['consume_get_score_ratio']);
$score = intval($scoreRatio * 0.01 * $order->total_fee);
if ($score > 0) {
\addons\shopro\model\User::score($score, $user['id'], 'consume_get_score', $order['id']);
}
}
// 检测有没有自动发货的商品,有就自动发货
$order->checkDispatchAndSend($order, ['user' => $user]);
});
// 支付成功的外部副作用必须在事务提交后触发,避免数据库回滚时已经打印小票。
\think\Hook::listen('order_payed_after', ['order' => $order]);
}
// 删除 job
$job->delete();
} catch (\Exception $e) {
// 队列执行失败
$error = json_encode([
'a' => $e->getLine(),
'b' => $e->getFile(),
'c' => $e->getTrace(),
'd' => $e->getMessage()
], JSON_UNESCAPED_UNICODE);
\think\Log::error('queue-' . get_class() . '-payed' . ':执行失败,错误信息:' . $error);
}
}
}

查看文件

@@ -0,0 +1,99 @@
<?php
namespace addons\shopro\job;
use addons\shopro\model\Order;
use app\common\library\PrinterService;
use think\Db;
use think\queue\Job;
class OrderPrint extends BaseJob
{
public function handle(Job $job, $data)
{
$orderId = isset($data['order_id']) ? (int)$data['order_id'] : 0;
$task = $orderId ? Db::name('shopro_order_print_task')->where('order_id', $orderId)->find() : null;
if (!$task || in_array((int)$task['status'], [1, 3], true)) {
$job->delete();
return;
}
try {
$order = Order::with('item')->where('id', $orderId)->find();
if (!$order) {
throw new \RuntimeException('订单不存在');
}
Db::name('shopro_order_print_task')->where('id', $task['id'])->update([
'status' => 2,
'attempts' => (int)$task['attempts'] + 1,
'updated_at' => time(),
'last_error' => '',
]);
$result = (new PrinterService())->printOrder($this->buildOrderData($order));
if (empty($result['accepted'])) {
$this->failTask($task['id'], !empty($result['error']) ? $result['error'] : '云打印未受理', $result);
$job->delete();
return;
}
Db::name('shopro_order_print_task')->where('id', $task['id'])->update([
// 云端已接单,仍需查询 queryOrderState 确认物理打印完成。
'status' => 3,
'cloud_order_id' => $result['cloud_order_id'],
'printer_response' => $result['response'],
'updated_at' => time(),
'last_error' => '',
]);
\think\Queue::later(30, '\\addons\\shopro\\job\\OrderPrintStatus@handle', ['task_id' => $task['id']], 'shopro-high');
$job->delete();
} catch (\Exception $e) {
if ($task) {
$this->failTask($task['id'], $e->getMessage(), []);
}
\think\Log::error('订单小票打印失败,订单ID ' . $orderId . ': ' . $e->getMessage());
$job->delete();
}
}
protected function buildOrderData($order)
{
$items = [];
foreach ((array)$order['item'] as $item) {
$items[] = [
'name' => (isset($item['goods_title']) ? $item['goods_title'] : '商品') . (!empty($item['goods_sku_text']) ? ' (' . $item['goods_sku_text'] . ')' : ''),
'num' => isset($item['goods_num']) ? $item['goods_num'] : 1,
'price' => isset($item['goods_price']) ? $item['goods_price'] : '0.00',
];
}
$address = (isset($order['province_name']) ? $order['province_name'] : '')
. (isset($order['city_name']) ? $order['city_name'] : '')
. (isset($order['area_name']) ? $order['area_name'] : '')
. (isset($order['address']) ? $order['address'] : '');
return [
'shop_name' => '小众厨房设备商城',
'order_sn' => $order['order_sn'],
'createtime' => $order['createtime'],
'consignee' => isset($order['consignee']) ? $order['consignee'] : '客户',
'phone' => isset($order['phone']) ? $order['phone'] : '',
'address' => $address ?: '到店自提/商家配送',
'total_fee' => isset($order['pay_fee']) ? sprintf('%.2f', $order['pay_fee']) : $order['total_fee'],
'items' => $items,
'print_idempotent' => 'shopro-' . $order['id'],
];
}
protected function failTask($taskId, $error, $result)
{
Db::name('shopro_order_print_task')->where('id', $taskId)->update([
'status' => -1,
'printer_response' => isset($result['response']) ? $result['response'] : '',
'last_error' => mb_substr($error, 0, 500, 'UTF-8'),
'updated_at' => time(),
]);
}
}

查看文件

@@ -0,0 +1,45 @@
<?php
namespace addons\shopro\job;
use app\common\library\PrinterService;
use think\Db;
use think\queue\Job;
class OrderPrintStatus extends BaseJob
{
public function handle(Job $job, $data)
{
$taskId = isset($data['task_id']) ? (int)$data['task_id'] : 0;
$task = $taskId ? Db::name('shopro_order_print_task')->where('id', $taskId)->find() : null;
if (!$task || (int)$task['status'] !== 3 || empty($task['cloud_order_id'])) {
$job->delete();
return;
}
$result = (new PrinterService())->queryOrderState($task['cloud_order_id']);
$attempts = (int)$task['verify_attempts'] + 1;
$update = [
'verify_attempts' => $attempts,
'updated_at' => time(),
'printer_response' => $result['response'],
'last_error' => !empty($result['accepted']) ? '' : $result['error'],
];
if (!empty($result['printed'])) {
$update['status'] = 1;
$update['printed_at'] = time();
Db::name('shopro_order_print_task')->where('id', $taskId)->update($update);
$job->delete();
return;
}
Db::name('shopro_order_print_task')->where('id', $taskId)->update($update);
if ($attempts < 30) {
\think\Queue::later(60, '\\addons\\shopro\\job\\OrderPrintStatus@handle', ['task_id' => $taskId], 'shopro-high');
} else {
\think\Log::warning('订单小票云端状态未确认,任务ID ' . $taskId);
}
$job->delete();
}
}

查看文件

@@ -0,0 +1,49 @@
<?php
namespace app\admin\command;
use think\Db;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
class ShoproPrintRetry extends Command
{
protected function configure()
{
$this->setName('shopro:print-retry')
->addOption('order-id', null, Option::VALUE_REQUIRED, 'failed print task order id')
->addOption('all', null, Option::VALUE_NONE, 'retry all failed print tasks')
->setDescription('Requeue failed Shopro receipt print tasks');
}
protected function execute(Input $input, Output $output)
{
$orderId = (int)$input->getOption('order-id');
$all = (bool)$input->getOption('all');
if (!$orderId && !$all) {
$output->error('Use --order-id=<id> or --all.');
return 1;
}
$staleBefore = time() - 300;
$query = Db::name('shopro_order_print_task')
->whereRaw('(status = -1 OR (status = 2 AND updated_at < ' . $staleBefore . '))');
if ($orderId) {
$query->where('order_id', $orderId);
}
$tasks = $query->select();
foreach ($tasks as $task) {
Db::name('shopro_order_print_task')->where('id', $task['id'])->update([
'status' => 0,
'updated_at' => time(),
'last_error' => '',
]);
\think\Queue::push('\\addons\\shopro\\job\\OrderPrint@handle', ['order_id' => $task['order_id']], 'shopro-high');
}
$output->info('Requeued ' . count($tasks) . ' receipt print task(s).');
return 0;
}
}

查看文件

@@ -0,0 +1,21 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
return [
'app\admin\command\Crud',
'app\admin\command\Menu',
'app\admin\command\Install',
'app\admin\command\Min',
'app\admin\command\Addon',
'app\admin\command\Api',
'app\admin\command\ShoproPrintRetry',
];

查看文件

@@ -0,0 +1,20 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
return [
'app\admin\command\Crud',
'app\admin\command\Menu',
'app\admin\command\Install',
'app\admin\command\Min',
'app\admin\command\Addon',
'app\admin\command\Api',
];

查看文件

@@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS `fa_shopro_order_print_task` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`order_id` int(10) unsigned NOT NULL,
`order_sn` varchar(64) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0待处理,1成功,2处理中,-1失败',
`attempts` int(10) unsigned NOT NULL DEFAULT '0',
`printer_response` varchar(1000) NOT NULL DEFAULT '',
`last_error` varchar(500) NOT NULL DEFAULT '',
`created_at` int(10) unsigned NOT NULL,
`updated_at` int(10) unsigned NOT NULL,
`printed_at` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_order_id` (`order_id`),
KEY `idx_status_updated_at` (`status`,`updated_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单云打印任务';

查看文件

@@ -0,0 +1,96 @@
<?php
namespace addons\shopro\job;
use addons\shopro\model\Order;
use app\common\library\PrinterService;
use think\Db;
use think\queue\Job;
class OrderPrint extends BaseJob
{
public function handle(Job $job, $data)
{
$orderId = isset($data['order_id']) ? (int)$data['order_id'] : 0;
$task = $orderId ? Db::name('shopro_order_print_task')->where('order_id', $orderId)->find() : null;
if (!$task || (int)$task['status'] === 1) {
$job->delete();
return;
}
try {
$order = Order::with('item')->where('id', $orderId)->find();
if (!$order) {
throw new \RuntimeException('订单不存在');
}
Db::name('shopro_order_print_task')->where('id', $task['id'])->update([
'status' => 2,
'attempts' => (int)$task['attempts'] + 1,
'updated_at' => time(),
'last_error' => '',
]);
$result = (new PrinterService())->printOrder($this->buildOrderData($order));
if (empty($result['accepted'])) {
$this->failTask($task['id'], !empty($result['error']) ? $result['error'] : '云打印未受理', $result);
$job->delete();
return;
}
Db::name('shopro_order_print_task')->where('id', $task['id'])->update([
'status' => 1,
'printer_response' => $result['response'],
'printed_at' => time(),
'updated_at' => time(),
'last_error' => '',
]);
$job->delete();
} catch (\Exception $e) {
if ($task) {
$this->failTask($task['id'], $e->getMessage(), []);
}
\think\Log::error('订单小票打印失败,订单ID ' . $orderId . ': ' . $e->getMessage());
$job->delete();
}
}
protected function buildOrderData($order)
{
$items = [];
foreach ((array)$order['item'] as $item) {
$items[] = [
'name' => (isset($item['goods_title']) ? $item['goods_title'] : '商品') . (!empty($item['goods_sku_text']) ? ' (' . $item['goods_sku_text'] . ')' : ''),
'num' => isset($item['goods_num']) ? $item['goods_num'] : 1,
'price' => isset($item['goods_price']) ? $item['goods_price'] : '0.00',
];
}
$address = (isset($order['province_name']) ? $order['province_name'] : '')
. (isset($order['city_name']) ? $order['city_name'] : '')
. (isset($order['area_name']) ? $order['area_name'] : '')
. (isset($order['address']) ? $order['address'] : '');
return [
'shop_name' => '小众厨房设备商城',
'order_sn' => $order['order_sn'],
'createtime' => $order['createtime'],
'consignee' => isset($order['consignee']) ? $order['consignee'] : '客户',
'phone' => isset($order['phone']) ? $order['phone'] : '',
'address' => $address ?: '到店自提/商家配送',
'total_fee' => isset($order['pay_fee']) ? sprintf('%.2f', $order['pay_fee']) : $order['total_fee'],
'items' => $items,
];
}
protected function failTask($taskId, $error, $result)
{
Db::name('shopro_order_print_task')->where('id', $taskId)->update([
'status' => -1,
'printer_response' => isset($result['response']) ? $result['response'] : '',
'last_error' => mb_substr($error, 0, 500, 'UTF-8'),
'updated_at' => time(),
]);
}
}

查看文件

@@ -0,0 +1,184 @@
<?php
namespace app\common\library;
/**
* 芯烨云 (Xprinter / xingye) 小票打印机服务类
*/
class PrinterService
{
protected $user;
protected $ukey;
protected $sn;
protected $url = "https://open.xprinter.com/Api/Open/";
public function __construct()
{
$config = [];
if (function_exists("config")) {
$config = config("printer");
}
if (empty($config)) {
$configFile = __DIR__ . "/../../extra/printer.php";
if (file_exists($configFile)) {
$config = include $configFile;
}
}
$this->user = isset($config["client_id"]) ? trim($config["client_id"]) : "";
$this->ukey = isset($config["client_secret"]) ? trim($config["client_secret"]) : "";
$this->sn = isset($config["sn"]) ? trim($config["sn"]) : "";
}
/**
* 查询芯烨云打印机状态
*/
public function queryStatus()
{
$stime = time();
$sig = sha1($this->user . $this->ukey . $stime);
$params = [
"user" => $this->user,
"stime" => $stime,
"sig" => $sig,
"apiname" => "Open_queryPrinterStatus",
"sn" => $this->sn
];
return $this->sendRequest($params);
}
/**
* 打印订单小票
*/
public function printOrder($orderData = [], $times = 1)
{
$stime = time();
$sig = sha1($this->user . $this->ukey . $stime);
$content = $this->buildReceiptContent($orderData);
$params = [
"user" => $this->user,
"stime" => $stime,
"sig" => $sig,
"apiname" => "Open_printMsg",
"sn" => $this->sn,
"content" => $content,
"times" => $times
];
return $this->sendRequest($params);
}
/**
* 拼接排版小票格式
*/
public function buildReceiptContent($order = [])
{
$title = $this->cleanText(isset($order["shop_name"]) ? $order["shop_name"] : "小众厨房设备商城");
$orderSn = $this->cleanText(isset($order["order_sn"]) ? $order["order_sn"] : "TEST" . date("YmdHis"));
$createTime = isset($order["createtime"]) ? date("Y-m-d H:i:s", $order["createtime"]) : date("Y-m-d H:i:s");
$consignee = $this->cleanText(isset($order["consignee"]) ? $order["consignee"] : "测试用户");
$phone = $this->cleanText(isset($order["phone"]) ? $order["phone"] : "138****8888");
$address = $this->cleanText(isset($order["address"]) ? $order["address"] : "贵州省修文县城内");
$totalAmount = $this->cleanText(isset($order["total_fee"]) ? $order["total_fee"] : "0.01");
$info = "<CB>{$title}</CB><BR>";
$info .= "<CB>-- 订单小票 --</CB><BR>";
$info .= "--------------------------------<BR>";
$info .= "订单编号:" . $orderSn . "<BR>";
$info .= "下单时间:" . $createTime . "<BR>";
$info .= "--------------------------------<BR>";
$info .= "商品名称 数量 单价<BR>";
if (!empty($order["items"]) && is_array($order["items"])) {
foreach ($order["items"] as $item) {
$name = $this->cleanText(isset($item["name"]) ? $item["name"] : "商品");
$num = $this->cleanText(isset($item["num"]) ? $item["num"] : 1);
$price = $this->cleanText(isset($item["price"]) ? $item["price"] : "0.00");
$info .= $name . " " . $num . " ¥" . $price . "<BR>";
}
} else {
$info .= "测试商品-厨房专用设备 1 ¥" . $totalAmount . "<BR>";
}
$info .= "--------------------------------<BR>";
$info .= "合计金额:¥" . $totalAmount . " 元<BR>";
$info .= "客户姓名:" . $consignee . "<BR>";
$info .= "联系电话:" . $phone . "<BR>";
$info .= "送货地址:" . $address . "<BR>";
$info .= "--------------------------------<BR>";
$info .= "<CB>谢谢惠顾,欢迎再次光临!</CB><BR><BR>";
return $info;
}
/**
* 发送 cURL 请求给芯烨云 API 网关
*/
protected function sendRequest($data)
{
if (!$this->user || !$this->ukey || !$this->sn) {
return [
'accepted' => false,
'response' => '',
'error' => '打印机配置不完整',
'uncertain' => false,
];
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Cookie: _gp_pc=1"]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
$error = curl_error($ch);
$errno = curl_errno($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($error) {
return [
'accepted' => false,
'response' => '',
'error' => '云打印请求失败: ' . $error,
// 网络层无法确认服务端是否已经受理,禁止自动重试以避免重复小票。
'uncertain' => true,
];
}
$response = trim((string)$result);
$accepted = $httpCode >= 200 && $httpCode < 300 && $this->isAcceptedResponse($response);
return [
'accepted' => $accepted,
'response' => mb_substr($response, 0, 1000, 'UTF-8'),
'error' => $accepted ? '' : '云打印未受理,HTTP ' . $httpCode,
'uncertain' => false,
];
}
protected function isAcceptedResponse($response)
{
if (strtoupper($response) === 'OK') {
return true;
}
$data = json_decode($response, true);
return is_array($data) && (
(isset($data['ret']) && (int)$data['ret'] === 0) ||
(isset($data['code']) && (int)$data['code'] === 0)
);
}
protected function cleanText($value)
{
$value = strip_tags((string)$value);
return preg_replace('/[\r\n\t]+/', ' ', $value);
}
}