要做一个淘宝客的微信公众号,想实现用户手淘分享商品公众号查内部优惠券的功能,但是淘宝联盟目前没有开放通过淘宝商品id查询优惠券、佣金信息的接口,好在有提供通用物料搜索api。
我这里有发布好的接口,可供大家调用,需要的话,可加我微信
大体思路是解析手淘分享内容,找出商品关键字,然后通过商品关键字使用淘宝 通用物料搜索api查到佣金、优惠券信息。实现最终效果如下:
实现
1 申请淘宝联盟appkey、secret
因为需要使用到淘宝接口,所以需要申请淘宝appkey、secret。需要开通淘宝客基础api和淘口令api,请自行前往淘宝联盟申请。
2 下载淘宝联盟sdk
需要申请淘宝appkey、secret之后在淘宝开放平台下载淘宝联盟SDK。
3 封装淘宝接口
目前只需要用到通用物料搜索api和淘宝客淘口令api,所以封装了这两个接口。
代码如下:
/// <summary>
/// 淘宝物料搜索接口,获取佣金、优惠券信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public IList<MapDataDomain> MaterialOptional(string key)
{
if (string.IsNullOrEmpty(appkey)||string.IsNullOrEmpty(secret)||addzoneId==0)
{
throw new Exception("请检查是否设置接口url、淘宝appkey、secret及addzoneId");
}
ITopClient client = new DefaultTopClient(apiUrl,appkey,secret);
TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
req.AdzoneId = addzoneId;
req.Platform = 2L;
req.PageSize = 100L;
req.Q = key;
req.PageNo = 1L;
TbkDgMaterialOptionalResponse rsp = client.Execute(req);
return rsp.ResultList;
}
/// <summary>
/// 获取淘口令
/// </summary>
/// <param name="url"></param>
/// <param name="log_url"></param>
/// <returns></returns>
public string GetTaobaoKePassword(string url, string log_url)
{
ITopClient client = new DefaultTopClient(apiUrl, appkey, secret);
TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
if (url.Substring(0, 4) != "http")
{
url = "https:" + url;
}
req.Text = "关注“网购有券”,超值活动,惊喜多多!";
req.Url = url;
req.Logo = log_url;
TbkTpwdCreateResponse rsp = client.Execute(req);
return rsp.Data.Model;
}
4. 解析商品关键字,并查询佣金、优惠券信息。
解析商品关键字有两种方式,一种是通过抓取淘宝分享内容中“【】”里的内容,将其作为关键字查询;另外一种是通过淘宝分享内容中的超链接,通过抓包方式获取关键字。
这两种都有些缺陷,第一种可能手淘版本的区别,会存在“【】”中内容不是淘宝商品关键字的情况,另外一种存在较小概率抓包失败的情况。所以目前这两种方式都需要用到。
第一种通过抓取淘宝分享内容中“【】”做关键字实现如下:
public string QueryCoupon(string itemInfo)
{
string responeMessage = "";
try
{
Match m_title = Regex.Match(itemInfo, @"【.*】");
string temp = m_title.Value;
if (!string.IsNullOrEmpty(temp))
{
temp = temp.Substring(1, temp.Length - 2);
}
else
{
return "";
}
if (temp.Contains("#手聚App"))
{
int IndexofA = temp.IndexOf("宝贝不错:");
int IndexofB = temp.IndexOf("(分享自");
temp = temp.Substring(IndexofA + 5, IndexofB - IndexofA - 5);
}
string title = temp;
//解决手淘分享【】内非商品关键字bug
if (title.Contains(",") | title.Contains(","))
{
return GetTaobaoCouponByLink(itemInfo);
}
var resultList = taobaoCommonApi.MaterialOptional(title);
if (resultList!=null&&resultList.Count > 0)
{
//获取淘宝短链接
Match m_url = Regex.Match(itemInfo, @"htt(p|ps):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?");
if (m_url.Value == "")
{
return responeMessage;
}
var s = HttpUtility.HttpGet(m_url.Value, "", "utf-8");
//获取宝贝item id
Match m_item = Regex.Match(s, @"((?<=m.taobao.com\/i)([0-9]+))|((?<=&id=)([0-9]+))");
string item_id = m_item.Value;
if (string.IsNullOrEmpty(item_id))
{
Match am_url = Regex.Match(s, @"(?<=var url = ')(.*)(?=')");
var htmlContent = HttpUtility.HttpGet(am_url.Value, "", "gbk");
Match re_m_item = Regex.Match(htmlContent, @"(?<=taobao.com/item.htm\?id=)([0-9]*)");
item_id = re_m_item.Value;
}
if (string.IsNullOrEmpty(item_id))
{
var g = resultList.Where(y => !string.IsNullOrEmpty(y.CouponId)).OrderByDescending(w => w.Volume).FirstOrDefault();
if (g == null)
{
responeMessage = ConfigurationManager.AppSettings["tbk_nocoupon_msg"].Replace("\\n", "\n").Replace("\\ue231", "\ue231");
}
else
{
var hongbao = (decimal.Parse(g.ZkFinalPrice) - decimal.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value)) * decimal.Parse(g.CommissionRate) / 10000 * commission_rate;
responeMessage = $"{g.Title}\n【在售价】{g.ZkFinalPrice}元\n【巻后价】{Math.Round(double.Parse(g.ZkFinalPrice) - double.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value), 2)} 元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(g.CouponShareUrl, g.PictUrl + "_400x400.jpg")}\n";
}
return responeMessage;
}
else
{
float numid = 0;
try
{
numid = float.Parse(item_id);
}
catch (Exception ex)
{
var g = resultList.Where(y => !string.IsNullOrEmpty(y.CouponId)).OrderByDescending(y => y.Volume).FirstOrDefault();
var hongbao = (decimal.Parse(g.ZkFinalPrice) - decimal.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value)) * decimal.Parse(g.CommissionRate) / 10000 * commission_rate;
responeMessage = $"{g.Title}\n【在售价】{g.ZkFinalPrice}元\n【巻后价】{Math.Round(double.Parse(g.ZkFinalPrice) - double.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value), 2)} 元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(g.CouponShareUrl, g.PictUrl + "_400x400.jpg")}\n";
return responeMessage;
}
foreach (var g in resultList)
{
if (g.NumIid == numid)
{
if (string.IsNullOrEmpty(g.CouponInfo))
{
var hongbao = decimal.Parse(g.ZkFinalPrice) * decimal.Parse(g.CommissionRate) / 10000 * commission_rate;
responeMessage = $"{g.Title}\n【在售价】{g.ZkFinalPrice}元\n【约返利】{Math.Round(hongbao, 2)}元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(g.Url, g.PictUrl + "_400x400.jpg")}\n==========================\n下单确认收货后就能收到返利佣金啦~\n 点击查看 <a href='http://mp.weixin.qq.com/s?__biz=Mzg2NTAxOTEyMA==&mid=100000146&idx=1&sn=62405c8df3db46e74940aefb9ac3737b&chksm=4e61340d7916bd1bf645afbc6d10c1f19561d7fa59847516c01e64c0791e6d544f4f56c4f498#rd'>如何领取返利</a>";
return responeMessage;
}
else
{
var hongbao = (decimal.Parse(g.ZkFinalPrice) - decimal.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value)) * decimal.Parse(g.CommissionRate) / 10000 * commission_rate;
responeMessage = $"{g.Title}\n【在售价】{g.ZkFinalPrice}元\n【巻后价】{Math.Round(double.Parse(g.ZkFinalPrice) - double.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value), 2)} 元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(g.CouponShareUrl, g.PictUrl + "_400x400.jpg")}\n";
return responeMessage;
}
}
}
//没有找到,有相似宝贝推荐
var w = resultList.Where(y => !string.IsNullOrEmpty(y.CouponId)).OrderByDescending(y => y.Volume).FirstOrDefault();
if (w == null)
{
responeMessage = ConfigurationManager.AppSettings["tbk_nocoupon_msg"].Replace("\\n", "\n").Replace("\\ue231", "\ue231");
}
else
{
var hongbao = (decimal.Parse(w.ZkFinalPrice) - decimal.Parse(Regex.Match(w.CouponInfo, "减" + @"(\d+)").Groups[1].Value)) * decimal.Parse(w.CommissionRate) / 10000 * commission_rate;
responeMessage = $"/:rose 亲,这款商品的优惠返利活动结束了~\n已为你推荐以下宝贝。\n==========================\n{w.Title}\n【在售价】{w.ZkFinalPrice}元\n【巻后价】{Math.Round(double.Parse(w.ZkFinalPrice) - double.Parse(Regex.Match(w.CouponInfo, "减" + @"(\d+)").Groups[1].Value), 2)} 元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(w.CouponShareUrl, w.PictUrl + "_400x400.jpg")}\n";
}
return responeMessage;
}
}
else
{
responeMessage = GetTaobaoCouponByLink(itemInfo);
}
}
catch (Exception ex)
{
Senparc.Weixin.WeixinTrace.SendCustomLog("查询淘宝优惠券异常",ex.Message);
}
return responeMessage;
}
第二种通过超链接抓包方式获取关键字方式,代码如下:
public string GetTaobaoCouponByLink(string itemInfo)
{
string tbk_nocoupon_msg = ConfigurationManager.AppSettings["tbk_nocoupon_msg"].Replace("\\n", "\n").Replace("\\ue231", "\ue231");
Match m_url = Regex.Match(itemInfo, @"htt(p|ps):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?");
if (m_url.Value == "")
{
return tbk_nocoupon_msg;
}
var s = HttpUtility.HttpGet(m_url.Value, "", "utf-8");
//获取宝贝item id
Match m_item = Regex.Match(s, @"((?<=m.taobao.com\/i)([0-9]+))|((?<=&id=)([0-9]+))");
string item_id = m_item.Value;
Match am_url = Regex.Match(s, @"(?<=var url = ')(.*)(?=')");
var htmlContent = HttpUtility.HttpGet(am_url.Value, "", "gbk");
Match keyMatch = Regex.Match(htmlContent, "(?<=title\\>).*(?=</title)");
if (string.IsNullOrEmpty(item_id))
{
Match re_m_item = Regex.Match(htmlContent, @"(?<=taobao.com/item.htm\?id=)([0-9]*)");
item_id = re_m_item.Value;
}
if (string.IsNullOrEmpty(keyMatch.Value))
{
return tbk_nocoupon_msg;
}
var mapDataResponse = taobaoCommonApi.MaterialOptional(keyMatch.Value.Split('-')[0]);
string responeMessage = "";
float numid = float.Parse(item_id);
if (mapDataResponse!=null&&mapDataResponse.Count > 0)
{
foreach (var g in mapDataResponse)
{
if (g.NumIid == numid)
{
if (string.IsNullOrEmpty(g.CouponInfo))
{
var hongbao = decimal.Parse(g.ZkFinalPrice) * decimal.Parse(g.CommissionRate) / 10000 * commission_rate;
responeMessage = $"{g.Title}\n【在售价】{g.ZkFinalPrice}元\n【约返利】{Math.Round(hongbao, 2)}元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(g.Url, g.PictUrl + "_400x400.jpg")}\n==========================\n下单确认收货后就能收到返利佣金啦~\n 点击查看 <a href='http://mp.weixin.qq.com/s?__biz=Mzg2NTAxOTEyMA==&mid=100000146&idx=1&sn=62405c8df3db46e74940aefb9ac3737b&chksm=4e61340d7916bd1bf645afbc6d10c1f19561d7fa59847516c01e64c0791e6d544f4f56c4f498#rd'>如何领取返利</a>";
return responeMessage;
}
else
{
var hongbao = (decimal.Parse(g.ZkFinalPrice) - decimal.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value)) * decimal.Parse(g.CommissionRate) / 10000 * commission_rate;
responeMessage = $"{g.Title}\n【在售价】{g.ZkFinalPrice}元\n【巻后价】{Math.Round(double.Parse(g.ZkFinalPrice) - double.Parse(Regex.Match(g.CouponInfo, "减" + @"(\d+)").Groups[1].Value), 2)} 元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(g.CouponShareUrl, g.PictUrl + "_400x400.jpg")}\n";
return responeMessage;
}
}
}
//没有找到,有相似宝贝推荐
var w = mapDataResponse.Where(y => !string.IsNullOrEmpty(y.CouponId)).OrderByDescending(y => y.Volume).FirstOrDefault();
if (w == null)
{
responeMessage = ConfigurationManager.AppSettings["tbk_nocoupon_msg"].Replace("\\n", "\n").Replace("\\ue231", "\ue231");
}
else
{
var hongbao = (decimal.Parse(w.ZkFinalPrice) - decimal.Parse(Regex.Match(w.CouponInfo, "减" + @"(\d+)").Groups[1].Value)) * decimal.Parse(w.CommissionRate) / 10000 * commission_rate;
responeMessage = $"/:rose 亲,这款商品的优惠返利活动结束了~\n已为你推荐以下宝贝。\n==========================\n{w.Title}\n【在售价】{w.ZkFinalPrice}元\n【巻后价】{Math.Round(double.Parse(w.ZkFinalPrice) - double.Parse(Regex.Match(w.CouponInfo, "减" + @"(\d+)").Groups[1].Value), 2)} 元\n复制这条信息,打开「手机绹宝」领巻下单{taobaoCommonApi.GetTaobaoKePassword(w.CouponShareUrl, w.PictUrl + "_400x400.jpg")}\n";
}
return responeMessage;
}
else
{
return ConfigurationManager.AppSettings["tbk_nocoupon_msg"].Replace("\\n", "\n").Replace("\\ue231", "\ue231");
}
}
代码较乱,请见谅。目前代码也在整理中,如有问题可以留言。
完整代码 github下载
扫一扫下面的二维码就能加入0元购群,快来抢购吧。群号:773148934