商品链接查询淘宝商品信息接口,淘宝天猫宝贝信息采集、淘宝商品历史最低价格数据接口、优惠信息数据、单日领券销量最高销量数据接口,淘宝联盟ck延期方案|接口+html前端UI界面
PHP完整代码:
<?php
// 定义API接口地址和参数
$apiUrl = "https://api.taolale.com/api/Tb_union/TB_Obtain_Products_Discounts";
//API文档地址:https://api.taolale.com/doc/8
$apiKey = "4mcAaupvfZOxgDDu9oz0ry39Tq"; // 替换为你的API Key
$Query = "替换为需要查询的淘宝商品链接"; // 替换为需要查询的淘宝商品链接
// 构建查询字符串
$queryString = http_build_query([
'key' => $apiKey,
'Query' => $Query
]);
// 初始化cURL会话
$ch = curl_init();
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $apiUrl.
"?".$queryString); // URL + 查询字符串
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应结果而不是直接输出
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // 设置请求方式为POST
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'application/x-www-form-urlencoded' // 设置请求头
]);
// 发送请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if (curl_errno($ch)) {
echo 'cURL Error: '.curl_error($ch);
} else {
// 解码JSON响应
$responseData = json_decode($response, true);
//data.CommodityInformation.0.itemName
$itemName = $responseData['data']['CommodityInformation'][0]['itemName'] ?? null; //商品名称
//data.CommodityInformation.0.outputMktId
$outputMktId = $responseData['data']['CommodityInformation'][0]['outputMktId'] ?? null; //商品itemId
//data.CommodityInformation.0.price
$price = $responseData['data']['CommodityInformation'][0]['price'] ?? null; //商品价格
//data.CommodityInformation[0].couponStartFee
$coupon_Start_Fee = $responseData['data']['CommodityInformation'][0]['couponStartFee'] ?? null; //优惠券开始费用
//data.CommodityInformation[0].couponAmount
$coupon_Amount = $responseData['data']['CommodityInformation'][0]['couponAmount'] ?? null; //优惠券金额
//data.CommodityInformation[0].couponRemainCount
$coupon_Remain_Count = $responseData['data']['CommodityInformation'][0]['couponRemainCount'] ?? null; //优惠券剩余计数
$historyHighlights = $responseData['data']['CommodityInformation'][0]['historyHighlights'] ?? null;
//data.historyHighlights
// 遍历数组,查找name为"历史最低价"的项
$historyLowestPrice = null;
foreach($historyHighlights as $item) {
if ($item['name'] === '历史最低价') {
$historyLowestPrice = $item;
break; // 找到后退出循环
}
}
//data.historyHighlights
// 遍历数组,查找name为"单日推广销量最高"的项
$Highdailysalesvolume = null;
foreach($historyHighlights as $item) {
if ($item['name'] === '单日推广销量最高') {
$Highdailysalesvolume = $item;
break; // 找到后退出循环
}
}
if ($historyLowestPrice['date']) {
// 将日期字符串重新格式化为YYYYMMDD格式以便DateTime类可以正确解析
$formattedDateString = substr($historyLowestPrice['date'], 0, 4).
'-'.substr($historyLowestPrice['date'], 4, 2).
'-'.substr($historyLowestPrice['date'], 6, 2);
// 创建DateTime对象
$date = new DateTime($formattedDateString);
// 格式化日期为所需格式
$historyLowestPrice['date'] = $date -> format('Y年m月d日');
}
if ($Highdailysalesvolume['date']) {
// 将日期字符串重新格式化为YYYYMMDD格式以便DateTime类可以正确解析
$formattedDateString = substr($Highdailysalesvolume['date'], 0, 4).
'-'.substr($Highdailysalesvolume['date'], 4, 2).
'-'.substr($Highdailysalesvolume['date'], 6, 2);
// 创建DateTime对象
$date = new DateTime($formattedDateString);
// 格式化日期为所需格式
$Highdailysalesvolume['date'] = $date -> format('Y年m月d日');
}
$Quan = $responseData['data']['Discountinformation'][0]['creativeStyle'][0]['cpsShortLinkUrl'] ?? null; //精简风格优惠券链接
if (!$Quan) {
//data.Discountinformation[0].creativeStyle[1].cpsShortLinkUrl
$Quan = $responseData['data']['Discountinformation'][0]['creativeStyle'][1]['cpsShortLinkUrl'] ?? null; //长句风格优惠券链接
}
//data.CommodityInformation[0].couponEffectiveEndTime
$Effective_End_Time = $responseData['data']['CommodityInformation'][0]['couponEffectiveEndTime'] ?? null; //优惠券结束时间戳
// 转换为十位时间戳(秒级)
$Effective_End_Time = $Effective_End_Time / 1000;
// 格式化时间
$Effective_End_Time = date('Y-m-d H:i:s', $Effective_End_Time);
// 检查解码是否成功
if (json_last_error() === JSON_ERROR_NONE) {
// 输出响应数据
echo "Code: ".$responseData['code'].
"<br>";
echo "Message: ".$responseData['msg'].
"<br>";
if ($responseData['code'] == 200) { // 200表示成功
$data = $responseData['data'];
echo "宝贝名称: ".$itemName.
"<br>";
echo "宝贝itemid: ".$outputMktId.
"<br>";
echo "宝贝价格: ".$price.
'元'.
"<br>";
echo "优惠规则: ".
'满'.$coupon_Start_Fee.
'元减'.$coupon_Amount.
'元'.
"<br>";
echo "优惠券剩余: ".$coupon_Remain_Count.
'张'.
"<br>";
echo "优惠券金额: ".$coupon_Amount.
'元'.
"<br>";
echo "优惠券链接: ".$Quan.
"<br>";
echo "优惠券结束时间: ".$Effective_End_Time.
"<br>";
echo "历史最低价时间: ".$historyLowestPrice['date'].
"<br>";
echo "历史最低价价格: ".$historyLowestPrice['price'].
'元'.
"<br>";
echo "单日领券销量最高|日期: ".$Highdailysalesvolume['date'].
"<br>";
echo "单日领券销量最高|数量: ".$Highdailysalesvolume['promotionSales'].
'件'.
"<br>";
} else {
echo "Error: ".$responseData['msg'];
}
} else {
echo 'JSON Decode Error: '.json_last_error_msg();
}
}
// 关闭cURL会话
curl_close($ch); ?>
HTML完整代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>淘宝商品信息|低价历史|最高销量信息查询</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
<!-- <link href="./css/bootstrap.min.css" rel="stylesheet"> -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- <script src="./js/jquery-3.5.1.min.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
<!-- <script src="./js/bootstrap.bundle.min.js"></script> -->
<style>
body {
background-color: #f8f9fa;
font-family: 'Arial', sans-serif;
}
.container {
max-width: 750px;
margin: 50px auto;
padding: 20px;
background-color: #ffffff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}
.alert {
margin-top: 20px;
}
.result-list {
margin-top: 20px;
}
.n {
width: 100%;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header">
<h3 class="card-title text-center">淘宝商品信息|低价历史|最高销量信息查询</h3>
</div>
<div class="card-body">
<form id="queryForm">
<div class="form-group">
<label for="Query">商品链接</label>
<input type="text" class="form-control" id="Query" name="Query" placeholder="请输入淘宝商品链接或商品ID" required>
</div>
<button type="submit" class="btn btn-primary btn-block n">查询</button>
</form>
<div id="result" class="mt-3">
<div id="alertContainer" class="mt-3"></div>
<ul class="list-group" id="resultList"></ul>
</div>
<div class="alert alert-info alert-dismissible fade show" role="alert">
<strong>可输入示例:</strong><br>【淘宝】大促价保 http://e.tb.cn/h.TaL719yr5hssIZH?tk=rIoW3KIl6p7 CZ8908 「乔丹运动鞋跑步鞋女2024冬季减震回弹户外越野鞋防滑耐磨登山鞋子」
点击链接直接打开 或者 淘宝搜索直接打开<br><br>846811603648<br><br>https://detail.tmall.com/item.htm?app=chrome&bxsign=scdneZJ4VWozSugTIWgvOG2d0aGHVLobd18Ld0iMNf8F4kuus9L1ewVyfWkNq19I6SaKJTYN3icFDjxVZxt8iGNmjoL2cULScrTEMsc5u__w52fdM9LZ_GIK0odULgiaafB&cpp=1&id=846811603648&share_crt_v=1&shareurl=true&short_name=h.TaL719yr5hssIZH&sp_tk=cklvVzNLSWw2cDc%3D&spm=a2159r.13376460.0.0&tbSocialPopKey=shareItem&tk=rIoW3KIl6p7%20CZ8908&un=aa48d20ce0c3a429d9a2d33a0bf32337&un_site=0&ut_sk=1.ZngiZZiLuHsDAFzTNEvdxhN0_21380790_1730947521627.TaoPassword-Weixin.1&wxsign=tbwso7SC046gyl_tNckSuixELKOUDMKNtxFe_m5HzhcG9MrkSgYHtjosdO-x0uOEkkBmNkNgY4x3geb2iFWjKQmMwzhaM_i16E4zxO0DXPaApYghAzQ9Dr5XYrmC094e_9G<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#queryForm').on('submit', function (e) {
e.preventDefault();
var Query = $('#Query').val();
//API文档地址:https://api.taolale.com/doc/8
var apiKey = '4mcAaupvfZOxgDDu9oz0ry39Tq'; // 请在此处替换为你的API key
var apiUrl = `https://api.taolale.com/api/Tb_union/TB_Obtain_Products_Discounts?key=${apiKey}&Query=${Query}`;
// 弹出提示框(加载中...)
var alertDiv = $('<div class="alert alert-info alert-dismissible fade show" role="alert">' +
'<strong>加载中...</strong> 请稍等...' +
'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
'</div>');
$('#alertContainer').html(alertDiv);
$.ajax({
url: apiUrl,
method: 'POST',
dataType: 'json',
success: function (response) {
// 关闭加载提示框
$('.alert').alert('close');
if (response.code === 200) {
var resultList = $('#resultList');
resultList.empty();
var data = response.data;
//优惠券结束时间格式转换开始
var End_Time = data.CommodityInformation[0].couponEffectiveEndTime;
// 创建一个新的Date对象
var date = new Date(parseInt(End_Time));
console.log('优惠券结束时间:', date);
// 提取年、月、日、时、分、秒
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份从0开始,需要加1,并且保证是两位数
var day = ('0' + date.getDate()).slice(-2); // 保证是两位数
var hours = ('0' + date.getHours()).slice(-2); // 保证是两位数
var minutes = ('0' + date.getMinutes()).slice(-2); // 保证是两位数
var seconds = ('0' + date.getSeconds()).slice(-2); // 保证是两位数
// 格式化日期和时间
var formattedDateTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
//优惠券结束时间格式转换结束
//历史最低价时间 时间格式转换开始
var Low_Price = data.CommodityInformation[0].historyHighlights[0].date;
// 提取年、月、日,并转换为整数
var Low_Price_year = parseInt(Low_Price.substring(0, 4), 10);
var Low_Price_month = parseInt(Low_Price.substring(4, 6), 10);
var Low_Price_day = parseInt(Low_Price.substring(6, 8), 10);
// 格式化月份和日期为两位数,并添加中文的“月”和“日”
var Low_Price_formattedMonth = ('0' + Low_Price_month).slice(-2) + "月";
var Low_Price_formattedDay = ('0' + Low_Price_day).slice(-2) + "日";
// 格式化日期字符串
var Low_Price_DateString = Low_Price_year + "年" + Low_Price_formattedMonth + Low_Price_formattedDay;
//历史最低价时间 时间格式转换结束
//单日领券销量最高 时间格式转换开始
var High_Sales = data.CommodityInformation[0].historyHighlights[3].date;
// 提取年、月、日,并转换为整数
var High_Sales_year = parseInt(High_Sales.substring(0, 4), 10);
var High_Sales_month = parseInt(High_Sales.substring(4, 6), 10);
var High_Sales_day = parseInt(High_Sales.substring(6, 8), 10);
// 格式化月份和日期为两位数,并添加中文的“月”和“日”
var High_Sales_formattedMonth = ('0' + High_Sales_month).slice(-2) + "月";
var High_Sales_formattedDay = ('0' + High_Sales_day).slice(-2) + "日";
// 格式化日期字符串
var High_Sales_DateString = High_Sales_year + "年" + High_Sales_formattedMonth + High_Sales_formattedDay;
//单日领券销量最高 时间格式转换结束
resultList.append(`<h4 class="text-center">查询结果</h4>`);
resultList.append(`<li class="list-group-item">宝贝名称: ${data.CommodityInformation[0].itemName}</li>`);
resultList.append(`<li class="list-group-item">宝贝itemid: ${data.CommodityInformation[0].outputMktId}</li>`);
resultList.append(`<li class="list-group-item">宝贝价格: ${data.CommodityInformation[0].price}元</li>`);
resultList.append(`<li class="list-group-item">优惠规则: 满${data.CommodityInformation[0].couponStartFee}元减${data.CommodityInformation[0].couponAmount}元</li>`);
resultList.append(`<li class="list-group-item">优惠券剩余: ${data.CommodityInformation[0].couponRemainCount}张</li>`);
resultList.append(`<li class="list-group-item">优惠券金额: ${data.CommodityInformation[0].couponAmount}元</li>`);
resultList.append(`<li class="list-group-item">优惠券链接: ${data.Discountinformation[0].creativeStyle[0].cpsShortLinkUrl}</li>`);
resultList.append(`<li class="list-group-item">优惠券结束时间: ${formattedDateTime}</li>`);
resultList.append(`<li class="list-group-item">历史最低价时间: ${Low_Price_DateString}</li>`);
resultList.append(`<li class="list-group-item">历史最低价价格: ${data.CommodityInformation[0].historyHighlights[0].price}元</li>`);
resultList.append(`<li class="list-group-item">单日领券销量最高|日期: ${High_Sales_DateString}</li>`);
resultList.append(`<li class="list-group-item">单日领券销量最高|数量: ${data.CommodityInformation[0].historyHighlights[3].promotionSales}件</li>`);
} else {
// 如果查询失败,则弹出错误提示框
var errorDiv = $('<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
'<strong>查询失败!</strong>' +
'<p>' + response.msg +" || "+ response.data + '</p>' +
'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
'</div>');
$('#alertContainer').html(errorDiv);
}
},
error: function(xhr, status, error) {
// 如果请求失败,则弹出错误提示框
var errorDiv = $('<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
'<strong>请求失败!</strong>' +
'<p>' + xhr.response || '无法连接到服务器,请稍后再试。' + '</p>' +
'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
'</div>');
$('#alertContainer').html(errorDiv);
}
});
});
});
</script>
</body>
</html>
标签:优惠券,数据,CommodityInformation,接口,echo,date,淘宝,var,data
From: https://blog.csdn.net/weixin_47019180/article/details/143609787