2514 lines
114 KiB
C#
2514 lines
114 KiB
C#
//=============================================================
|
||
// 创建人:千年老妖
|
||
// 本页代码,均为原创。对未经许可擅自使用者,本人保留追究其法律责任的权利。
|
||
//==============================================================
|
||
using Api.Framework.Events;
|
||
using Api.Framework.Model;
|
||
using CsharpHttpHelper;
|
||
using Api.Framework.Tools;
|
||
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading.Tasks;
|
||
using System.Threading;
|
||
using Api.Framework.Utils;
|
||
using Api.Framework.Enums;
|
||
using System.Net;
|
||
using System.Web;
|
||
using System.Web.Caching;
|
||
using Api.Framework.Timers;
|
||
using System.Windows.Forms;
|
||
using Api.Framework.Data.TB;
|
||
using Api.Framework.EntityTmp;
|
||
using Api.Framework.Extents;
|
||
using Microsoft.ClearScript.Util.Web;
|
||
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Linq;
|
||
|
||
namespace Api.Framework.Cps
|
||
{
|
||
/// <summary>
|
||
/// 阿里妈妈操作Api
|
||
/// </summary>
|
||
public class AlimamaApi : BaseCpsApi
|
||
{
|
||
#region 静态功能
|
||
|
||
/// <summary>
|
||
/// url请求方法
|
||
/// </summary>
|
||
/// <param name="tempUrl"></param>
|
||
/// <returns></returns>
|
||
private static string M_GET_HTML(string tempUrl)
|
||
{
|
||
try
|
||
{
|
||
HttpItem item = new HttpItem()
|
||
{
|
||
URL = tempUrl, //URL 必需项
|
||
Method = "get", //URL 可选项 默认为Get
|
||
IsToLower = false, //得到的HTML代码是否转成小写 可选项默认转小写
|
||
Cookie = Cookies + ";random=" + new Random().Next(), //字符串Cookie 可选项
|
||
Referer = "http://m.taobao.com", //来源URL 可选项
|
||
Timeout = 100000, //连接超时时间 可选项默认为100000
|
||
ReadWriteTimeout = 30000, //写入Post数据超时时间 可选项默认为30000
|
||
UserAgent =
|
||
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", //用户的浏览器类型,版本,操作系统 可选项有默认值
|
||
ContentType = "text/html", //返回类型 可选项有默认值
|
||
Allowautoredirect = false, //是否根据301跳转 可选项
|
||
};
|
||
HttpHelper http = new HttpHelper();
|
||
//HttpResult result = http.GetHtml(item);
|
||
|
||
var result = http.GetHtml(item);
|
||
if (!string.IsNullOrEmpty(result.Cookie))
|
||
{
|
||
Cookies = result.UpdateCookies(Cookies);
|
||
}
|
||
|
||
return result.Html;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
//Console.WriteLine(ex.Message);
|
||
return string.Empty;
|
||
}
|
||
}
|
||
|
||
private static string appKey = "12574478";
|
||
private static string Cookies = string.Empty;
|
||
|
||
private static Dictionary<string, object> M_GET(string api, object data, string version = "1.0")
|
||
{
|
||
//_cookies = string.Empty;
|
||
int number = 1;
|
||
Next:
|
||
string time = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000).ToString();
|
||
string mh5Tk = HttpExtend.GetCookiesValue("_m_h5_tk", Cookies);
|
||
mh5Tk = string.IsNullOrEmpty(mh5Tk) ? "f64aa152f943661f750e6212ebc98804_1481170439770" : mh5Tk;
|
||
string json = (data.GetType() == typeof(string))
|
||
? data.ToString()
|
||
: HttpHelper.ObjectToJson(data).Replace("\\u0026", "&");
|
||
string temp_ = mh5Tk + "&" + time + "&" + appKey + "&" + json;
|
||
|
||
string sign = HttpHelper.ToMD5(temp_).ToLower();
|
||
;
|
||
string send = HttpHelper.URLEncode(json);
|
||
string temp =
|
||
string.Format(
|
||
"http://acs.m.taobao.com/h5/{5}/{4}/?v={4}&api={5}&appKey={0}&t={1}&callback=mtopjsonp1&type=jsonp&sign={2}&data={3}",
|
||
appKey, time, sign, send, version, api);
|
||
string html = M_GET_HTML(temp).Trim();
|
||
if ((html.Contains("令牌过期") || html.Contains("令牌为空") || html.Contains("失效") ||
|
||
html.Contains("login.m.taobao.com")))
|
||
{
|
||
if (number < 5)
|
||
{
|
||
number++;
|
||
goto Next;
|
||
}
|
||
}
|
||
|
||
var reg = System.Text.RegularExpressions.Regex.Match(html, @"^mtopjsonp1\((.*?)\)$",
|
||
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||
if (reg.Success)
|
||
{
|
||
var dic = HttpExtend.JsonToDictionary(reg.Groups[1].Value);
|
||
if (dic.ContainsKey("data") && html.Contains("SUCCESS::调用成功"))
|
||
return dic["data"] as Dictionary<string, object>;
|
||
throw new Exception(reg.Groups[1].Value);
|
||
}
|
||
|
||
throw new Exception(html);
|
||
}
|
||
|
||
private static Dictionary<string, DateTime> error_next = new Dictionary<string, DateTime>();
|
||
|
||
/// <summary>
|
||
/// 解析优惠券信息
|
||
/// </summary>
|
||
/// <param name="sellerId">商家id</param>
|
||
/// <param name="activityId">优惠券id</param>
|
||
/// <param name="pid"></param>
|
||
/// <returns></returns>
|
||
public static Dictionary<string, object> mtop_alimama_union_hsf_coupon_get(string sellerId, string activityId,
|
||
string pid = "")
|
||
{
|
||
try
|
||
{
|
||
//222097624044 7b66a82d352a4af481bc85452fcf3344
|
||
|
||
if (string.IsNullOrEmpty(pid)) pid = "mm_33231688_7050284_23466709";
|
||
string api = "mtop.alimama.union.hsf.mama.coupon.get";
|
||
string version = "1.0";
|
||
var data = new
|
||
{
|
||
sellerId = sellerId,
|
||
activityId = activityId,
|
||
pid = pid
|
||
|
||
};
|
||
if (!error_next.ContainsKey(api) || error_next[api] > DateTime.Now)
|
||
{
|
||
try
|
||
{
|
||
var result = M_GET(api, data, version);
|
||
return result;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
if (ex.Message.Contains("访问受限"))
|
||
{
|
||
error_next[api] = DateTime.Now.AddMinutes(10);
|
||
}
|
||
else throw new Exception("mauhcg:" + ex.Message);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// Client.OnLog("error:mtop_alimama_union_hsf_coupon_get->" + ex.Message);
|
||
}
|
||
|
||
return null;
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 优惠券结构类
|
||
/// </summary>
|
||
public class Coupon
|
||
{
|
||
/// <summary>
|
||
/// 优惠券状态,!=0表示优惠券失效或没有优惠券
|
||
/// </summary>
|
||
public int retStatus { get; set; }
|
||
|
||
/// <summary>
|
||
/// 使用条件
|
||
/// </summary>
|
||
public string startFee { get; set; }
|
||
|
||
/// <summary>
|
||
/// 使用金额
|
||
/// </summary>
|
||
public string amount { get; set; }
|
||
|
||
/// <summary>
|
||
/// 店铺Logo
|
||
/// </summary>
|
||
public string shopLogo { get; set; }
|
||
|
||
/// <summary>
|
||
/// 店铺名称
|
||
/// </summary>
|
||
public string shopName { get; set; }
|
||
|
||
/// <summary>
|
||
/// 使用时间
|
||
/// </summary>
|
||
public DateTime effectiveStartTime { get; set; }
|
||
|
||
/// <summary>
|
||
/// 活动截止时间
|
||
/// </summary>
|
||
public DateTime effectiveEndTime { get; set; }
|
||
|
||
/// <summary>
|
||
/// 点击下单
|
||
/// </summary>
|
||
public string clickUrl { get; set; }
|
||
|
||
/// <summary>
|
||
/// 分享地址
|
||
/// </summary>
|
||
public string shareUrl { get; set; }
|
||
|
||
/// <summary>
|
||
/// 软件标题
|
||
/// </summary>
|
||
public string title { get; set; }
|
||
|
||
/// <summary>
|
||
/// 原价
|
||
/// </summary>
|
||
public string reservePrice { get; set; }
|
||
|
||
/// <summary>
|
||
/// 折扣价格
|
||
/// </summary>
|
||
public string discountPrice { get; set; }
|
||
|
||
/// <summary>
|
||
/// 30天销量
|
||
/// </summary>
|
||
public int biz30Day { get; set; }
|
||
|
||
/// <summary>
|
||
/// 是否是天猫 ,1(是)
|
||
/// </summary>
|
||
public string tmall { get; set; }
|
||
|
||
/// <summary>
|
||
/// 未知参数
|
||
/// </summary>
|
||
public int postFree { get; set; }
|
||
|
||
/// <summary>
|
||
/// 宝贝ID
|
||
/// </summary>
|
||
public string itemId { get; set; }
|
||
|
||
/// <summary>
|
||
/// 未知参数
|
||
/// </summary>
|
||
public string couponFlowLimit { get; set; }
|
||
}
|
||
|
||
#region 私域数据异步绑定
|
||
|
||
/// <summary>
|
||
/// 淘宝eid绑定缓存
|
||
/// </summary>
|
||
public class TBEidExid
|
||
{
|
||
/// <summary>
|
||
/// 淘宝客外部用户标记,如自身系统账户ID;微信ID等
|
||
/// </summary>
|
||
public string special_id { get; set; }
|
||
|
||
/// <summary>
|
||
/// 失效时间
|
||
/// </summary>
|
||
public int dietime { get; set; }
|
||
|
||
/// <summary>
|
||
/// eid
|
||
/// </summary>
|
||
public string external_id { get; set; }
|
||
}
|
||
|
||
/// <summary>
|
||
/// 缓存
|
||
/// </summary>
|
||
private static Dictionary<string, List<TBEidExid>> TBEidExidList = new Dictionary<string, List<TBEidExid>>();
|
||
|
||
/// <summary>
|
||
/// 添加Eid缓存
|
||
/// </summary>
|
||
/// <param name="external_id">eid</param>
|
||
public void AddTBEid(string external_id)
|
||
{
|
||
try
|
||
{
|
||
if (!TBEidExidList.ContainsKey(Member.username))
|
||
TBEidExidList.Add(Member.username, new List<TBEidExid>());
|
||
var ext = TBEidExidList[Member.username].FirstOrDefault(f => f.external_id == external_id);
|
||
if (ext != null && ext.dietime < HttpExtend.GetTimeStamp(DateTime.Now))
|
||
{
|
||
TBEidExidList[Member.username].Remove(ext);
|
||
ext = null;
|
||
}
|
||
|
||
if (ext == null)
|
||
{
|
||
TBEidExidList[Member.username].Add(new TBEidExid()
|
||
{ external_id = external_id, dietime = HttpExtend.GetTimeStamp(DateTime.Now.AddMinutes(10)) });
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
}
|
||
}
|
||
|
||
private static Dictionary<string, string> RunEidSyncDic = new Dictionary<string, string>();
|
||
|
||
/// <summary>
|
||
/// 同步私域数据
|
||
/// </summary>
|
||
private static System.Threading.Timer timer =
|
||
new System.Threading.Timer(new TimerCallback(EidSync), null, 0, 1000 * 60 * 2);
|
||
|
||
private static TBHelper.TbAnalysis tbAnalysis = new TBHelper.TbAnalysis();
|
||
|
||
private static int runNum = 1;
|
||
|
||
/// <summary>
|
||
/// 同步私域数据
|
||
/// </summary>
|
||
/// <param name="state"></param>
|
||
private static void EidSync(object state)
|
||
{
|
||
try
|
||
{
|
||
if (!tbAnalysis.IsRunTBSiYu())
|
||
return;
|
||
runNum++;
|
||
|
||
if (TBEidExidList.Count == 0) return;
|
||
|
||
var cpsMembers = CpsClient.Members
|
||
.Where(f => f.cpstype == CpsType.阿里妈妈 && f.is_download == SwitchType.开启).ToList();
|
||
|
||
Task[] _task = new Task[cpsMembers.Count];
|
||
for (int i = 0; i < cpsMembers.Count; i++)
|
||
{
|
||
var cps = cpsMembers[i];
|
||
_task[i] = new Task(delegate
|
||
{
|
||
if (RunEidSyncDic.ContainsKey(cps.username))
|
||
return;
|
||
try
|
||
{
|
||
RunEidSyncDic.Add(cps.username, cps.username);
|
||
var api = CpsClient.CreateAlimamaRequest(cps);
|
||
if (!TBEidExidList.ContainsKey(cps.username) || TBEidExidList[cps.username].Count == 0)
|
||
return;
|
||
|
||
#region 删除过期的数据
|
||
|
||
if (runNum % 10 == 0)
|
||
{
|
||
try
|
||
{
|
||
var dieEidList = TBEidExidList[cps.username]
|
||
.Where(f => f.dietime < HttpExtend.GetTimeStamp(DateTime.Now)).ToList();
|
||
for (int q = 0; q < dieEidList.Count; q++)
|
||
{
|
||
TBEidExidList[cps.username].Remove(dieEidList[q]);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
TBEidExidList[cps.username] = TBEidExidList[cps.username]
|
||
.Where(f => f.dietime >= HttpExtend.GetTimeStamp(DateTime.Now)).ToList();
|
||
|
||
var arrList = tbAnalysis.FindTbPublisherInfoAll(api);
|
||
List<Dictionary<string, object>> dicList = new List<Dictionary<string, object>>();
|
||
foreach (Dictionary<string, object> item in arrList)
|
||
{
|
||
if (item.ContainsKey("external_id"))
|
||
dicList.Add(item);
|
||
}
|
||
|
||
var db = ApiClient.GetSession();
|
||
|
||
bool isUpdate = false;
|
||
for (int e = 0; e < TBEidExidList[cps.username].Count; e++)
|
||
{
|
||
try
|
||
{
|
||
var result = dicList.Where(z =>
|
||
z["external_id"].ToString() == TBEidExidList[cps.username][e].external_id)
|
||
.ToList();
|
||
if (result != null && result.Count != 0)
|
||
{
|
||
var count = result.Count;
|
||
if (count == 1)
|
||
{
|
||
var special_id = long.Parse(result[0]["special_id"].ToString());
|
||
var external_id = TBEidExidList[cps.username][e].external_id;
|
||
|
||
var relation = db.FindTbRelations().FirstOrDefault(f =>
|
||
f.special_id == special_id && f.cps_memberid == cps.username);
|
||
if (relation == null)
|
||
relation = new fl_tb_relation()
|
||
{ cps_memberid = cps.username, special_id = special_id };
|
||
if (relation.username != external_id)
|
||
{
|
||
isUpdate = true;
|
||
relation.username = external_id;
|
||
relation = db.Saveable(relation).ExecuteReturnEntity();
|
||
}
|
||
|
||
TBEidExidList[cps.username].Remove(TBEidExidList[cps.username][e]);
|
||
}
|
||
//else if (count > 1)
|
||
//{
|
||
// for (int w = 0; w < result.Count; w++)
|
||
// {
|
||
// dicList.Remove(result[w]);
|
||
// }
|
||
//}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
}
|
||
}
|
||
|
||
if (isUpdate)
|
||
db.FindTbRelations(true);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
EventClient.OnEvent("私域异步绑定", ex.Message);
|
||
}
|
||
finally
|
||
{
|
||
if (RunEidSyncDic.ContainsKey(cps.username))
|
||
RunEidSyncDic.Remove(cps.username);
|
||
}
|
||
});
|
||
_task[i].Start();
|
||
Thread.Sleep(1);
|
||
}
|
||
|
||
Task.WaitAll(_task);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
EventClient.OnEvent("", $"私域异步绑定异常:{ex.Message} - {ex.StackTrace}");
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
private const string SIGN_METHOD_MD5 = "md5";
|
||
private const string SIGN_METHOD_HMAC = "hmac";
|
||
|
||
private string SignTopRequest(Dictionary<string, string> parameters, string secret, string signMethod = "hmac")
|
||
{
|
||
// 第一步:把字典按Key的字母顺序排序
|
||
IDictionary<string, string> sortedParams =
|
||
new SortedDictionary<string, string>(parameters, StringComparer.Ordinal);
|
||
|
||
// 第二步:把所有参数名和参数值串在一起
|
||
StringBuilder query = new StringBuilder();
|
||
if (SIGN_METHOD_MD5.Equals(signMethod))
|
||
{
|
||
query.Append(secret);
|
||
}
|
||
|
||
foreach (KeyValuePair<string, string> kv in sortedParams)
|
||
{
|
||
if (!string.IsNullOrEmpty(kv.Key) && !string.IsNullOrEmpty(kv.Value) && kv.Key != "sign")
|
||
{
|
||
query.Append(kv.Key).Append(kv.Value);
|
||
}
|
||
}
|
||
|
||
//// 第三步:把请求主体拼接在参数后面
|
||
//if (!string.IsNullOrEmpty(body))
|
||
//{
|
||
// query.Append(body);
|
||
//}
|
||
|
||
// 第四步:使用MD5/HMAC加密
|
||
byte[] bytes;
|
||
if (SIGN_METHOD_HMAC.Equals(signMethod))
|
||
{
|
||
HMACMD5 hmac = new HMACMD5(Encoding.UTF8.GetBytes(secret));
|
||
bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
|
||
}
|
||
else
|
||
{
|
||
query.Append(secret);
|
||
MD5 md5 = MD5.Create();
|
||
bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
|
||
}
|
||
|
||
// 第五步:把二进制转化为大写的十六进制
|
||
StringBuilder result = new StringBuilder();
|
||
for (int i = 0; i < bytes.Length; i++)
|
||
{
|
||
result.Append(bytes[i].ToString("X2"));
|
||
}
|
||
|
||
return result.ToString();
|
||
}
|
||
|
||
private static DateTime servertime = DateTime.MinValue;
|
||
|
||
#region 老道重新修改
|
||
|
||
private static string tlj = "taobao.tbk.dg.vegas.tlj.create";
|
||
private static string[] not_session = new string[] { "taobao.tbk.item.info.get", tlj };
|
||
private static int[] server_port = new[] { 30001, 30002, 30003, 30004, 30005 };
|
||
|
||
/// <summary>
|
||
/// 计算签名,返回请求阿里妈妈服务器的参数
|
||
/// </summary>
|
||
/// <param name="_api">api名称</param>
|
||
/// <param name="_data">参数</param>
|
||
/// <param name="appkey">appkey</param>
|
||
/// <param name="appsecret">appsecret</param>
|
||
/// <returns></returns>
|
||
private string GetAlimamaRequestData(string _api, object _data, string appkey = "", string appsecret = "")
|
||
{
|
||
try
|
||
{
|
||
var data = _data;
|
||
var api = _api;
|
||
Dictionary<string, string> param = new Dictionary<string, string>();
|
||
var type = data.GetType().GetProperties();
|
||
|
||
foreach (var item in type)
|
||
{
|
||
var _value = item.GetValue(data).ToString();
|
||
param[item.Name] = _value;
|
||
}
|
||
|
||
var app_id = Token.appid;
|
||
var app_key = Token.appkey;
|
||
var accessToken = Token.access_token;
|
||
|
||
//#if DEBUG
|
||
// app_id = "33951412";
|
||
// app_key = "ab478e5a7332acee4ee3e4f56f70a6cb";
|
||
// accessToken = "6100412e139f270d8430132973d2e7cefbbb26be53653b12200733453642";
|
||
//#endif
|
||
|
||
|
||
//淘礼金接口
|
||
if (tlj == api)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(appkey)) throw new Exception("淘礼金appkey不能为空,终止淘礼金生成操作");
|
||
if (string.IsNullOrWhiteSpace(appsecret)) throw new Exception("淘礼金appsecret不能为空,终止淘礼金生成操作");
|
||
app_id = appkey;
|
||
app_key = appsecret;
|
||
}
|
||
|
||
param["method"] = api;
|
||
param["app_key"] = app_id;
|
||
if (!not_session.Contains(api))
|
||
param["session"] = accessToken;
|
||
|
||
//param["session"] = "7000010023374d0168aa5c8b8404a7d1de45cfb11ad3114891fccad8b7384c4d05d4e3c862677733";
|
||
param["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||
param["format"] = "json";
|
||
param["v"] = "2.0";
|
||
param["sign_method"] = "md5";
|
||
|
||
//计算签名
|
||
string sign = SignTopRequest(param, app_key, param["sign_method"]);
|
||
param["sign"] = sign;
|
||
return HttpExtend.BuildQuery(param);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
}
|
||
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 请求淘宝服务器端
|
||
/// </summary>
|
||
/// <param name="_api">api名称</param>
|
||
/// <param name="_data">参数</param>
|
||
/// <param name="appkey">appkey</param>
|
||
/// <param name="appsecret">appsecret</param>
|
||
/// <returns></returns>
|
||
private Dictionary<string, object> SendTaobaoServer(string _api, object _data, string _appkey = "",
|
||
string _appsecret = "")
|
||
{
|
||
var data = _data;
|
||
var api = _api;
|
||
var appkey = _appkey;
|
||
var appsecret = _appsecret;
|
||
int number = 0;
|
||
Next:
|
||
|
||
number++;
|
||
|
||
if (!Member.is_valid && !this.RefToken()) throw new Exception("授权状态已过期,请重新登陆阿里妈妈!");
|
||
var query = GetAlimamaRequestData(api, data, appkey, appsecret);
|
||
|
||
var html = string.Empty;
|
||
string _url = string.Empty;
|
||
try
|
||
{
|
||
HttpHelper http = new HttpHelper();
|
||
|
||
_url = "http://gw.api.taobao.com/router/rest?" + query;
|
||
|
||
if (servertime > DateTime.Now || (number > 2 && api == "taobao.tbk.item.info.get"))
|
||
{
|
||
try
|
||
{
|
||
var _item = http.GetItem(
|
||
$"http://jushita.api.52cmg.cn:{server_port[new Random().Next(0, server_port.Length)]}/api/http/gethtml",
|
||
"", $"url={HttpHelper.URLEncode(_url)}");
|
||
var _html = http.GetHtml(_item).Html;
|
||
//if (api == "taobao.tbk.sc.tpwd.convert") EventClient.OnEvent("解析日志", _html);
|
||
var _dic = HttpExtend.JsonToDictionary(_html);
|
||
if (_dic != null && _dic["Code"].ToString() == "0") html = _dic["Data"].ToString();
|
||
}
|
||
catch (Exception)
|
||
{
|
||
}
|
||
}
|
||
|
||
if (string.IsNullOrEmpty(html))
|
||
{
|
||
HttpItem item = new HttpItem()
|
||
{
|
||
URL = _url, //URL 必需项
|
||
Method = "GET", //URL 可选项 默认为Get
|
||
Timeout = 5000, //连接超时时间 可选项默认为100000
|
||
ReadWriteTimeout = 5000, //写入Post数据超时时间
|
||
Accept = "text/html, application/xhtml+xml, */*", // 可选项有默认值
|
||
ContentType = "application/json", //返回类型 可选项有默认值
|
||
};
|
||
var result = http.GetHtml(item);
|
||
//{"tbk_dg_vegas_tlj_create_response":{"result":{"model":{"rights_id":"XvLXNwkX8HBQ8VZ2WS4DlNtN7m9cS4TU","send_url":"https:\/\/uland.taobao.com\/taolijin\/edetail?eh=5L6pfx5vldOZuQF0XRz0iAXoB%2BDaBK5LQS0Flu%2FfbSp4QsdWMikAalrisGmre1Id0BFAqRODu1004PvI5lqUzYTPq7zN5TtBXU4J7X2wljh7PW2ShemY2x1IRRpXndAncj8tXpgtxXzbOKxKSviYxsuv0da8KKt7WubOUkoI2Oa3HR2hP0JFSmjppH3xlrrJg8pBHJnzzOjd2vZvO6fEydXbwx4naJ6dk%2FBu2lJxZtMc7BMk%2FDH7wY2fDQKPuN9qcxwaWpDoQwfi%2B9ZUBfurmaewy3GJqMoK4342DlvX1ZVNOJlvqrE2h6J7%2BkHL3AEW&union_lens=lensId%3A0b14fbf4_0b3d_16f65a622fd_31b4%3Btraffic_flag%3Dlm","vegas_code":"N4HHV6HV"},"success":true},"request_id":"no8k8bbwsct2"}}
|
||
html = result.Html;
|
||
if (result != null && result.StatusCode != System.Net.HttpStatusCode.OK)
|
||
throw new Exception(html);
|
||
}
|
||
|
||
//Console.WriteLine($"html = {html}");
|
||
var dic = HttpExtend.JsonToDictionary(html);
|
||
if (dic == null) throw new Exception(html);
|
||
if (dic.ContainsKey("error_response"))
|
||
throw new Exception(html);
|
||
|
||
var key = api.Replace("taobao.", "").Replace(".", "_") + "_response";
|
||
if (!dic.ContainsKey(key)) throw new Exception($"key = {key},html = {html}");
|
||
dic = dic[key] as Dictionary<String, object>;
|
||
if (dic.ContainsKey("result")) return dic["result"] as Dictionary<string, object>;
|
||
if (dic.ContainsKey("results")) return dic["results"] as Dictionary<string, object>;
|
||
return dic;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
var appId = Token?.appid;
|
||
|
||
#if DEBUG
|
||
appId = "33951412";
|
||
#endif
|
||
|
||
LogHelper.GetSingleObj().Error("AlimamaApi", $"api{api},appid={appId},url={_url}");
|
||
if (ex.Message.Contains("invalid-sessionkey"))
|
||
{
|
||
Thread.Sleep(1000);
|
||
if (this.Member != null && RefToken() && this.Member.is_valid) goto Next;
|
||
else throw new Exception($"{this.Member.username}({this.Member.usernick})授权状态已过期,请重新登陆阿里妈妈!");
|
||
}
|
||
else if (ex.Message.Contains("Platform System blacklist"))
|
||
{
|
||
servertime = DateTime.Now.AddMonths(5);
|
||
if (number > 3)
|
||
{
|
||
throw ex;
|
||
}
|
||
|
||
goto Next;
|
||
}
|
||
else if (number < 3 && (ex.Message.Contains("sub_msg\":\"无结果") ||
|
||
ex.Message.Contains("Invalid signature") ||
|
||
ex.Message.Contains("请求阿里妈妈API异常") || ex.Message.Contains("未将对象引用设置到对象的实例") ||
|
||
ex.Message.Contains("操作超时") ||
|
||
(!ex.Message.Contains("SessionKey非法") &&
|
||
!ex.Message.Contains("App Call Limited")) || Regex.Match(ex.Message,
|
||
@"(""error_response"":{""code"":15,""msg"":""Remote service error"",""sub_code"":)|(操作超时)|(基础连接已经关闭)|(远程服务调用超时)|(淘宝客API服务不可用)|(HSF执行错误)")
|
||
.Success))
|
||
{
|
||
if ((ex.Message.Contains("该item_id对应宝贝已下架或非淘客宝贝") || ex.Message.Contains("sub_msg\":\"无结果")) &&
|
||
number > 1) //重试两次就直接抛出
|
||
throw ex;
|
||
Thread.Sleep(100);
|
||
goto Next;
|
||
}
|
||
else if (ex.Message.Contains("sub_msg\":\"无结果") || ex.Message.Contains("sub_msg\":\"淘口令解析结果为空") ||
|
||
ex.Message.Contains("sub_msg\":\"口令跳转url不支持口令转换"))
|
||
throw ex;
|
||
else
|
||
{
|
||
//EventClient.OnEvent(this,$@"cce:{_api.Replace("taobao.tbk.", "").Replace(".", "")} => {ex.Message} - {ex.StackTrace}
|
||
//html => {html}");
|
||
if (ex.Message.Contains("Invalid signature"))
|
||
throw new Exception($"{this.Member.username}({this.Member.usernick})Invalid signature,请求异常");
|
||
else
|
||
{
|
||
if (ex.Message.Contains("Insufficient isv permissions"))
|
||
throw new Exception(
|
||
$"{this.Member.username}({this.Member.usernick}) isv权限不足~!处理方法:1.请检测阿里妈妈权限 2.重新登陆阿里妈妈重试");
|
||
throw new Exception($"{this.Member.username}({this.Member.usernick})请求阿里妈妈接口:" + ex.Message +
|
||
" - " + ex.StackTrace);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 请求淘宝服务器端
|
||
/// </summary>
|
||
/// <param name="_api">api名称</param>
|
||
/// <param name="_data">参数</param>
|
||
/// <param name="appkey">appkey</param>
|
||
/// <param name="appsecret">appsecret</param>
|
||
/// <returns></returns>
|
||
private JToken SendTaobaoServerJToken(string _api, object _data, string _appkey = "", string _appsecret = "")
|
||
{
|
||
var data = _data;
|
||
var api = _api;
|
||
var appkey = _appkey;
|
||
var appsecret = _appsecret;
|
||
int number = 0;
|
||
Next:
|
||
|
||
number++;
|
||
|
||
if (!Member.is_valid && !this.RefToken()) throw new Exception("授权状态已过期,请重新登陆阿里妈妈!");
|
||
var query = GetAlimamaRequestData(api, data, appkey, appsecret);
|
||
|
||
var html = string.Empty;
|
||
string _url = string.Empty;
|
||
try
|
||
{
|
||
HttpHelper http = new HttpHelper();
|
||
|
||
_url = "http://gw.api.taobao.com/router/rest?" + query;
|
||
|
||
if (servertime > DateTime.Now || (number > 2 && api == "taobao.tbk.item.info.get"))
|
||
{
|
||
try
|
||
{
|
||
var _item = http.GetItem(
|
||
$"http://jushita.api.52cmg.cn:{server_port[new Random().Next(0, server_port.Length)]}/api/http/gethtml",
|
||
"", $"url={HttpHelper.URLEncode(_url)}");
|
||
var _html = http.GetHtml(_item).Html;
|
||
//if (api == "taobao.tbk.sc.tpwd.convert") EventClient.OnEvent("解析日志", _html);
|
||
var _dic = HttpExtend.JsonToDictionary(_html);
|
||
if (_dic != null && _dic["Code"].ToString() == "0") html = _dic["Data"].ToString();
|
||
}
|
||
catch (Exception)
|
||
{
|
||
}
|
||
}
|
||
|
||
if (string.IsNullOrEmpty(html))
|
||
{
|
||
HttpItem item = new HttpItem()
|
||
{
|
||
URL = _url, //URL 必需项
|
||
Method = "GET", //URL 可选项 默认为Get
|
||
Timeout = 5000, //连接超时时间 可选项默认为100000
|
||
ReadWriteTimeout = 5000, //写入Post数据超时时间
|
||
Accept = "text/html, application/xhtml+xml, */*", // 可选项有默认值
|
||
ContentType = "application/json", //返回类型 可选项有默认值
|
||
};
|
||
var result = http.GetHtml(item);
|
||
//{"tbk_dg_vegas_tlj_create_response":{"result":{"model":{"rights_id":"XvLXNwkX8HBQ8VZ2WS4DlNtN7m9cS4TU","send_url":"https:\/\/uland.taobao.com\/taolijin\/edetail?eh=5L6pfx5vldOZuQF0XRz0iAXoB%2BDaBK5LQS0Flu%2FfbSp4QsdWMikAalrisGmre1Id0BFAqRODu1004PvI5lqUzYTPq7zN5TtBXU4J7X2wljh7PW2ShemY2x1IRRpXndAncj8tXpgtxXzbOKxKSviYxsuv0da8KKt7WubOUkoI2Oa3HR2hP0JFSmjppH3xlrrJg8pBHJnzzOjd2vZvO6fEydXbwx4naJ6dk%2FBu2lJxZtMc7BMk%2FDH7wY2fDQKPuN9qcxwaWpDoQwfi%2B9ZUBfurmaewy3GJqMoK4342DlvX1ZVNOJlvqrE2h6J7%2BkHL3AEW&union_lens=lensId%3A0b14fbf4_0b3d_16f65a622fd_31b4%3Btraffic_flag%3Dlm","vegas_code":"N4HHV6HV"},"success":true},"request_id":"no8k8bbwsct2"}}
|
||
html = result.Html;
|
||
if (result != null && result.StatusCode != System.Net.HttpStatusCode.OK)
|
||
throw new Exception(html);
|
||
}
|
||
|
||
var jsonResult = JObject.Parse(html);
|
||
if (jsonResult == null)
|
||
throw new Exception(html);
|
||
|
||
var jToken = jsonResult.First?.First;
|
||
if (jToken != null)
|
||
{
|
||
if (jToken["code"] != null)
|
||
throw new Exception(jToken.ToString());
|
||
if (jToken["results"] != null)
|
||
return jToken["results"];
|
||
if (jToken["result"] != null)
|
||
{
|
||
var jTokenResult = jToken["result"];
|
||
return (jTokenResult["data"] ?? jTokenResult);
|
||
}
|
||
if (jToken["data"] != null)
|
||
return jToken["data"];
|
||
}
|
||
return jToken;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
var appId = Token.appid;
|
||
|
||
LogHelper.GetSingleObj().Error("AlimamaApi", $"api{api},appid={appId},url={_url}");
|
||
if (ex.Message.Contains("invalid-sessionkey"))
|
||
{
|
||
Thread.Sleep(1000);
|
||
if (this.Member != null && RefToken() && this.Member.is_valid) goto Next;
|
||
else throw new Exception($"{this.Member.username}({this.Member.usernick})授权状态已过期,请重新登陆阿里妈妈!");
|
||
}
|
||
else if (ex.Message.Contains("Platform System blacklist"))
|
||
{
|
||
servertime = DateTime.Now.AddMonths(5);
|
||
if (number > 3)
|
||
{
|
||
throw ex;
|
||
}
|
||
|
||
goto Next;
|
||
}
|
||
else if (number < 3 && (ex.Message.Contains("sub_msg\":\"无结果") ||
|
||
ex.Message.Contains("Invalid signature") ||
|
||
ex.Message.Contains("请求阿里妈妈API异常") || ex.Message.Contains("未将对象引用设置到对象的实例") ||
|
||
ex.Message.Contains("操作超时") ||
|
||
(!ex.Message.Contains("SessionKey非法") &&
|
||
!ex.Message.Contains("App Call Limited")) || Regex.Match(ex.Message,
|
||
@"(""error_response"":{""code"":15,""msg"":""Remote service error"",""sub_code"":)|(操作超时)|(基础连接已经关闭)|(远程服务调用超时)|(淘宝客API服务不可用)|(HSF执行错误)")
|
||
.Success))
|
||
{
|
||
if ((ex.Message.Contains("该item_id对应宝贝已下架或非淘客宝贝") || ex.Message.Contains("sub_msg\":\"无结果")) &&
|
||
number > 1) //重试两次就直接抛出
|
||
throw ex;
|
||
Thread.Sleep(100);
|
||
goto Next;
|
||
}
|
||
else if (ex.Message.Contains("sub_msg\":\"无结果") || ex.Message.Contains("sub_msg\":\"淘口令解析结果为空") ||
|
||
ex.Message.Contains("sub_msg\":\"口令跳转url不支持口令转换"))
|
||
throw ex;
|
||
else
|
||
{
|
||
//EventClient.OnEvent(this,$@"cce:{_api.Replace("taobao.tbk.", "").Replace(".", "")} => {ex.Message} - {ex.StackTrace}
|
||
//html => {html}");
|
||
if (ex.Message.Contains("Invalid signature"))
|
||
throw new Exception($"{this.Member.username}({this.Member.usernick})Invalid signature,请求异常");
|
||
else
|
||
{
|
||
if (ex.Message.Contains("Insufficient isv permissions"))
|
||
throw new Exception(
|
||
$"{this.Member.username}({this.Member.usernick}) isv权限不足~!处理方法:1.请检测阿里妈妈权限 2.重新登陆阿里妈妈重试");
|
||
throw new Exception($"{this.Member.username}({this.Member.usernick})请求阿里妈妈接口:" + ex.Message +
|
||
" - " + ex.StackTrace);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 淘礼金调用
|
||
/// </summary>
|
||
/// <param name="_api">api名称</param>
|
||
/// <param name="_data">参数</param>
|
||
/// <param name="_appkey">appkey</param>
|
||
/// <param name="_appsecret">appsecret</param>
|
||
/// <returns></returns>
|
||
public Dictionary<string, object> SendTaobao(string _api, object _data, string _appkey = "",
|
||
string _appsecret = "")
|
||
{
|
||
var data = _data;
|
||
var api = _api;
|
||
var appkey = _appkey;
|
||
var appsecret = _appsecret;
|
||
|
||
return SendTaobaoServer(api, data, appkey, appsecret);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 发送阿里妈妈报文
|
||
/// </summary>
|
||
/// <param name="_api">api名称</param>
|
||
/// <param name="_data">参数</param>
|
||
/// <returns></returns>
|
||
public Dictionary<string, object> SendTaobao(string _api, object _data)
|
||
{
|
||
var data = _data;
|
||
var api = _api;
|
||
|
||
return SendTaobaoServer(api, data);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 发送阿里妈妈报文
|
||
/// </summary>
|
||
/// <param name="_api">api名称</param>
|
||
/// <param name="_data">参数</param>
|
||
/// <returns></returns>
|
||
public T SendTaobao<T>(string _api, object _data)
|
||
{
|
||
var data = _data;
|
||
var api = _api;
|
||
|
||
return SendTaobaoServerJToken(api, data).ToObject<T>();
|
||
}
|
||
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 解析淘口令
|
||
/// </summary>
|
||
/// <param name="password"></param>
|
||
/// <param name="adzoneId"></param>
|
||
/// <param name="siteId"></param>
|
||
/// <returns></returns>
|
||
public TBPassInfoData AnalysisTkPassword(string password, string adzoneId, string siteId)
|
||
{
|
||
var data = SendTaobao<TBPassInfoData>("taobao.tbk.sc.tpwd.convert",
|
||
new { password_content = password, adzone_id = adzoneId, site_id = siteId });
|
||
return data;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析链接 (长短链接 s.click.taobao)
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <returns></returns>
|
||
public AnalysisTkUrlData AnalysisTkUrl(string url, string bizSceneId)
|
||
{
|
||
var result = SendTaobao<AnalysisTkUrlData>("taobao.tbk.item.click.extract", new { click_url = url, biz_scene_id = bizSceneId });
|
||
|
||
return result;
|
||
}
|
||
|
||
|
||
public TBItemInfoData TurnItemId(string itemId, string activityId, string adzoneId, string siteId,
|
||
string bizSceneId, string specialId = "", bool isCircle = false)
|
||
{
|
||
try
|
||
{
|
||
bizSceneId = TBHelper.TbAnalysis.BizSceneId(itemId);
|
||
|
||
object transportData;
|
||
if (!string.IsNullOrWhiteSpace(specialId))
|
||
transportData = new { adzone_id = adzoneId, site_id = siteId, item_id = itemId, special_id = specialId, biz_scene_id = bizSceneId };
|
||
else
|
||
transportData = new { adzone_id = adzoneId, site_id = siteId, item_id = itemId, biz_scene_id = bizSceneId };
|
||
|
||
var queryItemDataResult = GetItemInfo(itemId, bizSceneId);
|
||
|
||
if (queryItemDataResult == null)
|
||
{
|
||
throw new Exception("商品基础信息查询失败");
|
||
}
|
||
|
||
if (queryItemDataResult.n_tbk_item == null || queryItemDataResult.n_tbk_item.Count <= 0)
|
||
{
|
||
throw new Exception("商品基础信息查询失败");
|
||
}
|
||
|
||
var queryItemData = queryItemDataResult.n_tbk_item[0];
|
||
|
||
if (queryItemData == null)
|
||
{
|
||
throw new Exception("商品基础信息查询失败");
|
||
}
|
||
|
||
var jToken = SendTaobaoServerJToken("taobao.tbk.privilege.get", transportData);
|
||
if (jToken != null)
|
||
{
|
||
var item = new TBItemInfoData()
|
||
{
|
||
ItemId = queryItemData.num_iid,
|
||
//BuyPass = string.Empty,
|
||
BuyUrl = jToken["coupon_click_url"]?.Value<string>() ?? jToken["item_url"]?.Value<string>(),
|
||
CommissionRatio = (jToken["max_commission_rate"]?.Value<decimal>() ?? 0).ExecDivision(100, 4),
|
||
//CouponUrl = jToken["coupon_click_url"]?.ToString(),
|
||
ImageUrl = queryItemData.pict_url,
|
||
ItemTitle = queryItemData.title,
|
||
ItemUrl = queryItemData.item_url,
|
||
Price = decimal.Parse(queryItemData.zk_final_price),
|
||
Sales = queryItemData.volume,
|
||
ShopId = queryItemData.seller_id.ToString(),
|
||
ShopNick = queryItemData.nick,
|
||
IsTip = true,
|
||
ActivityId = activityId
|
||
};
|
||
|
||
GetCouponInfo(jToken, item);
|
||
|
||
var tklResult = SendTaobaoServerJToken("taobao.tbk.tpwd.create", new { url = item.BuyUrl });
|
||
var regResult = HttpExtend.RegexMatchUrl(tklResult["model"]?.Value<string>());
|
||
if (!string.IsNullOrWhiteSpace(regResult))
|
||
{
|
||
item.BuyUrl = regResult.Replace("m.tb", "s.tb");
|
||
}
|
||
|
||
item.BuyPass = tklResult["password_simple"]?.Value<string>();
|
||
|
||
//朋友圈中间页
|
||
var zjyResult = ComposeTbClick(itemId, item.ImageUrl, item.BuyPass, item.BuyUrl, adzoneId, true, isCircleZjy: isCircle);
|
||
if (zjyResult != null)
|
||
{
|
||
item.ZJYUrl = zjyResult;
|
||
}
|
||
|
||
return item;
|
||
}
|
||
throw new Exception("商品链接失败");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw new Exception($"转连商品信息异常:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取商品信息
|
||
/// </summary>
|
||
/// <param name="itemId"></param>
|
||
/// <param name="bizSceneId"></param>
|
||
/// <returns></returns>
|
||
public GetItemInfosData GetItemInfo(string itemId, string bizSceneId)
|
||
{
|
||
bizSceneId = TBHelper.TbAnalysis.BizSceneId(itemId);
|
||
|
||
var result = SendTaobao<GetItemInfosData>("taobao.tbk.item.info.get", new { num_iids = itemId, biz_scene_id = bizSceneId });
|
||
return result;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 获取优惠券信息
|
||
/// </summary>
|
||
/// <param name="data"></param>
|
||
/// <param name="infoData"></param>
|
||
private void GetCouponInfo(JToken data, TBItemInfoData infoData)
|
||
{
|
||
//优惠券地址
|
||
//var couponUrl = data["item_url"]?.ToString();
|
||
var couponUrl = data["coupon_click_url"]?.Value<string>() ?? data["item_url"]?.ToString();
|
||
|
||
if (!string.IsNullOrWhiteSpace(infoData.ActivityId))
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(couponUrl))
|
||
{
|
||
couponUrl = Regex.Replace(couponUrl, @"&?activityId=(?<活动ID>[A-Za-z0-9]+)", "");
|
||
}
|
||
|
||
infoData.CouponUrl = couponUrl = $"{couponUrl}&activityId={infoData.ActivityId}";
|
||
|
||
var activityData = GetActivityInfo(infoData.ItemId, infoData.ActivityId);
|
||
if (activityData != null)
|
||
{
|
||
if (activityData.ConditionPrice <= infoData.Price)
|
||
{
|
||
infoData.CouponPrice = activityData.CouponPrice;
|
||
infoData.UseCouponPrice = infoData.Price - infoData.CouponPrice;
|
||
}
|
||
infoData.BuyUrl = couponUrl;
|
||
}
|
||
return;
|
||
}
|
||
|
||
//妈妈券
|
||
var mmCouponInfo = data["mm_coupon_info"];
|
||
//普通券
|
||
var couponInfo = data["coupon_info"];
|
||
|
||
List<CouponData> couponList = new List<CouponData>();
|
||
|
||
//普通优惠券
|
||
if (couponInfo != null)
|
||
{
|
||
var coupon = new CouponData();
|
||
|
||
var quanReg = Regex.Match(data["coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
|
||
if (quanReg.Success)
|
||
{
|
||
coupon.CouponPrice = decimal.Parse(quanReg.Groups["减"].Value);
|
||
coupon.ConditionPrice = decimal.Parse(quanReg.Groups["满"].Value);
|
||
couponUrl = coupon.CouponUrl = data["coupon_click_url"].ToString();
|
||
|
||
couponList.Add(coupon);
|
||
}
|
||
}
|
||
|
||
//妈妈优惠券
|
||
if (mmCouponInfo != null)
|
||
{
|
||
var coupon = new CouponData();
|
||
|
||
var mmQuanReg = Regex.Match(data["mm_coupon_info"].ToString(), @"满(?<满>\d+)元减(?<减>\d+)元");
|
||
if (mmQuanReg.Success)
|
||
{
|
||
coupon.CouponPrice = decimal.Parse(mmQuanReg.Groups["减"].Value);
|
||
coupon.ConditionPrice = decimal.Parse(mmQuanReg.Groups["满"].Value);
|
||
couponUrl = coupon.CouponUrl = data["mm_coupon_click_url"].ToString();
|
||
|
||
couponList.Add(coupon);
|
||
}
|
||
}
|
||
|
||
//获取其他优惠券Id信息
|
||
if (string.IsNullOrWhiteSpace(infoData.ActivityId) == false)
|
||
{
|
||
var activityData = GetActivityInfo(infoData.ItemId, infoData.ActivityId);
|
||
if (activityData != null)
|
||
{
|
||
couponList.Add(activityData);
|
||
}
|
||
}
|
||
//将优惠券排序
|
||
couponList.Sort(new CouponDataComparer());
|
||
|
||
//获取一个符合的优惠券
|
||
var couponData = couponList.FirstOrDefault(f => f.ConditionPrice <= infoData.Price);
|
||
if (couponData != null)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(couponData.ActivityId))
|
||
{
|
||
couponUrl = couponData.CouponUrl = $"{couponUrl}&activityId={couponData.ActivityId}";
|
||
}
|
||
infoData.CouponPrice = couponData.CouponPrice;
|
||
infoData.UseCouponPrice = infoData.Price - infoData.CouponPrice;
|
||
}
|
||
else//没有优惠券
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(infoData.ActivityId))
|
||
{
|
||
couponUrl = $"{couponUrl}&activityId={infoData.ActivityId}";
|
||
}
|
||
|
||
infoData.CouponPrice = 0m;
|
||
infoData.UseCouponPrice = infoData.Price;
|
||
infoData.BuyUrl = couponUrl;
|
||
}
|
||
|
||
infoData.CouponUrl = couponUrl;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取优惠券Id的信息
|
||
/// </summary>
|
||
/// <param name="itemId">商品Id</param>
|
||
/// <param name="activityId">优惠券活动Id</param>
|
||
public CouponData GetActivityInfo(string itemId, string activityId)
|
||
{
|
||
try
|
||
{
|
||
var jToken = SendTaobaoServerJToken("taobao.tbk.coupon.get", new { activity_id = activityId, item_id = itemId });
|
||
|
||
if ((jToken["coupon_remain_count"]?.Value<int>() ?? 0) == 0)
|
||
{
|
||
throw new Exception("优惠券已经无效");
|
||
}
|
||
|
||
var coupon = new CouponData();
|
||
coupon.ConditionPrice = jToken["coupon_start_fee"]?.Value<decimal>() ?? 0;
|
||
coupon.CouponPrice = jToken["coupon_amount"]?.Value<decimal>() ?? 0;
|
||
coupon.ActivityId = jToken["coupon_activity_id"]?.ToString();
|
||
|
||
return coupon;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 校验阿里妈妈cookiecs是否有效
|
||
/// </summary>
|
||
/// <param name="cookies">cookies</param>
|
||
/// <returns></returns>
|
||
public static Dictionary<string, object> GetUnionPubContextInfo(string cookies)
|
||
{
|
||
var http = new HttpHelper();
|
||
var item = http.GetItem("https://www.alimama.com/getLogInfo.htm?callback=__jp0", cookies);
|
||
var html = http.GetHtml(item).Html;
|
||
html = html.Replace("__jp0(", "").Replace(")", "");
|
||
var result =
|
||
HttpHelper.JsonToObject<Dictionary<string, object>>(html.Replace("__jp0", "").Replace(")", "")) as
|
||
Dictionary<string, object>;
|
||
if (result != null && result.ContainsKey("result"))
|
||
{
|
||
return result["result"] as Dictionary<string, object>;
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 订单类型
|
||
/// </summary>
|
||
public enum OrderType
|
||
{
|
||
淘客订单明细 = 1,
|
||
第三方订单明细 = 2,
|
||
维权退款明细 = 3
|
||
}
|
||
|
||
/// <summary>
|
||
/// 判断是否是天猫商品
|
||
/// </summary>
|
||
/// <param name="itemid">商品id</param>
|
||
/// <returns></returns>
|
||
public bool IsTianmao(string itemid)
|
||
{
|
||
var html = GetAlimamaHtml("https://detail.tmall.com/item.htm?id=" + itemid);
|
||
if (html.Contains("天猫Tmall.com") || html.Contains("tmallBuySupport=true")) return true;
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 爬虫 - 从阿里妈妈官网提取订单
|
||
/// </summary>
|
||
/// <param name="type">爬取的订单类型</param>
|
||
/// <param name="queryType">写0吧</param>
|
||
/// <param name="payStatus">写空吧</param>
|
||
/// <param name="maxSize">最大1000</param>
|
||
/// <param name="day">不能操作90天最好少于90天</param>
|
||
/// <param name="toPage">第几页</param>
|
||
/// <returns></returns>
|
||
public List<Dictionary<string, object>> SerchOrder(OrderType type, int queryType, string payStatus, int maxSize,
|
||
DateTime day, int toPage)
|
||
{
|
||
List<Dictionary<string, object>> rst = new List<Dictionary<string, object>>();
|
||
//string url = "http://pub.alimama.com/report/getTbkPaymentDetails.json?startTime=" + start.ToString("yyyy-MM-dd") + "&endTime=" + end.ToString("yyyy-MM-dd") + "&payStatus="+(all?"":"3")+"&queryType=" + (all ? "1" : "3") + "&toPage=1&perPageSize=" + maxSize + "&total=&t=" + Tools.ConvertDateTimeInt(DateTime.Now).ToString() + "&_tb_token_=" + this.GetKey("tb_token") + "&_input_charset=utf-8";
|
||
//pub.alimama.com/report/getTbkThirdPaymentDetails
|
||
try
|
||
{
|
||
|
||
string url = string.Empty;
|
||
if (type == OrderType.淘客订单明细) //淘客订单明细
|
||
//url = "https://pub.alimama.com/report/getTbkPaymentDetails.json?startTime=" + day.ToString("yyyy-MM-dd") + "&endTime=" + DateTime.Now.ToString("yyyy-MM-dd") + "&payStatus=" + payStatus + "&queryType=" + queryType + "&toPage=" + toPage + "&perPageSize=" + maxSize + "&total=&_input_charset=utf-8";
|
||
url = "https://pub.alimama.com/report/getTbkPaymentDetails.json?startTime=" +
|
||
day.ToString("yyyy-MM-dd") + "&endTime=" + DateTime.Now.ToString("yyyy-MM-dd") +
|
||
"&payStatus=" + payStatus + "&queryType=" + queryType + "&toPage=" + toPage +
|
||
"&perPageSize=" + maxSize + "&total=&_input_charset=utf-8";
|
||
else if (type == OrderType.第三方订单明细) //第三方订单明细
|
||
//url = "https://pub.alimama.com/report/getTbkThirdPaymentDetails.json?startTime=" + day.ToString("yyyy-MM-dd") + "&endTime=" + DateTime.Now.ToString("yyyy-MM-dd") + "&payStatus=" + payStatus + "&queryType=" + queryType + "&toPage=" + toPage + "&perPageSize=" + maxSize + "&total=&_input_charset=utf-8";
|
||
url = "https://pub.alimama.com/report/getTbkThirdPaymentDetails.json?startTime=" +
|
||
day.ToString("yyyy-MM-dd") + "&endTime=" + DateTime.Now.ToString("yyyy-MM-dd") +
|
||
"&payStatus=" + payStatus + "&queryType=" + queryType + "&toPage=" + toPage +
|
||
"&perPageSize=" + maxSize + "&total=&_input_charset=utf-8";
|
||
else if (type == OrderType.维权退款明细)
|
||
{
|
||
//url = "https://pub.alimama.com/report/getNewTbkRefundPaymentDetails.json?startTime=" + day.ToString("yyyy-MM-dd") + "&endTime=" + DateTime.Now.ToString("yyyy-MM-dd") + "&refundType=1&searchType=1&toPage=1&perPageSize=" + maxSize + "&_input_charset=utf-8";
|
||
|
||
//url = $"https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.getTbkRefundOrderDetails.json?pageNo={toPage}&startTime={day.ToString("yyyy-MM-dd")}&endTime={DateTime.Now.ToString("yyyy-MM-dd")}&queryType=1&isFullRefund=0&memberType=1&pageSize={maxSize}";
|
||
|
||
var tbToken = GetTbToken();
|
||
if (string.IsNullOrWhiteSpace(tbToken))
|
||
{
|
||
return rst;
|
||
}
|
||
|
||
url =
|
||
$"https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.publisher.getRefundOrderDetail.json?t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&{tbToken}&pageNo={toPage}&pageSize={maxSize}&startTime={day.ToString("yyyy-MM-dd")}&endTime={DateTime.Now.ToString("yyyy-MM-dd")}&payStatus=&queryType=1&jumpType=0&isFullRefund=0&memberType=&positionIndex=";
|
||
|
||
//"https://pub.alimama.com/report/getNewTbkRefundPaymentDetails.json?startTime=" + day.ToString("yyyy-MM-dd") + "&endTime=" + DateTime.Now.ToString("yyyy-MM-dd") + "&refundType=1&searchType=1&toPage=" + toPage + "&perPageSize=" + maxSize + "&_input_charset=utf-8";
|
||
}
|
||
string html = GetAlimamaHtml(url);
|
||
if (html.Contains("<title>阿里妈妈</title>"))
|
||
{
|
||
Member.online = false;
|
||
var session = ApiClient.GetSession();
|
||
session.SaveOrUpdate(Member);
|
||
}
|
||
|
||
Dictionary<string, object> dic = HttpExtend.JsonToDictionary(html);
|
||
if (dic != null && dic.ContainsKey("data"))
|
||
{
|
||
dic = dic["data"] as Dictionary<string, object>;
|
||
if (dic != null && dic.ContainsKey("result"))
|
||
{
|
||
var list = dic["result"] as ArrayList;
|
||
var _rst = new List<Dictionary<string, object>>();
|
||
foreach (Dictionary<string, object> item in list) _rst.Add(item);
|
||
|
||
_rst = _rst.OrderByDescending(a => DateTime.Parse(a["refundCreateTime"].ToString()))
|
||
.ToList(); //降序
|
||
foreach (var item in _rst)
|
||
{
|
||
var _item = rst.FirstOrDefault(f =>
|
||
f["tbTradeId"].ToString() == item["tbTradeId"].ToString() &&
|
||
f["tbTradeParentId"].ToString() == item["tbTradeParentId"].ToString());
|
||
if (_item == null)
|
||
rst.Add(item);
|
||
}
|
||
|
||
}
|
||
}
|
||
}
|
||
catch (Exception wz)
|
||
{
|
||
// client.SendLogEvent("AliSerchOrder异常:" + ex.Message);
|
||
}
|
||
|
||
return rst;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 爬虫 - 从阿里妈妈官网提取维权订单
|
||
/// </summary>
|
||
/// <param name="type">爬取的订单类型</param>
|
||
/// <param name="queryType">写0吧</param>
|
||
/// <param name="payStatus">写空吧</param>
|
||
/// <param name="maxSize">最大1000</param>
|
||
/// <param name="day">不能操作90天最好少于90天</param>
|
||
/// <param name="toPage">第几页</param>
|
||
/// <returns></returns>
|
||
public void RefundOrder(DateTime startTime, Func<JToken, bool> callback)
|
||
{
|
||
var html = string.Empty;
|
||
try
|
||
{
|
||
var tbToken = GetTbToken();
|
||
if (string.IsNullOrWhiteSpace(tbToken))
|
||
{
|
||
return;
|
||
}
|
||
|
||
var pageIndex = 1;
|
||
var pageSize = 1000;
|
||
var positionIndex = string.Empty;
|
||
bool hasNext = false;
|
||
|
||
do
|
||
{
|
||
var url = $"https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.publisher.getRefundOrderDetail.json?t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&_tb_token_={tbToken}&pageNo={pageIndex}&pageSize={pageSize}&startTime={startTime:yyyy-MM-dd}&endTime={DateTime.Now:yyyy-MM-dd}&payStatus=&queryType=1&jumpType={(string.IsNullOrWhiteSpace(positionIndex) ? 0 : 1)}&isFullRefund=0&memberType=&positionIndex=" + positionIndex;
|
||
|
||
html = GetAlimamaHtml(url);
|
||
if (html.Contains("<title>阿里妈妈</title>"))
|
||
{
|
||
Member.online = false;
|
||
var session = ApiClient.GetSession();
|
||
session.SaveOrUpdate(Member);
|
||
}
|
||
var json = JObject.Parse(html);
|
||
|
||
if (json["resultCode"]?.Value<int>() != 200 || json["success"]?.Value<bool>() != true || json["data"] == null)
|
||
{
|
||
Sleep();
|
||
continue;
|
||
}
|
||
|
||
var data = json["data"];
|
||
if (data == null)
|
||
{
|
||
Sleep();
|
||
continue;
|
||
}
|
||
|
||
positionIndex = data["positionIndex"]?.ToString();
|
||
hasNext = data["hasNext"]?.ToObject<bool>() ?? false;
|
||
var result = data["result"];
|
||
if (result == null || !result.Any())
|
||
{
|
||
break;
|
||
}
|
||
callback(result);
|
||
if (hasNext)
|
||
{
|
||
Sleep();
|
||
pageIndex++;
|
||
}
|
||
} while (hasNext);
|
||
}
|
||
catch (Exception wz)
|
||
{
|
||
// client.SendLogEvent("AliSerchOrder异常:" + ex.Message);
|
||
}
|
||
}
|
||
|
||
private void Sleep(int seconds = 2)
|
||
{
|
||
Thread.Sleep(1000 * seconds);
|
||
}
|
||
|
||
private string create_scorder_url(Dictionary<string, object> infos, string start_time, int page, int tk_status,
|
||
string order_query_type, string fields = "")
|
||
{
|
||
var parameters = new Dictionary<string, string>();
|
||
parameters["fields"] = string.IsNullOrEmpty(fields)
|
||
? "tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,relation_id,tk_status,earning_time"
|
||
: fields;
|
||
parameters["method"] = "taobao.tbk.sc.order.get";
|
||
parameters["start_time"] = start_time;
|
||
parameters["span"] = "1200";
|
||
parameters["page_no"] = page.ToString();
|
||
parameters["page_size"] = "100";
|
||
parameters["tk_status"] = tk_status.ToString();
|
||
parameters["order_query_type"] = order_query_type;
|
||
parameters["app_key"] = infos["key"].ToString();
|
||
parameters["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||
parameters["format"] = "json";
|
||
parameters["v"] = "2.0";
|
||
parameters["sign_method"] = "md5";
|
||
//计算签名
|
||
string sign = SignTopRequest(parameters, infos["secret"].ToString(), parameters["sign_method"]);
|
||
parameters["sign"] = sign;
|
||
string query = HttpExtend.BuildQuery(parameters);
|
||
return "http://gw.api.taobao.com/router/rest?" + query;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 下载订单,带状态(有多页,获取所有)
|
||
/// </summary>
|
||
/// <param name="start_time">开始时间</param>
|
||
/// <param name="_page_index">第几页</param>
|
||
/// <param name="page_size">页大小</param>
|
||
/// <param name="tk_status">同步的订单状态</param>
|
||
/// <param name="type">阿里妈妈同步的订单类型</param>
|
||
/// <param name="order_scene">场景订单场景类型,1:常规订单,2:渠道订单,3:会员运营订单,默认为1</param>
|
||
/// <returns></returns>
|
||
internal ArrayList DownOrder(DateTime start_time, int _page_index, int page_size, AlimamaOrderStatus tk_status,
|
||
AlimamaOrderType type, int order_scene)
|
||
{
|
||
#region 2021-08-04之后 新接口 第三版(按照订单更新时间)
|
||
|
||
var interval = DownAlimamaTimer.GetIntervalCache(); //这个是三个小时的间隔 如果报错就用19分钟的间隔,默认179
|
||
ArrayList array = new ArrayList();
|
||
try
|
||
{
|
||
object obj = null;
|
||
var page_index = _page_index;
|
||
Dictionary<string, object> _rst = null;
|
||
for (int i = 0; i < 2; i++)
|
||
{
|
||
try
|
||
{
|
||
obj = new
|
||
{
|
||
query_type = 4, //查询时间类型,1:按照订单淘客创建时间查询,2:按照订单淘客付款时间查询,3:按照订单淘客结算时间查询,4:按照订单更新时间;
|
||
page_size = page_size, //页大小
|
||
start_time = start_time.ToString("yyyy-MM-dd HH:mm:ss"),
|
||
end_time = start_time.AddMinutes(interval)
|
||
.ToString(
|
||
"yyyy-MM-dd HH:mm:ss"), //这里是对应前面同步间隔的19分钟 //【订单查询结束时间,订单开始时间至订单结束时间,中间时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!】
|
||
page_no = page_index,
|
||
order_count_type = (int)type,
|
||
order_scene = order_scene
|
||
};
|
||
_rst = this.SendTaobao("taobao.tbk.sc.order.details.get", obj);
|
||
DownAlimamaTimer.SetIntervalCache(interval);
|
||
break;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
//29453481(魏娜晓辉)请求阿里妈妈接口:{"error_response":{"code":15,"msg":"Remote service error","sub_code":"2007","sub_msg":"亲,订单开始时间至订单结束时间的时间段是60分钟,时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!","request_id":"3ppg3w1tkhay"}} - 在 Api.Framework.Cps.AlimamaApi.SendTaobaoServer(String _api, Object _data, String _appkey, String _appsecret) 位置 D:\秒单客项目\返利机器人\fl_system\类库\Api.Framework\Cps\AlimamaApi.cs:行号 569
|
||
if (ex.Message.Contains("年货节等大促期间预估时间段不可超过"))
|
||
interval = 19;
|
||
else
|
||
throw ex;
|
||
}
|
||
}
|
||
|
||
var isWhile = false;
|
||
do
|
||
{
|
||
//Console.WriteLine($"{this.Member.usernick} - {tk_status} - {start_time} - {page_index}/{page_size}");
|
||
try
|
||
{
|
||
if (_rst != null && _rst.ContainsKey("data"))
|
||
{
|
||
var data = _rst["data"] as Dictionary<string, object>;
|
||
//查看是否还有下一页
|
||
if (data.ContainsKey("has_next") && data["has_next"].ToString().ToLower() != "false")
|
||
{
|
||
isWhile = true;
|
||
|
||
#region 获取下一页数据
|
||
|
||
array.AddRange(GetResult(data));
|
||
if (data.ContainsKey("position_index"))
|
||
{
|
||
var position_index = data["position_index"].ToString();
|
||
page_index++;
|
||
if (tk_status != AlimamaOrderStatus.全部订单)
|
||
obj = new
|
||
{
|
||
query_type = 4, //查询时间类型,1:按照订单淘客创建时间查询,2:按照订单淘客付款时间查询,3:按照订单淘客结算时间查询
|
||
page_size = page_size, //页大小
|
||
tk_status = (int)tk_status,
|
||
start_time = start_time.ToString("yyyy-MM-dd HH:mm:ss"),
|
||
end_time = start_time.AddMinutes(interval)
|
||
.ToString(
|
||
"yyyy-MM-dd HH:mm:ss"), //这里是对应前面同步间隔的19分钟 //【订单查询结束时间,订单开始时间至订单结束时间,中间时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!】
|
||
page_no = page_index,
|
||
position_index = position_index,
|
||
order_count_type = (int)type
|
||
};
|
||
else
|
||
obj = new
|
||
{
|
||
query_type = 4, //查询时间类型,1:按照订单淘客创建时间查询,2:按照订单淘客付款时间查询,3:按照订单淘客结算时间查询
|
||
page_size = page_size, //页大小
|
||
start_time = start_time.ToString("yyyy-MM-dd HH:mm:ss"),
|
||
end_time = start_time.AddMinutes(interval)
|
||
.ToString(
|
||
"yyyy-MM-dd HH:mm:ss"), //这里是对应前面同步间隔的19分钟 //【订单查询结束时间,订单开始时间至订单结束时间,中间时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!】
|
||
page_no = page_index,
|
||
position_index = position_index,
|
||
order_count_type = (int)type
|
||
};
|
||
//continue;
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
else
|
||
{
|
||
//isWhile = false;
|
||
_rst.Clear();
|
||
_rst = null;
|
||
array.AddRange(GetResult(data));
|
||
return array;
|
||
}
|
||
|
||
_rst = this.SendTaobao("taobao.tbk.sc.order.details.get", obj);
|
||
}
|
||
}
|
||
catch (Exception _ex)
|
||
{
|
||
throw _ex;
|
||
}
|
||
} while (isWhile);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
|
||
return array;
|
||
|
||
#endregion
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// 下载订单,不带状态(有多页,获取所有)
|
||
/// </summary>
|
||
/// <param name="start_time">开始时间</param>
|
||
/// <param name="_page_index">第几页</param>
|
||
/// <param name="page_size">页大小</param>
|
||
/// <param name="type">阿里妈妈同步的订单类型</param>
|
||
/// <param name="order_scene">场景订单场景类型,1:常规订单,2:渠道订单,3:会员运营订单,默认为1</param>
|
||
/// <returns></returns>
|
||
internal ArrayList DownOrder(DateTime start_time, int _page_index, int page_size, AlimamaOrderType type,
|
||
int order_scene)
|
||
{
|
||
#region 2021-08-04之后 新接口 第三版(按照订单更新时间)
|
||
|
||
var interval = DownAlimamaTimer.GetIntervalCache(); //这个是三个小时的间隔 如果报错就用19分钟的间隔,默认179
|
||
ArrayList array = new ArrayList();
|
||
try
|
||
{
|
||
object obj = null;
|
||
var page_index = _page_index;
|
||
Dictionary<string, object> _rst = null;
|
||
for (int i = 0; i < 2; i++)
|
||
{
|
||
try
|
||
{
|
||
obj = new
|
||
{
|
||
query_type = 4, //查询时间类型,1:按照订单淘客创建时间查询,2:按照订单淘客付款时间查询,3:按照订单淘客结算时间查询,4:按照订单更新时间;
|
||
page_size = page_size, //页大小
|
||
start_time = start_time.ToString("yyyy-MM-dd HH:mm:ss"),
|
||
end_time = start_time.AddMinutes(interval)
|
||
.ToString(
|
||
"yyyy-MM-dd HH:mm:ss"), //这里是对应前面同步间隔的19分钟 //【订单查询结束时间,订单开始时间至订单结束时间,中间时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!】
|
||
page_no = page_index,
|
||
order_count_type = (int)type,
|
||
order_scene = order_scene
|
||
};
|
||
_rst = this.SendTaobao("taobao.tbk.sc.order.details.get", obj);
|
||
DownAlimamaTimer.SetIntervalCache(interval);
|
||
break;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
//1029080089(秒单客036)请求阿里妈妈接口:{"error_response":{"code":15,"msg":"Remote service error","sub_code":"2007","sub_msg":"亲,订单开始时间至订单结束时间的时间段是60分钟,时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!","request_id":"5zjxw7z7laai"}} - 在 Api.Framework.Cps.AlimamaApi.SendTaobaoServer(String _api, Object _data, String _appkey, String _appsecret) 位置 D:\秒单客项目\返利机器人\fl_system\类库\Api.Framework\Cps\AlimamaApi.cs:行号 614
|
||
|
||
//29453481(魏娜晓辉)请求阿里妈妈接口:{"error_response":{"code":15,"msg":"Remote service error","sub_code":"2007","sub_msg":"亲,订单开始时间至订单结束时间的时间段是60分钟,时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!","request_id":"3ppg3w1tkhay"}} - 在 Api.Framework.Cps.AlimamaApi.SendTaobaoServer(String _api, Object _data, String _appkey, String _appsecret) 位置 D:\秒单客项目\返利机器人\fl_system\类库\Api.Framework\Cps\AlimamaApi.cs:行号 569
|
||
|
||
//28592081(永远圆不了)请求阿里妈妈接口:{"error_response":{"code":15,"msg":"Remote service error","sub_code":"2007","sub_msg":"亲,订单开始时间至订单结束时间的时间段是60分钟,时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!","request_id":"f87pm4x24dn2"}} - 在 Api.Framework.Cps.AlimamaApi.SendTaobaoServer(String _api, Object _data, String _appkey, String _appsecret) 位置 D:\秒单客项目\返利机器人\fl_system\类库\Api.Framework\Cps\AlimamaApi.cs:行号 614
|
||
if (ex.Message.Contains("年货节等大促期间预估时间段不可超过"))
|
||
interval = 19;
|
||
else
|
||
throw ex;
|
||
}
|
||
}
|
||
|
||
var isWhile = false;
|
||
do
|
||
{
|
||
//Console.WriteLine($".{this.Member.usernick} - {start_time} - {page_index}/{page_size}");
|
||
try
|
||
{
|
||
if (_rst != null && _rst.ContainsKey("data"))
|
||
{
|
||
var data = _rst["data"] as Dictionary<string, object>;
|
||
//查看是否还有下一页
|
||
if (data.ContainsKey("has_next") && data["has_next"].ToString().ToLower() != "false")
|
||
{
|
||
isWhile = true;
|
||
|
||
#region 获取下一页数据
|
||
|
||
array.AddRange(GetResult(data));
|
||
if (data.ContainsKey("position_index"))
|
||
{
|
||
var position_index = data["position_index"].ToString();
|
||
page_index++;
|
||
obj = new
|
||
{
|
||
query_type = 4, //查询时间类型,1:按照订单淘客创建时间查询,2:按照订单淘客付款时间查询,3:按照订单淘客结算时间查询
|
||
page_size = page_size, //页大小
|
||
start_time = start_time.ToString("yyyy-MM-dd HH:mm:ss"),
|
||
end_time = start_time.AddMinutes(interval)
|
||
.ToString(
|
||
"yyyy-MM-dd HH:mm:ss"), //这里是对应前面同步间隔的19分钟 //【订单查询结束时间,订单开始时间至订单结束时间,中间时间段日常要求不超过3个小时,但如618、双11、年货节等大促期间预估时间段不可超过20分钟,超过会提示错误,调用时请务必注意时间段的选择,以保证亲能正常调用!】
|
||
page_no = page_index,
|
||
position_index = position_index,
|
||
order_count_type = (int)type
|
||
};
|
||
//continue;
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
else
|
||
{
|
||
//isWhile = false;
|
||
_rst.Clear();
|
||
_rst = null;
|
||
array.AddRange(GetResult(data));
|
||
return array;
|
||
}
|
||
|
||
_rst = this.SendTaobao("taobao.tbk.sc.order.details.get", obj);
|
||
}
|
||
}
|
||
catch (Exception _ex)
|
||
{
|
||
throw _ex;
|
||
}
|
||
} while (isWhile);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
|
||
return array;
|
||
|
||
#endregion
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析请求到的订单
|
||
/// </summary>
|
||
/// <param name="data">获取到的订单数据</param>
|
||
/// <returns></returns>
|
||
private ArrayList GetResult(Dictionary<string, object> data)
|
||
{
|
||
if (data != null && data.ContainsKey("results"))
|
||
{
|
||
var results = data["results"] as Dictionary<string, object>;
|
||
if (results != null && results.ContainsKey("publisher_order_dto"))
|
||
return results["publisher_order_dto"] as ArrayList;
|
||
}
|
||
|
||
return new ArrayList();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 淘宝防屏蔽地址(不带缩短)
|
||
/// </summary>
|
||
/// <param name="itemId">淘宝ID</param>
|
||
/// <param name="img">图片地址</param>
|
||
/// <param name="tkl">淘口令</param>
|
||
/// <param name="url">下单地址</param>
|
||
/// <param name="pid">推荐商品转链pid</param>
|
||
/// <param name="isTuiguang">是否有推荐商品</param>
|
||
/// <param name="target">自定义的目标地址</param>
|
||
/// <returns></returns>
|
||
private string ComposeTbClick(string itemId, string img, string tkl, string url, string pid, bool isTuiguang,
|
||
string target = "", bool isCircleZjy = false)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(tkl))
|
||
{
|
||
var reg = Regex.Match(tkl, "[^A-Za-z0-9]?([A-Za-z0-9]{11})[^A-Za-z0-9]?");
|
||
if (reg.Success)
|
||
tkl = "¥" + reg.Groups[1].Value + "¥";
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(target))
|
||
target = string.IsNullOrWhiteSpace(ApiClient.Setting.SystemConfig.URLTbTkl)
|
||
? FindTransferAddress(isCircleZjy ? TargetType.朋友圈中间页 : TargetType.淘口令)
|
||
: ApiClient.Setting.SystemConfig.URLTbTkl.Trim();
|
||
target = target
|
||
.Replace("[关键词]", System.Web.HttpUtility.UrlEncode(tkl))
|
||
.Replace("[口令]", "[淘口令]")
|
||
.Replace("[淘口令]", System.Web.HttpUtility.UrlEncode(tkl))
|
||
.Replace("[宝贝ID]", itemId)
|
||
.Replace("[图片]", System.Web.HttpUtility.UrlEncode(HttpExtend.StringToBase64String(img)))
|
||
.Replace("[图片地址]", System.Web.HttpUtility.UrlEncode(img))
|
||
.Replace("[宝贝地址]", "[地址]")
|
||
.Replace("&url=[返利链接]", "")
|
||
.Replace("[地址]", System.Web.HttpUtility.UrlEncode(url))
|
||
.Replace("[pid]", pid)
|
||
.Replace("[tj]", isTuiguang.ToString());
|
||
|
||
if (target.StartsWith("https://hkl.api.52cmg.cn"))
|
||
{
|
||
var html = string.Empty;
|
||
for (int i = 0; i < 3; i++)
|
||
{
|
||
var http = new HttpHelper();
|
||
var item = http.GetItem(target);
|
||
html = http.GetHtml(item).Html;
|
||
var json = HttpExtend.JsonToDictionary(html);
|
||
if (json != null && json["ok"].ToString().ToLower() == "true")
|
||
{
|
||
return json["message"].ToString();
|
||
}
|
||
|
||
continue;
|
||
}
|
||
|
||
throw new Exception($@"gethkl:{html}
|
||
t = {target}");
|
||
}
|
||
|
||
return target;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 淘宝防屏蔽地址带缩短
|
||
/// </summary>
|
||
/// <param name="itemId">淘宝ID</param>
|
||
/// <param name="img">图片地址</param>
|
||
/// <param name="tkl">淘口令</param>
|
||
/// <param name="url">下单地址</param>
|
||
/// <param name="isShortUrl">是否缩短</param>
|
||
/// <param name="DwzType">缩短的枚举类型数值(-1为系统基础设置)</param>
|
||
/// <param name="target">自定义的目标地址</param>
|
||
/// <returns></returns>
|
||
public string ComposeTbClick(string itemId, string img, string tkl, string url, bool isShortUrl,
|
||
int DwzType = -1, string target = "", bool isCircleZjy = false)
|
||
{
|
||
try
|
||
{
|
||
if (string.IsNullOrWhiteSpace(img))
|
||
img = "https://img.alicdn.com/tfs/TB1MaLKRXXXXXaWXFXXXXXXXXXX-480-260.png";
|
||
|
||
var compose = ComposeTbClick(itemId, img, tkl, url, "", false, target, isCircleZjy);
|
||
|
||
return GetComposeUrl(compose, isShortUrl, DwzType, target); //
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
EventClient.OnEvent(this, $@"CTC:{ex.Message} @ {ex.StackTrace}");
|
||
}
|
||
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 淘宝防屏蔽地址(带推荐)
|
||
/// </summary>
|
||
/// <param name="itemId">淘宝ID</param>
|
||
/// <param name="img">图片地址</param>
|
||
/// <param name="tkl">淘口令</param>
|
||
/// <param name="url">下单地址</param>
|
||
/// <param name="isShortUrl">是否缩短</param>
|
||
/// <param name="pid">推广商品转链用的推广位信息</param>
|
||
/// <param name="isTuiGuang">是否推广</param>
|
||
/// <param name="DwzType">缩短的枚举类型数值(-1为系统基础设置)</param>
|
||
/// <param name="target">自定义的目标地址</param>
|
||
/// <returns></returns>
|
||
public string ComposeTbClick(string itemId, string img, string tkl, string url, bool isShortUrl, string pid,
|
||
bool isTuiGuang, int DwzType = -1, string target = "", bool isCircleZjy = false)
|
||
{
|
||
var compose = string.Empty;
|
||
if (string.IsNullOrWhiteSpace(pid))
|
||
compose = ComposeTbClick(itemId, img, tkl, url, isShortUrl, DwzType, target, isCircleZjy);
|
||
else
|
||
compose = ComposeTbClick(itemId, img, tkl, url, pid, isTuiGuang, target, isCircleZjy);
|
||
return GetComposeUrl(compose, isShortUrl, DwzType, target);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取中间页地址
|
||
/// </summary>
|
||
/// <param name="compose"></param>
|
||
/// <param name="isShortUrl"></param>
|
||
/// <param name="DwzType"></param>
|
||
/// <param name="target"></param>
|
||
/// <returns></returns>
|
||
private string GetComposeUrl(string compose, bool isShortUrl, int DwzType = -1, string target = "", bool isCircleZjy = false)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(target))
|
||
{
|
||
//target =
|
||
if (string.IsNullOrWhiteSpace(ApiClient.Setting.SystemConfig.URLTbTkl))
|
||
{
|
||
target = FindTransferAddress(isCircleZjy ? TargetType.朋友圈中间页 : TargetType.淘口令);
|
||
}
|
||
else
|
||
{
|
||
target = ApiClient.Setting.SystemConfig.URLTbTkl.Trim();
|
||
}
|
||
|
||
}
|
||
|
||
if (target.StartsWith("https://hkl.api.52cmg.cn"))
|
||
{
|
||
return compose;
|
||
}
|
||
|
||
var dtype = Api.Framework.ApiClient.Setting.SystemConfig.dwz_type;
|
||
if (isShortUrl && DwzType != -1)
|
||
{
|
||
//Util.CheckUrlDomain(compose);
|
||
//return ApiClient.ShortURL(compose, (DwzType)DwzType).Result;
|
||
dtype = (DwzType)DwzType;
|
||
}
|
||
|
||
if (!string.IsNullOrWhiteSpace(ApiClient.Setting.SystemConfig.URLTbTkl)) Util.CheckUrlDomain(compose);
|
||
return ApiClient.ShortURL(compose, dtype).Result;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 拼接淘宝Cms地址.关键词:[推广位]、[关键词](注:小写的url编码)、[关键词U](注:大写的url编码)、
|
||
/// </summary>
|
||
/// <param name="pid">推广位id</param>
|
||
/// <param name="keyword">搜索的关键词</param>
|
||
/// <returns>拼接好的url</returns>
|
||
public string ComposeTbCms(string pid, string keyword)
|
||
{
|
||
var target = string.Empty;
|
||
if (string.IsNullOrWhiteSpace(ApiClient.Setting.SystemConfig.URLTbCms))
|
||
{
|
||
target = FindTransferAddress(TargetType.产品库);
|
||
}
|
||
else
|
||
{
|
||
target = ApiClient.Setting.SystemConfig.URLTbCms.Trim();
|
||
}
|
||
|
||
var result = target
|
||
.Replace("[推广位]", pid)
|
||
.Replace("[关键词]", "[关键词L]")
|
||
.Replace("[关键词L]", System.Web.HttpUtility.UrlEncode(keyword))
|
||
.Replace("[关键词U]", HttpExtend.UrlEncode(keyword));
|
||
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 淘宝防屏蔽地址缓存
|
||
/// </summary>
|
||
/// <param name="type">请求目标类型(产品库/淘口令/订单页)</param>
|
||
/// <param name="refresh">false获取缓存,true重新获取</param>
|
||
/// <returns></returns>
|
||
public static string FindTransferAddress2(TargetType type, bool refresh = false)
|
||
{
|
||
string key = $"key_alimamaapi_composetbclick_{(int)type}";
|
||
string target = ApiClient.Cache.Get<string>(key);
|
||
//Console.WriteLine(type.ToString() + ",target = " + target);
|
||
if (refresh || string.IsNullOrWhiteSpace(target))
|
||
{
|
||
for (int i = 0; i < 5; i++)
|
||
{
|
||
try
|
||
{
|
||
var ali = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.阿里妈妈);
|
||
if (ali == null) return target;
|
||
var cps = CpsClient.CreateAlimamaRequest(ali);
|
||
if (cps == null)
|
||
{
|
||
//Console.WriteLine("cps = " + cps == null + " , " + type.ToString() + ",target = " + target);
|
||
return target;
|
||
}
|
||
target = cps.SendServer("find_wangzhi", "webTool.asmx", new { name = type.ToString() }).message.ToString();
|
||
ApiClient.Cache.Set(key, target, 10);
|
||
break;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Thread.Sleep(200);
|
||
}
|
||
}
|
||
}
|
||
//Console.WriteLine(type.ToString() + ",target = " + target);
|
||
return target;
|
||
}
|
||
|
||
internal AlimamaApi(fl_cps_member member) : base(member)
|
||
{
|
||
}
|
||
|
||
|
||
|
||
#region MyRegion
|
||
|
||
private static NoticeSocketClient _noticeSocket;
|
||
private static RemoteCloudConnectService _remoteCloudConnectService = new RemoteCloudConnectService();
|
||
|
||
public static void Init()
|
||
{
|
||
_remoteCloudConnectService.Initialize();
|
||
//"tksoft", "circle_goods_task"
|
||
_noticeSocket = new NoticeSocketClient();
|
||
_remoteCloudConnectService.CloudNoticeEvent += _remoteCloudConnectService_CloudNoticeEvent;
|
||
_remoteCloudConnectService.OnOpen += _remoteCloudConnectService_OnOpen;
|
||
ThreadPool.QueueUserWorkItem(o => { RefreshTkUrl(); });
|
||
}
|
||
// 连接打开
|
||
private static void _remoteCloudConnectService_OnOpen()
|
||
{
|
||
var arr = new string[] { "tksoft", "circle_goods_task", "laow" };
|
||
foreach (var item in arr)
|
||
{
|
||
_remoteCloudConnectService.SendString("subchannel\u0000" + item);
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 防止重复
|
||
/// </summary>
|
||
private static List<string> repeatList = new List<string>();
|
||
private static void _remoteCloudConnectService_CloudNoticeEvent(object sender, CloudNoticeEventArgs e)
|
||
{
|
||
if (repeatList.Contains(e.Id))//去重复
|
||
{
|
||
return;
|
||
}
|
||
repeatList.Add(e.Id);
|
||
|
||
var commonId = e.CommonId.ToLower();
|
||
try
|
||
{
|
||
LogHelper.GetSingleObj().Info("", "域名相关通知 => " + e.Body);
|
||
if (commonId == "change_tkurl")
|
||
{
|
||
var data = JObject.Parse(e.Body);
|
||
var newUrl = (data["new"] ?? string.Empty).Value<string>();
|
||
var oldUrl = (data["old"] ?? string.Empty).Value<string>();
|
||
if (string.IsNullOrEmpty(newUrl) || string.IsNullOrEmpty(oldUrl)) return;
|
||
//替换查询中间页
|
||
for (int i = 0; i < TkUrl.UrlQuery.Length; i++)
|
||
{
|
||
if (TkUrl.UrlQuery[i].IndexOf(oldUrl, StringComparison.Ordinal) != -1)
|
||
TkUrl.UrlQuery[i] = TkUrl.UrlQuery[i].Replace(oldUrl, newUrl);
|
||
}
|
||
|
||
//替换cms网站
|
||
for (int i = 0; i < TkUrl.UrlCms.Length; i++)
|
||
{
|
||
if (TkUrl.UrlCms[i].IndexOf(oldUrl, StringComparison.Ordinal) != -1)
|
||
TkUrl.UrlCms[i] = TkUrl.UrlCms[i].Replace(oldUrl, newUrl);
|
||
}
|
||
|
||
////替换提现页面
|
||
//for (int i = 0; i < TkUrl.UrlCash.Length; i++)
|
||
//{
|
||
// if (TkUrl.UrlCash[i].IndexOf(oldUrl, StringComparison.Ordinal) != -1)
|
||
// TkUrl.UrlCash[i] = TkUrl.UrlCash[i].Replace(oldUrl, newUrl);
|
||
//}
|
||
|
||
//替换朋友圈中间页
|
||
for (int i = 0; i < TkUrl.UrlCircle.Length; i++)
|
||
{
|
||
if (TkUrl.UrlCircle[i].IndexOf(oldUrl, StringComparison.Ordinal) != -1)
|
||
TkUrl.UrlCircle[i] = TkUrl.UrlCircle[i].Replace(oldUrl, newUrl);
|
||
}
|
||
}
|
||
else if (commonId == "refreshTkurl".ToLower())
|
||
{
|
||
RefreshTkUrl();
|
||
}
|
||
else if (commonId == "send" && e.Channel == "circle_goods_task")
|
||
{
|
||
//{"Id":"122522636742819840","TaskId":"122522636742819840","IsGoods":true}
|
||
EventClient.OnDyyNoticeEvent(null, new DyyNoticeEvent() { Data = e.Body });
|
||
}
|
||
}
|
||
catch (Exception exception)
|
||
{
|
||
EventClient.OnEvent("收到域名变化通知", $"数据:{e.Body};异常:{exception.Message}");
|
||
}
|
||
finally
|
||
{
|
||
if (repeatList.Count > 10000)
|
||
{
|
||
repeatList.RemoveRange(0, 9000);
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// 淘客的地址
|
||
/// </summary>
|
||
public static TkUrlClass TkUrl { get; private set; }
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// 刷新淘客中间页
|
||
/// </summary>
|
||
public static void RefreshTkUrl()
|
||
{
|
||
try
|
||
{
|
||
var data = _noticeSocket.GetData("tkurl");
|
||
LogHelper.GetSingleObj().Info("", "域名重新获取 => " + data);
|
||
if (string.IsNullOrWhiteSpace(data))
|
||
{
|
||
throw new Exception("请求域名为空");
|
||
}
|
||
|
||
var rst = JsonConvert.DeserializeObject<TkUrlClass>(data);
|
||
if (rst != null) TkUrl = rst;
|
||
}
|
||
catch (Exception exception)
|
||
{
|
||
EventClient.OnEvent($"获取淘客域名失败", $"{exception.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取新的域名
|
||
/// </summary>
|
||
/// <param name="targetType"></param>
|
||
/// <param name="refresh"></param>
|
||
/// <returns></returns>
|
||
public static string FindTransferAddress(TargetType targetType, bool refresh = false)
|
||
{
|
||
if (TkUrl == null)
|
||
{
|
||
RefreshTkUrl();
|
||
}
|
||
|
||
switch (targetType)
|
||
{
|
||
case TargetType.产品库:
|
||
{
|
||
var _url = GetRandomUrl(TkUrl.UrlCms);
|
||
return $"{_url}/?keyword=[关键词]&pid=[推广位]";
|
||
}
|
||
break;
|
||
case TargetType.淘口令:
|
||
{
|
||
var _url = GetRandomUrl(TkUrl.UrlQuery);
|
||
return $"{_url}/?taowords=[淘口令]&pic=[图片]&url=[地址]&pid=[pid]&tj=[tj]&item_id=[宝贝ID]";
|
||
}
|
||
break;
|
||
case TargetType.订单页:
|
||
{
|
||
//var _url = GetRandomUrl(TkUrl.UrlCms);
|
||
//return $"{_url}/aliorder.html?key=[key]";
|
||
|
||
var _url = FindTransferAddress2(targetType);
|
||
return _url;
|
||
}
|
||
break;
|
||
case TargetType.朋友圈中间页:
|
||
{
|
||
var _url = GetRandomUrl(TkUrl.UrlCircle);
|
||
return $"{_url}/?taowords=[淘口令]&pic=[图片]&url=[地址]&pid=[pid]&tj=[tj]&item_id=[宝贝ID]";
|
||
}
|
||
break;
|
||
}
|
||
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 随机取一个
|
||
/// </summary>
|
||
/// <param name="list"></param>
|
||
/// <returns></returns>
|
||
private static string GetRandomUrl(string[] list)
|
||
{
|
||
if (list != null && list.Length > 0)
|
||
{
|
||
var r = new Random(Guid.NewGuid().GetHashCode());
|
||
var index = r.Next(0, list.Length);
|
||
return list[index];
|
||
}
|
||
return string.Empty;
|
||
}
|
||
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 会员推广位为列表
|
||
/// </summary>
|
||
/// <param name="topage">第几页</param>
|
||
/// <param name="pagesize">页大小</param>
|
||
/// <returns></returns>
|
||
internal Dictionary<string, object> VipAdzoneManage(int topage, int pagesize)
|
||
{
|
||
var _tb_token_ = string.Empty;
|
||
var reg = Regex.Match(Member.cookies, "_tb_token_=([^;]+)");
|
||
if (reg.Success)
|
||
_tb_token_ = reg.Groups[1].Value;
|
||
var _url = $"https://pub.alimama.com/common/adzone/adzoneList.json?type=2&t={HttpExtend.GetTimeStamp()}&_tb_token_={_tb_token_}&pvid=";
|
||
var http = new HttpHelper();
|
||
var item = http.GetItem(_url, Member.cookies);
|
||
var html = http.GetHtml(item).Html;
|
||
if (html.Contains("没有权限"))
|
||
{
|
||
try
|
||
{
|
||
Clipboard.SetDataObject("https://survey.taobao.com/apps/zhiliao/0JpI9eizU");
|
||
}
|
||
catch (Exception ex)
|
||
{ }
|
||
throw new Exception($@"{Member.usernick},您还没有申请权限哦
|
||
申请地址已经复制,请在网页中打开");
|
||
}
|
||
//EventClient.OnEvent("", "html = " + html);
|
||
var _dic = HttpExtend.JsonToDictionary(html);
|
||
if (_dic == null) throw new Exception($"{Member.usernick},此接口需要访问阿里妈妈官网,登录已过期请重新登录阿里妈妈!");
|
||
if (_dic["ok"].ToString().ToLower() == "false") throw new Exception(html);
|
||
_dic = _dic["data"] as Dictionary<string, object>;
|
||
|
||
return _dic;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 普通推广位列表
|
||
/// </summary>
|
||
/// <param name="topage">第几页</param>
|
||
/// <param name="pagesize">页大小</param>
|
||
/// <returns></returns>
|
||
public Dictionary<string, object> AdzoneManage(int topage, int pagesize)
|
||
{
|
||
var _url = $"https://pub.alimama.com/common/adzone/adzoneManage.json?tab=3&toPage={topage}&perPageSize={pagesize}&gcid=8&t={HttpExtend.GetTimeStamp()}&_input_charset=utf-8";
|
||
var http = new HttpHelper();
|
||
var item = http.GetItem(_url, Member.cookies);
|
||
var html = http.GetHtml(item).Html;
|
||
var _dic = HttpExtend.JsonToDictionary(html);
|
||
if (_dic == null) throw new Exception($"{Member.usernick},此接口需要访问阿里妈妈官网,登录已过期请重新登录阿里妈妈!");
|
||
if (_dic["ok"].ToString().ToLower() == "false") throw new Exception(html);
|
||
_dic = _dic["data"] as Dictionary<string, object>;
|
||
|
||
return _dic;
|
||
}
|
||
|
||
private static DateTime NextTime = DateTime.MinValue;
|
||
|
||
/// <summary>
|
||
/// 检测淘宝优惠券
|
||
/// </summary>
|
||
/// <param name="coupon_click_url">优惠券地址</param>
|
||
/// <returns></returns>
|
||
public Coupon CheckCoupon(string coupon_click_url)
|
||
{
|
||
string html = string.Empty;
|
||
try
|
||
{
|
||
if (coupon_click_url.Contains("coupon/details") || coupon_click_url.Contains("coupon/edetail"))
|
||
{
|
||
Coupon c = new Coupon();
|
||
coupon_click_url = coupon_click_url.Replace("coupon/details", "cp/coupon/").Replace("coupon/edetail", "cp/coupon/");
|
||
var http = new HttpHelper();
|
||
|
||
for (int i = 0; i < 4; i++)
|
||
{
|
||
if (NextTime > DateTime.Now)
|
||
return null;
|
||
|
||
var item = http.GetItem(coupon_click_url);
|
||
item.Timeout = 30000;
|
||
item.ReadWriteTimeout = 20000;
|
||
item.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
|
||
item.ContentType = "application/x-www-form-urlencoded";
|
||
item.SetProxyipCDN();
|
||
html = http.GetHtml(item).Html.Replace("\\", "");
|
||
if (html.Contains("亲,小二正忙,滑动一下马上回来") || html.Contains("操作超时") || html == @"{""success"": false}")
|
||
{
|
||
if (i == 3)
|
||
{
|
||
NextTime = DateTime.Now.AddMinutes(2);
|
||
return null;
|
||
}
|
||
Thread.Sleep(500);
|
||
continue;
|
||
}
|
||
|
||
var _obj = HttpExtend.JsonToDictionary(html);//转成字典
|
||
if (_obj != null)
|
||
{
|
||
_obj = _obj["result"] as Dictionary<string, object>;
|
||
_obj.ConvertToObj(c);
|
||
if (c.retStatus == 1) continue;
|
||
_obj = _obj["item"] as Dictionary<string, object>;
|
||
if (_obj["clickUrl"] != null) _obj["clickUrl"] = "http:" + _obj["clickUrl"].ToString();
|
||
if (_obj["shareUrl"] != null) _obj["shareUrl"] = "http:" + _obj["shareUrl"].ToString();
|
||
_obj.ConvertToObj(c);
|
||
if (c.retStatus == 2 || c.retStatus == 0 || c.retStatus == 4) return c;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
EventClient.OnEvent(this, $@"检查优惠券异常:{ex.Message} @ {ex.StackTrace}
|
||
html => {html}");
|
||
}
|
||
return null;
|
||
}
|
||
|
||
private string GetTbToken()
|
||
{
|
||
var reg = Regex.Match(Member.cookies, "(?<tbToken>_tb_token_=[a-zA-Z0-9]+)",
|
||
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
|
||
if (reg.Success)
|
||
{
|
||
return reg.Groups["tbToken"].Value;
|
||
}
|
||
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获得HTML
|
||
/// </summary>
|
||
/// <param name="url">请求的地址</param>
|
||
/// <param name="postData">post数据</param>
|
||
/// <param name="referer">referer的地址</param>
|
||
/// <returns></returns>
|
||
private string GetAlimamaHtml(string url, string postData = "", string referer = "http://pub.alimama.com/myunion.htm")
|
||
{
|
||
try
|
||
{
|
||
//Console.WriteLine(url);
|
||
Thread.Sleep(300 + random.Next(700, 3000));
|
||
|
||
HttpHelper _http = new HttpHelper();
|
||
HttpItem item = new HttpItem()
|
||
{
|
||
URL = url,
|
||
Method = string.IsNullOrEmpty(postData) ? "get" : "post",
|
||
IsToLower = false,
|
||
Cookie = Member.cookies,
|
||
Referer = referer,
|
||
Postdata = postData,
|
||
Timeout = 3000,
|
||
ReadWriteTimeout = 3000,
|
||
UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER",
|
||
ContentType = "application/x-www-form-urlencoded",
|
||
Allowautoredirect = true,
|
||
ProtocolVersion = System.Net.HttpVersion.Version11
|
||
};
|
||
//item.SetProxyipCDN();
|
||
var result = _http.GetHtml(item);
|
||
//Console.WriteLine($"{result.Html} - {result.Cookie}");
|
||
if (!string.IsNullOrEmpty(result.Cookie))
|
||
{
|
||
this.Member.cookies = result.UpdateCookies(this.Member.cookies);
|
||
}
|
||
return result.Html;
|
||
}
|
||
catch (Exception)
|
||
{ }
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 随机数对象
|
||
/// </summary>
|
||
private static Random random = new Random();
|
||
|
||
/// <summary>
|
||
/// 淘宝活动页参数
|
||
/// </summary>
|
||
private List<string> ActivityList = new List<string>() { "official", "union", "local", "tbtm", "atb", "bpk" };
|
||
|
||
/// <summary>
|
||
/// 更新阿里妈妈Cookies
|
||
/// </summary>
|
||
internal void UpdateCookies()
|
||
{
|
||
GetAlimamaHtml("https://pub.alimama.com/portal/home/index.htm");
|
||
GetAlimamaHtml("https://pub.alimama.com/promo/search/index.htm");
|
||
|
||
for (int i = 0; i < 2; i++)
|
||
{
|
||
var index = random.Next(0, ActivityList.Count);
|
||
GetAlimamaHtml($"https://pub.alimama.com/portal/promo/activity.htm?tab={ActivityList[index]}");
|
||
}
|
||
|
||
GetAlimamaHtml("https://pub.alimama.com/portal/account/settle/income/index.htm");
|
||
GetAlimamaHtml("https://media.alimama.com/account/drawback/list.htm");
|
||
GetAlimamaHtml("https://pub.alimama.com/fourth/tool/api/index.htm");
|
||
GetAlimamaHtml("https://pub.alimama.com/portal/v2/tool/links/page/home/index.htm");
|
||
GetAlimamaHtml("https://dmp.taobao.com/");
|
||
GetAlimamaHtml("https://pub.alimama.com/");
|
||
GetAlimamaHtml("https://subway.simba.taobao.com/indexnew.jsp");
|
||
GetAlimamaHtml("https://pub.alimama.com/openapi/param2/1/gateway.unionpub/thor.campaign.report.json", $"t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&campaignName=&gap=7&pageSize=20&page=1");
|
||
GetAlimamaHtml("https://pub.alimama.com/openapi/param2/1/gateway.unionpub/thor.ad.unit.report.json", $"t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&itemId=&pid=&gap=1&pageSize=20&page=1&campaignId=");
|
||
GetAlimamaHtml("https://pub.alimama.com/openapi/json2/1/gateway.unionpub/xt.entry.json", $"t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&_tb_token_=eb53bb61783d6&_data_=%7B%22floorId%22%3A36306%2C%22variableMap%22%3A%7B%22status%22%3A%22check%22%2C%22orderType%22%3A%22%22%7D%2C%22pageNum%22%3A%221%22%2C%22pageSize%22%3A%2220%22%7D");
|
||
GetAlimamaHtml($"https://pub.alimama.com/openapi/param2/1/gateway.unionpub/asset.entry.json?t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&bizType=asset.asset-accountQuery&bizParam=");
|
||
GetAlimamaHtml($"https://pub.alimama.com/common/site/getAuthorities.json?t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&siteId=111111");
|
||
GetAlimamaHtml($"https://mo.m.taobao.com/union/mm/pub-common/frontversion");
|
||
GetAlimamaHtml($"https://aff-open.taobao.com/apply.htm");
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
GetAlimamaHtml("http://www.alimama.com/index.htm");
|
||
GetAlimamaHtml("https://ssp.tanx.com/api/userinfo?callback=userInfoCallback");
|
||
GetAlimamaHtml("http://ssp.tanx.com/api/userinfo?callback=userInfoCallback");
|
||
GetAlimamaHtml("https://media.alimama.com/user/base_info.htm");
|
||
GetAlimamaHtml("https://media.alimama.com/verify/risk.htm");
|
||
GetAlimamaHtml("https://media.alimama.com/");
|
||
GetAlimamaHtml("https://media.alimama.com/product.htm");
|
||
|
||
GetAlimamaHtml("https://pub.alimama.com/myunion.htm");
|
||
GetAlimamaHtml("https://tbk.bbs.taobao.com/list.html");
|
||
GetAlimamaHtml("https://pub.alimama.com/manage/overview/index.htm");
|
||
|
||
GetAlimamaHtml("https://pub.alimama.com/common/getUnionPubContextInfo.json");
|
||
|
||
var page = random.Next(1, 5);
|
||
var size = page * 10;
|
||
GetAlimamaHtml($"https://media.alimama.com/violationu2/violation2_page.json?r=mx_387&toPage={page}&pageSize=40");
|
||
|
||
if (page % 2 != 0)
|
||
{
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/adzone.htmhttps://pub.alimama.com/third/manage/record/site.htm?tab=self_web_site");//媒体备案管理 - 自有平台(网站)
|
||
if (page == 3)
|
||
GetAlimamaHtml($"https://pub.ama.com/third/manage/record/site.htm?tab=self_web_site&sencecode=self_app&pageNo=1&pageSize=50");//媒体备案管理 - 自有平台(App客户端)
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=self_web_site&sencecode=self_pc_client&pageNo=1&pageSize=50");//媒体备案管理 - 自有平台(PC客户端)
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=self_web_site&sencecode=self_offline&pageNo=1&pageSize=50");//媒体备案管理 - 自有平台(线下阵地)
|
||
}
|
||
else
|
||
{
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/adzone.htm");//推广位
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=all");//媒体备案管理 - 全部
|
||
if (page == 2)
|
||
{
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=self_web_site&sencecode=self_miniprogram&pageNo=1&pageSize=50");//媒体备案管理 - 自有平台(小程序/快应用)
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=self_web_site&sencecode=self_operating_system&pageNo=1&pageSize=50");//媒体备案管理 - 自有平台(操作系统)
|
||
}
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=self_web_site&sencecode=self_hardware_device&pageNo=1&pageSize=50");//媒体备案管理 - 自有平台(硬件设备)
|
||
}
|
||
GetAlimamaHtml($"https://pub.alimimama.com/third/manage/record/site.htm?tab=other_social");//媒体备案管理 - 他方平台(社交平台)
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=other_social&sencecode=other_content&pageNo=1&pageSize=50");//媒体备案管理 - 他方平台(内容平台)
|
||
|
||
GetAlimamaHtml($"https://pub.alimama.com/third/manage/record/site.htm?tab=traffic_purchasing");//媒体备案管理 - 无自有阵地
|
||
|
||
GetAlimamaHtml("http://c.tanx.com/");
|
||
|
||
for (int i = 0; i < 2; i++)
|
||
{
|
||
GetAlimamaHtml($"https://pub.alimama.com/openapi/json2/1/gateway.unionpub/xt.entry.json", $"t={HttpExtend.GetTimeStamp()}000&_tb_token_=33183160110853659822%3A34758%2C%22variableMap%22%3A%7B%22itemId%22%3A%22{(Util.GetRandomString(12))}%22%7D%7D");//内容库查询
|
||
}
|
||
|
||
|
||
GetAlimamaHtml($"https://pub.alimama.com/manage/user/new_privilege.htm");
|
||
|
||
for (int i = 0; i < 3; i++)
|
||
{
|
||
var punishStatus = random.Next(1, 9);
|
||
|
||
page = random.Next(1, 5);
|
||
size = page * 10;
|
||
|
||
GetAlimamaHtml($"https://media.alimama.com/violationu2/violation2_page.json?toPage={page}&pageSize={size}&punishStatus={punishStatus}");
|
||
}
|
||
|
||
GetAlimamaHtml($"https://pub.alimama.com/manage/overview/index.htm");
|
||
|
||
for (int i = 0; i < 3; i++)
|
||
{
|
||
var type = random.Next(1, 4);
|
||
var day = random.Next(1, 16);
|
||
var date1 = DateTime.Now.Date.AddDays(-day).ToString("yyyy-MM-dd");
|
||
var date2 = DateTime.Now.Date.ToString("yyyy-MM-dd");
|
||
GetAlimamaHtml($"https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json?t={HttpExtend.GetTimeStamp()}000&_tb_token_=33183d55eb1e6&jumpType=0&positionIndex=&pageNo=1&startTime={date1}&endTime={date2}&queryType={type}&tkStatus=&memberType=&pageSize=40");
|
||
}
|
||
|
||
for (int i = 0; i < 5; i++)
|
||
{
|
||
GetAlimamaHtml($"https://pub.alimama.com/openapi/param2/1/gateway.unionpub/mkt.campaign.signUp.list.json?t={HttpExtend.GetTimeStamp(DateTime.Now, true)}&pageNo=1&pageSize=20&keyword=&showStatus={(i + 1)}&productType=19&phaseType=3&searchType=1");
|
||
}
|
||
|
||
CheckLoginAlimama();
|
||
|
||
GetAlimamaHtml("https://pub.alimama.com/common/getUnionPubContextInfo.json");
|
||
|
||
GetAlimamaHtml($"https://media.alimama.com/violationu2/warning_instance_page.json?r=mx_544&toPage={page}&pageSize={size}");
|
||
|
||
GetAlimamaHtml($"https://everyservice.cdn.taobao.com/widget/queryServiceStrategy");
|
||
GetAlimamaHtml($"https://everyhelp.taobao.com/version/getWidgetVersion");
|
||
GetAlimamaHtml($"https://media.alimama.com/violation/violation_list.htm");
|
||
|
||
CheckLoginAlimama();
|
||
|
||
GetAlimamaHtml("https://c.tanx.com/");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 检测登录阿里妈妈
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
internal bool CheckLoginAlimama()
|
||
{
|
||
try
|
||
{
|
||
var dic = GetUnionPubContextInfo(this.Member.cookies);
|
||
if (dic != null)
|
||
{
|
||
if (dic.ContainsKey("memberID"))
|
||
return true;
|
||
else return false;
|
||
}
|
||
else return true;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 阿里妈妈同步的订单类型
|
||
/// </summary>
|
||
internal enum AlimamaOrderType : int
|
||
{
|
||
淘客明细订单 = 1,
|
||
第三方订单明细 = 2
|
||
}
|
||
|
||
/// <summary>
|
||
/// 阿里妈妈订单状态
|
||
/// </summary>
|
||
public enum AlimamaOrderStatus : int
|
||
{
|
||
全部订单 = 1,
|
||
订单结算 = 3,
|
||
订单付款 = 12,
|
||
订单失效 = 13,
|
||
订单成功 = 14,
|
||
订单维权中 = 15,
|
||
}
|
||
|
||
//public enum AlimamaOrderSort : int
|
||
//{
|
||
// 创建时间 = 1,
|
||
// 结算时间 = 2
|
||
//}
|
||
|
||
/// <summary>
|
||
/// 请求目标类型 产品库/淘口令/订单页
|
||
/// </summary>
|
||
public enum TargetType : int
|
||
{
|
||
淘口令 = 1,
|
||
产品库 = 2,
|
||
订单页 = 3,
|
||
朋友圈中间页 = 4
|
||
}
|
||
|
||
}
|
||
}
|