文件差异内容过多而无法显示
加载差异
@@ -0,0 +1,254 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
class PrinterService
|
||||
{
|
||||
protected $user;
|
||||
protected $ukey;
|
||||
protected $sn;
|
||||
protected $enabled = true;
|
||||
protected $copies = 1;
|
||||
protected $expiresIn = 3600;
|
||||
protected $shopName = '小众厨房设备商城';
|
||||
protected $labelWidthMm = 40;
|
||||
protected $labelHeightMm = 30;
|
||||
protected $labelGapMm = 2;
|
||||
protected $url = 'https://open.xpyun.net/api/openapi/xprinter/';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$config = function_exists('config') ? config('printer') : [];
|
||||
if (!is_array($config) || empty($config)) {
|
||||
$configFile = __DIR__ . '/../../extra/printer.php';
|
||||
$config = file_exists($configFile) ? include $configFile : [];
|
||||
}
|
||||
$config = is_array($config) ? $config : [];
|
||||
|
||||
// 后台配置优先;空字段保留文件配置,方便首次迁移时平滑过渡。
|
||||
try {
|
||||
$backendConfig = \addons\shopro\model\Config::load('printer');
|
||||
if (is_array($backendConfig)) {
|
||||
foreach ($backendConfig as $key => $value) {
|
||||
if ($value !== '' && $value !== null) {
|
||||
$config[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
\think\Log::warning('读取后台标签打印配置失败: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$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']) : '';
|
||||
$this->enabled = !isset($config['enable']) || (string)$config['enable'] !== '0';
|
||||
$this->copies = isset($config['copies']) ? max(1, min(65535, (int)$config['copies'])) : 1;
|
||||
$this->expiresIn = isset($config['expires_in']) ? max(1, min(86399, (int)$config['expires_in'])) : 3600;
|
||||
$this->shopName = !empty($config['shop_name']) ? trim($config['shop_name']) : $this->shopName;
|
||||
$this->labelWidthMm = $this->normalizeMillimeters(isset($config['label_width_mm']) ? $config['label_width_mm'] : 40, 20, 120, 40);
|
||||
$this->labelHeightMm = $this->normalizeMillimeters(isset($config['label_height_mm']) ? $config['label_height_mm'] : 30, 20, 120, 30);
|
||||
$this->labelGapMm = $this->normalizeMillimeters(isset($config['label_gap_mm']) ? $config['label_gap_mm'] : 2, 0, 20, 2);
|
||||
}
|
||||
|
||||
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 = null)
|
||||
{
|
||||
return $this->printLabelOrder($orderData, $copies);
|
||||
}
|
||||
|
||||
public function printLabelOrder($orderData = [], $copies = null)
|
||||
{
|
||||
if (!$this->enabled) {
|
||||
return $this->failure('后台未启用标签打印');
|
||||
}
|
||||
|
||||
$content = $this->buildLabelContent($orderData);
|
||||
if ($this->gbkLength($content) > 12 * 1024) {
|
||||
return $this->failure('打印内容超过芯烨云 12KB 限制');
|
||||
}
|
||||
|
||||
$idempotent = isset($orderData['print_idempotent']) ? trim((string)$orderData['print_idempotent']) : '';
|
||||
if ($idempotent !== '') {
|
||||
$idempotent = substr($idempotent, 0, 50);
|
||||
}
|
||||
|
||||
$result = $this->sendRequest('printLabel', [
|
||||
'sn' => $this->sn,
|
||||
'content' => $content,
|
||||
'copies' => $copies === null ? $this->copies : max(1, min(65535, (int)$copies)),
|
||||
// 离线时由芯烨云暂存,避免本地重发造成重复标签。
|
||||
'mode' => 1,
|
||||
'expiresIn' => $this->expiresIn,
|
||||
'idempotent' => $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 buildLabelContent($order = [])
|
||||
{
|
||||
$title = $this->labelText(isset($order['shop_name']) ? $order['shop_name'] : $this->shopName, 12);
|
||||
$orderSn = $this->barcodeText(isset($order['order_sn']) ? $order['order_sn'] : 'TEST' . date('YmdHis'));
|
||||
$itemSummary = $this->buildItemSummary(isset($order['items']) && is_array($order['items']) ? $order['items'] : []);
|
||||
$totalAmount = $this->labelText(isset($order['total_fee']) ? $order['total_fee'] : '0.00', 12);
|
||||
|
||||
$widthDots = (int)round($this->labelWidthMm * 8);
|
||||
$heightDots = (int)round($this->labelHeightMm * 8);
|
||||
$margin = 8;
|
||||
$barcodeY = 56;
|
||||
$barcodeHeight = 64;
|
||||
$itemY = $barcodeY + $barcodeHeight + 12;
|
||||
$quantityY = $itemY + 28;
|
||||
$totalY = $quantityY + 28;
|
||||
|
||||
// 40 x 30mm is the official example size. Keep the final text inside smaller custom labels.
|
||||
if ($totalY + 24 > $heightDots) {
|
||||
$barcodeY = 48;
|
||||
$barcodeHeight = max(40, min(56, $heightDots - 136));
|
||||
$itemY = $barcodeY + $barcodeHeight + 8;
|
||||
$quantityY = $itemY + 24;
|
||||
$totalY = $quantityY + 24;
|
||||
}
|
||||
|
||||
$content = '<PAGE l="' . $this->formatMillimeters($this->labelGapMm) . '">';
|
||||
$content .= '<SIZE>' . $this->formatMillimeters($this->labelWidthMm) . ',' . $this->formatMillimeters($this->labelHeightMm) . '</SIZE>';
|
||||
$content .= '<TEXT x="' . $margin . '" y="8" font="9" w="1" h="1" r="0">' . $title . '</TEXT>';
|
||||
$content .= '<TEXT x="' . $margin . '" y="32" font="9" w="1" h="1" r="0">订单号:' . $this->labelText($orderSn, 18) . '</TEXT>';
|
||||
$content .= '<BC128 x="' . $margin . '" y="' . $barcodeY . '" h="' . $barcodeHeight . '" s="0" n="1" w="1" r="0">' . $orderSn . '</BC128>';
|
||||
$content .= '<TEXT x="' . $margin . '" y="' . $itemY . '" font="9" w="1" h="1" r="0">商品:' . $itemSummary['name'] . '</TEXT>';
|
||||
$content .= '<TEXT x="' . $margin . '" y="' . $quantityY . '" font="9" w="1" h="1" r="0">数量:' . $itemSummary['quantity'] . '</TEXT>';
|
||||
$content .= '<TEXT x="' . $margin . '" y="' . $totalY . '" font="9" w="1" h="1" r="0">金额:' . $totalAmount . '</TEXT>';
|
||||
return $content . '</PAGE>';
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
protected function labelText($value, $maxWidth)
|
||||
{
|
||||
$text = $this->cleanText($value);
|
||||
if (function_exists('mb_strimwidth')) {
|
||||
$text = mb_strimwidth($text, 0, $maxWidth * 2, '', 'UTF-8');
|
||||
} else {
|
||||
$text = substr($text, 0, $maxWidth * 2);
|
||||
}
|
||||
return str_replace(['<', '>'], ['<', '>'], $text);
|
||||
}
|
||||
|
||||
protected function barcodeText($value)
|
||||
{
|
||||
$text = preg_replace('/[^\x20-\x7E]/', '', $this->cleanText($value));
|
||||
return $text !== '' ? substr($text, 0, 50) : 'TEST' . date('YmdHis');
|
||||
}
|
||||
|
||||
protected function buildItemSummary(array $items)
|
||||
{
|
||||
$firstName = '商品';
|
||||
$quantity = 0;
|
||||
foreach ($items as $index => $item) {
|
||||
if ($index === 0 && isset($item['name'])) {
|
||||
$firstName = $item['name'];
|
||||
}
|
||||
$quantity += isset($item['num']) ? max(1, (int)$item['num']) : 1;
|
||||
}
|
||||
if (count($items) > 1) {
|
||||
$firstName .= '等' . count($items) . '件';
|
||||
}
|
||||
return [
|
||||
'name' => $this->labelText($firstName, 12),
|
||||
'quantity' => $quantity ?: 1,
|
||||
];
|
||||
}
|
||||
|
||||
protected function normalizeMillimeters($value, $min, $max, $default)
|
||||
{
|
||||
if (!is_numeric($value)) {
|
||||
return $default;
|
||||
}
|
||||
return max($min, min($max, (float)$value));
|
||||
}
|
||||
|
||||
protected function formatMillimeters($value)
|
||||
{
|
||||
return rtrim(rtrim(number_format((float)$value, 2, '.', ''), '0'), '.');
|
||||
}
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户