Files
KJD/TEMUKJD/VDianForms/VDianShopListForm.cs
T

901 lines
43 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using NaiBa.Util.Extension;
using Work;
using AllBase;
using AllBase.Helper;
using TemuKJD.BaseForms;
using TemuKJD.Extension;
using AllBase.Model.Result;
using TemuKJD.BLL.VDian;
using TemuKJD;
namespace KJD.VDianForms
{
public partial class VDianShopListForm : BaseGeneralForm
{
private bool isLoading = false;
public static VDianShopListForm Instance;
public VDianShopListForm()
{
InitializeComponent();
Instance = this;
}
public void HideBorder()
{
this.panel6.BorderStyle = BorderStyle.None;
}
private void ProductMappingVDianListFrom_Load(object sender, EventArgs e)
{
this.TitleText = this.Text;
this.dgvVDianShop.AddSelectorColumn("colSelect");
this.VisibleChanged += ProductMappingVDianListFrom_VisibleChanged;
}
private void ProductMappingVDianListFrom_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible == true)
RefreshDataGridView();
}
private void ProductMappingVDianLoginForm_SaveComplete(object obj)
{
VDianShopLoginInfo vDianShopLoginInfo = obj as VDianShopLoginInfo;
if (vDianShopLoginInfo == null)
return;
var vDianShop = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == vDianShopLoginInfo.ShopId);
if (vDianShop != null)
{
vDianShop.ShopName = vDianShopLoginInfo.ShopName;
vDianShop.Wdtoken = vDianShopLoginInfo.Wdtoken;
vDianShop.Cookies = vDianShopLoginInfo.Cookies;
vDianShop.ApiAuth = vDianShopLoginInfo.ApiAuth;
// 保存到服务器
SaveVDianToServer(vDianShop);
}
else
{
GlobalConfig.VDianShopLoginList.Add(vDianShopLoginInfo);
// 保存到服务器
SaveVDianToServer(vDianShopLoginInfo);
}
CheckShopLogin(new string[] { vDianShopLoginInfo.ShopId });
if (vDianShopLoginInfo.LoginStatus == 1)
{
// cookie保存到服务端
var url = BaseClass.BuildObjString("api/weidian&act=add_weidian_login_cookie").Replace("littlecow/api/weidian", "api/weidian");
var data = UserLogin.GetSignaturex() +
"&shop_id=" + vDianShopLoginInfo.ShopId +
"&shop_name=" + vDianShopLoginInfo.ShopName +
"&cookie=" + GetHtml.UrlEncodeUtf8(vDianShopLoginInfo.Cookies.Replace(" ", ""));
var html = GetHtml.PostUtf8(url, data);
// 测试获取cookie
//url = BaseClass.BuildObjString("api/weidian&act=get_weidian_login_cookie").Replace("littlecow/api/weidian", "api/weidian");
//data = UserLogin.GetSignaturex() + "&cid=6";
//html = GetHtml.PostUtf8(url, data);
}
}
/// <summary>
/// 读取服务端的微店
/// </summary>
public static List<VDianShopLoginInfo> GetServerVDian()
{
// 读取已有店铺
List<VDianShopLoginInfo> list = new List<VDianShopLoginInfo>();
string url = BaseClass.BuildObjString("shop&act=auto_login_shop_v1");
string data = UserLogin.GetSignaturex();
data += "&siteid=5";
string html = GetHtml.PostUtf8(url, data);
if (html == "Ok" || string.IsNullOrEmpty(html))
{
return list;
}
var m = BaseRegex.GetMatchRegex(ref html, "<shop([^>]+?)>");
for (int i = 0; m != null && i < m.Count; i++)
{
string shopStr = m[i].Groups[0].Value;
VDianShopLoginInfo vsp = new VDianShopLoginInfo();
vsp.ShopId = BaseRegex.GetStringJson(ref shopStr, "id");
if (vsp.ShopId == null)
continue;
vsp.Phone = BaseRegex.GetStringJson(ref shopStr, "user_name");
vsp.ShopName = BaseRegex.GetStringJson(ref shopStr, "name");
vsp.Password = BaseRegex.GetStringJson(ref shopStr, "password");
if (!string.IsNullOrEmpty(vsp.Password))
vsp.Password = DataOpenSSL.DecryptString(vsp.Password);
vsp.ShopId = BaseRegex.GetStringJson(ref shopStr, "shop_id");
if (list.Any(l => l.Phone == vsp.Phone))
continue;
list.Add(vsp);
}
return list;
}
/// <summary>
/// 新增微店店铺列表
/// </summary>
/// <param name="vDianList"></param>
/// <param name="isUpdateContainsShop">是否更新服务端已存在的店铺</param>
public void SaveVDianToServer(List<VDianShopLoginInfo> vDianList, bool isUpdateContainsShop = false)
{
var shops = vDianList;
if (!isUpdateContainsShop)
{
/// <summary>
/// 读取店铺列表
/// </summary>
/// <returns></returns>
List<VDianShopLoginInfo> list = new List<VDianShopLoginInfo>();
string url = BaseClass.BuildObjString("shop&act=auto_login_shop_v1");
string data = UserLogin.GetSignaturex();
data += "&siteid=5";
string html = GetHtml.PostUtf8(url, data);
if (!string.IsNullOrEmpty(html))
{
var m = BaseRegex.GetMatchRegex(ref html, "<shop([^>]+?)>");
for (int i = 0; m != null && i < m.Count; i++)
{
string shopStr = m[i].Groups[0].Value;
VDianShopLoginInfo vsp = new VDianShopLoginInfo();
vsp.ShopId = BaseRegex.GetStringJson(ref shopStr, "id");
if (vsp.ShopId == null)
continue;
vsp.Phone = BaseRegex.GetStringJson(ref shopStr, "user_name");
vsp.ShopName = BaseRegex.GetStringJson(ref shopStr, "name");
vsp.Password = BaseRegex.GetStringJson(ref shopStr, "password");
if (!string.IsNullOrEmpty(vsp.Password))
vsp.Password = DataOpenSSL.DecryptString(vsp.Password);
vsp.ShopId = BaseRegex.GetStringJson(ref shopStr, "shop_id");
if (list.Any(l => l.Phone == vsp.Phone))
continue;
list.Add(vsp);
}
}
// 写入服务端没有的店铺
shops = GlobalConfig.VDianShopLoginList.Where(s => !list.Any(l => l.ShopId == s.ShopId)).ToList();
}
for (int i = 0; i < shops.Count; i++)
{
var vShop = shops[i];
SaveVDianToServer(vShop);
}
}
/// <summary>
/// 将微店保存到服务器,如果已存在店铺,将会被覆盖
/// </summary>
public void SaveVDianToServer(VDianShopLoginInfo vShop)
{
string sShopPhone = vShop.Phone;
string sPassword = vShop.Password;
string sShopName = vShop.ShopName;
string sShopId = vShop.ShopId;
//string sGroup = "";
//var x = "123 +/";
//var r = GetHtml.UrlEncodeUtf8(DataOpenSSL.EncryptString(x));
//var rr = DataOpenSSL.DecryptString(GetHtml.UrlDecode(r));
var url = BaseClass.BuildObjString("shop&act=add_shop_vd_v1");
var data = UserLogin.GetSignaturex() + "&user_name=" + sShopPhone
+ "&password=" + GetHtml.UrlEncodeUtf8(DataOpenSSL.EncryptString(sPassword)) + "&name=" + sShopName
+ "&shop_id=" + sShopId //+ "&cat_name=" + sGroup
+ "&service=&buyer=&login_user=&upload_user="
+ "&collect_user=" + BaseClass.NickName + "&sub_account_name=&sub_account_password=";
data += "&site_id=5"; // 5为微店
var html = GetHtml.PostUtf8(url, data);
if (!string.IsNullOrEmpty(html) && html.Equals("Full Shop Count"))
{
BaseMsgForm.ShowInfo("当前版本支持的最大店铺数已满,请升级版本或另外购买一个账户");
}
if (string.IsNullOrEmpty(html))
{
Thread.Sleep(1000);
html = GetHtml.PostUtf8(url, data);
}
}
/// <summary>
/// 删除服务端的微店店铺
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public string DelServerVDianShop(string name)
{
string url = BaseClass.BuildObjString("shop&act=delete");
string data = UserLogin.GetSignaturex() + "&name=" + name;
data += "&site_id=5";
string html = GetHtml.PostUtf8(url, data);
return html;
}
private void dgvVDianShop_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvVDianShop.Columns[e.ColumnIndex].HeaderText;
string shopId = dgvVDianShop.Rows[e.RowIndex].Cells["colShopId"].Value.ParseToString();
string shopName = dgvVDianShop.Rows[e.RowIndex].Cells["colShopName"].Value.ParseToString();
switch (headerText)
{
case "检测":
CheckShopLogin(new string[] { shopId });
break;
case "删除":
if (BaseMsgForm.ShowConfirm("确定删除店铺吗?").DialogResult == DialogResult.Cancel)
return;
DeleteVDianShop(e.RowIndex);
DelServerVDianShop(shopName);
//StartUp.SaveVDianShopLogin();
break;
case "编辑":
//var shopInfo = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopId);
//ProductMappingVDianEditForm editForm = new ProductMappingVDianEditForm(shopInfo);
//editForm.SaveComplete += EditForm_SaveComplete;
//editForm.ShowDialog();
break;
case "重登":
//ProductMappingVDianLoginForm.IsRun = true;
//var vDian = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopId);
//var phone = "";
//var password = "";
//if (vDian != null)
//{
// phone = vDian.Phone;
// password = vDian.Password;
//}
//ProductMappingVDianLoginForm productMappingVDianLoginForm = new ProductMappingVDianLoginForm(phone, password);
//productMappingVDianLoginForm.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
//productMappingVDianLoginForm.ShowDialog();
//ProductMappingVDianLoginForm.IsRun = false;
break;
case "上货认证":
//ProductMappingVDianLoginForm.IsRun = true;
//var vDian1 = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopId);
//if (vDian1 != null)
//{
// if (vDian1.UpGoodAuth == "去认证")
// {
// ProductMappingVDianLoginForm productMappingVDianLoginForm1 = new ProductMappingVDianLoginForm(vDian1, "upAuth");
// productMappingVDianLoginForm1.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
// productMappingVDianLoginForm1.ShowDialog();
// }
// else
// {
// ProductMappingVDianLoginForm productMappingVDianLoginForm1 = new ProductMappingVDianLoginForm(vDian1, "mainAuth");
// productMappingVDianLoginForm1.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
// productMappingVDianLoginForm1.ShowDialog();
// }
//}
//ProductMappingVDianLoginForm.IsRun = false;
break;
case "接口授权":
//ProductMappingVDianLoginForm.IsRun = true;
//var vDian2 = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopId);
//ApiAuth(vDian2);
//ProductMappingVDianLoginForm.IsRun = false;
break;
case "接口模式2":
//var vDian3 = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopId);
//if (vDian3 != null)
//{
// ProductMappingVDianLoginForm productMappingVDianLoginForm3 = new ProductMappingVDianLoginForm(vDian3, "api2Auth");
// productMappingVDianLoginForm3.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
// productMappingVDianLoginForm3.ShowDialog();
//}
break;
default:
dgvVDianShop.Rows[e.RowIndex].Cells["colSelect"].Value = !(bool)dgvVDianShop.Rows[e.RowIndex].Cells["colSelect"].Value;
break;
}
}
private void EditForm_SaveComplete(object obj)
{
VDianShopLoginInfo vDianShopLoginInfo = obj as VDianShopLoginInfo;
if (vDianShopLoginInfo == null)
return;
//StartUp.SaveVDianShopLogin();
SaveVDianToServer(vDianShopLoginInfo);
DataGridViewRow dgvr = dgvVDianShop.Rows.Cast<DataGridViewRow>().Where(p =>
p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == vDianShopLoginInfo.ShopId).FirstOrDefault();
if (dgvr != null)
UpdateDataGridViewRowToken(dgvr, vDianShopLoginInfo);
}
private void dgvVDianShop_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
{
}
/// <summary>
/// 检测店铺登录授权等情况
/// </summary>
/// <param name="shopIds"></param>
/// <param name="isStart"></param>
public void CheckShopLogin(string[] shopIds, bool isStart = false)
{
if (!isStart)
{
this.statusBar.lblTaskStatus.Text = "正在检测...";
this.statusBar.pgbTaskProgress.Value = 0;
this.statusBar.pgbTaskProgress.Maximum = shopIds.Length;
this.statusBar.pgbTaskProgress.Text = "0" + "/" + shopIds.Length;
}
Task.Run(() =>
{
for (int i = 0; i < shopIds.Length; i++)
{
var vDian = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopIds[i]);
if (vDian != null)
{
// 获取登录状态
// string url = "https://d.weidian.com/weidian-pc/pc-vue-index/index.html"; // 微店商家后台
var result = new VDianUpProdMappingBLL().request_vdian_sell_com(vDian.Wdtoken, vDian.Cookies);
Thread.Sleep(200);
if (result.Contains("LOGIN ERROR"))
{
vDian.LoginStatus = 2;
}
else if (result.Contains("\"message\":\"OK\""))
{
vDian.LoginStatus = 1;
}
// 获取店铺token列表
vDian.ApiAuth = "未授权";
#region 检测微店授权1
//int authCount = 0;
//foreach (var vDianAppKey in ProductMappingVDianLoginForm.lstVDianAppKey)
//{
// VDianApiToken vDianApiToken = new VDianApiToken() { AppKey = vDianAppKey, ApiAuth = "未授权", ApiAccessToken = "" };
// string data = UserLogin.GetSignaturex() + "&act=get_token_list&shop_id=" + vDian.ShopId + "&appkey=" + vDianApiToken.AppKey.AppKey;
// string sVDianTokenApiUrl = ProductMappingVDianLoginForm.VDianUrl + "?" + BaseClass.ObjUrl + "weidian_token&appkey=" + vDianAppKey?.AppKey;
// var res = GetHtml.PostUtf8(sVDianTokenApiUrl, data);
// if (res.Contains(","))
// {
// var arr = res.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
// if (arr.Length > 0)
// {
// var arr1 = arr[0].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
// if (arr1.Length == 2 && !string.IsNullOrEmpty(arr1[1]))
// {
// vDianApiToken.ApiAccessToken = arr1[1];
// bool outDay = false;
// var tokenExists = vDian.LstWdApiToken.FirstOrDefault(t => t.AppKey?.AppKey == vDianApiToken.AppKey?.AppKey);
// if (tokenExists != null && tokenExists.LastRefreshDate != DateTime.Now.ToString("yyyyMMdd"))
// {
// outDay = true;
// }
// var apiJson = "";
// if (!outDay)
// {
// apiJson = request_vdian_api_auth(vDianApiToken.ApiAccessToken);
// if (apiJson.Contains("\"status_code\":0"))
// {
// vDianApiToken.ApiAuth = "已授权";
// authCount++;
// }
// // 频次超过上限
// else if (apiJson.Contains("上限"))
// vDian.ApiAuth = "接口上限";
// else if (string.IsNullOrEmpty(apiJson))
// vDianApiToken.ApiAuth = "获取失败";
// }
// if (outDay || apiJson.Contains("无效或已过期") && apiJson.Contains("access_token:")) // 有效期只有1天,所以即使已授权也直接刷新
// {
// sVDianTokenApiUrl = ProductMappingVDianLoginForm.VDianUrl + "?" + BaseClass.ObjUrl + "weidian_token";
// data = UserLogin.GetSignaturex() + "&act=reflesh_token&shop_id=" + vDian.ShopId + "&appkey=" + vDianApiToken.AppKey.AppKey;
// var refreshResult = GetHtml.PostUtf8(sVDianTokenApiUrl, data);
// if (refreshResult.StartsWith("ok,") && refreshResult.Length > 3)
// {
// vDianApiToken.ApiAccessToken = refreshResult.Substring(3);
// vDianApiToken.ApiAuth = "已授权";
// authCount++;
// }
// else if (refreshResult.StartsWith("ok,"))
// vDianApiToken.ApiAuth = "已过期";
// else
// vDianApiToken.ApiAuth = "获取失败";
// if (tokenExists != null)
// {
// tokenExists.LastRefreshDate = DateTime.Now.ToString("yyyyMMdd");
// }
// }
// }
// }
// }
// var vDianTokenExists = vDian.LstWdApiToken.FirstOrDefault(t => t.AppKey?.AppKey == vDianApiToken.AppKey?.AppKey);
// if (vDianTokenExists != null)
// {
// vDianTokenExists.ApiAccessToken = vDianApiToken.ApiAccessToken;
// vDianTokenExists.ApiAuth = vDianApiToken.ApiAuth;
// }
// else
// vDian.LstWdApiToken.Add(vDianApiToken);
//}
//vDian.ApiAuth = authCount < 2 ? "未授权" : "已授权";
#endregion
vDian.Api2Auth = "未授权";
#region 验证授权2
//if (!string.IsNullOrEmpty(vDian.WdApi2Token))
//{
// var api2Json = request_vdian_api_auth(vDian.WdApi2Token);
// if (api2Json.Contains("\"status_code\":0"))
// vDian.Api2Auth = "已授权";
// else if (api2Json.Contains("无效或已过期") && api2Json.Contains("access_token:"))
// {
// var refreshResult = MappingVDianThirdApiBLL.RefreshVDianAccessToken(vDian.WdApi2RefreshToken);
// if (refreshResult.Contains("\"status_code\":0"))
// {
// vDian.WdApi2Token = BaseRegex.GetMatchRegexString(refreshResult, "\"access_token\":\"([\\s\\S]*?)\"");
// vDian.WdApi2RefreshToken = BaseRegex.GetMatchRegexString(refreshResult, "\"refresh_token\":\"([\\s\\S]*?)\"");
// vDian.Api2Auth = "已授权";
// }
// else
// vDian.Api2Auth = "已过期";
// }
// // 频次超过上限
// else if (api2Json.Contains("上限"))
// vDian.Api2Auth = "接口上限";
// else
// vDian.Api2Auth = "获取失败";
//}
//// 是否通过上货认证
//var authResult = request_vdian_upgood_auth_com(vDian.Cookies);
//vDian.UpGoodAuth = "去认证";
//vDian.MainAuth = "未认证";
//if (authResult.ToLower().Replace("\"", "").Contains("status:unauth") || authResult.Contains("信息不存在"))
// vDian.UpGoodAuth = "去认证";
//else if (authResult.Contains("LOGIN ERROR"))
// vDian.UpGoodAuth = "请先登录";
//else if (authResult.ToLower().Replace("\"", "").Contains("成功"))
//{
// // 企业认证信息: {"status":{"code":0,"message":"成功","description":"成功"},"result":{"basicAuthModel":{"authTime":1596704856000,"certNo":"**************4311","certType":"BL","payTypes":["WD"],"updateTime":1596704856000,"userId":"1504742654","userName":"厦门*****有限公司","userType":"COMPANY","verifyTypes":["BL","LEGAL"]},"licenseAuthModel":{"beginTime":1596643200000,"businessAddress":"厦门市思明区东坪山路93号101单元","businessArea":"福建省-厦门市-思明区","certNo":"**************4311","certStatus":"USABLE","companyName":"厦门*****有限公司","createTime":1596704856000,"endTime":2214489600000,"licenseImg":"https://private.weidian.com/audit1504742654-776e00000173c2aee4650a217216_4032_3024.jpg","licenseType":1,"updateTime":1596704856000}}}
// if (authResult.Contains("\"CERT\"") == false && authResult.Contains("\"LEGAL\"") == false)
// vDian.UpGoodAuth = "需主体认证";
// else
// {
// vDian.UpGoodAuth = "认证成功";
// vDian.MainAuth = "认证成功";
// }
//}
//else
// vDian.UpGoodAuth = "获取失败";
#endregion
// 每天第一次打开验证的话要验证一个保存一次,防止没验证完关闭了再打开浪费接口资源。
if (!isStart)
AddDataGridViewRow(vDian);
}
if (this.Created && !isStart)
{
if (i % 5 == 0 || i == shopIds.Length - 1)
{
this.Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在检测...";
this.statusBar.pgbTaskProgress.Value = (i + 1);
this.statusBar.pgbTaskProgress.Text = (i + 1) + "/" + shopIds.Length;
}));
}
}
//if (isStart)
// StartUp.SaveVDianShopLogin();
}
if (this.Created && !isStart)
{
this.Invoke(new Action(() =>
{
//this.btnCheck.Text = "检测选中";
this.statusBar.lblTaskStatus.Text = "检测完毕";
}));
}
//if (!isStart)
// StartUp.SaveVDianShopLogin();
});
}
private void AddDataGridViewRow(VDianShopLoginInfo param, bool isRefresh = false)
{
if (!this.Created)
return;
this.Invoke(new Action(() =>
{
DataGridViewRow dgvr = dgvVDianShop.Rows.Cast<DataGridViewRow>().Where(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == param.ShopId).FirstOrDefault();
if (dgvr != null)
{
UpdateDataGridViewRowToken(dgvr, param);
if (!isRefresh)
{
// help to scroll to checked
dgvVDianShop.CurrentCell = dgvr.Cells[2];
}
}
else
{
int rowIndex = this.dgvVDianShop.Rows.Add(param.ShopId,
false,
param.ShopName,
param.Phone,
param.Cookies,
param.LoginStatus == 1 ? "正常" : "未登录",
"检测",
"重登",
param.UpGoodAuth,
param.ApiAuth,
param.Api2Auth,
"编辑",
"删除");
if (!isRefresh)
{
// help to scroll to latest checked
dgvVDianShop.CurrentCell = this.dgvVDianShop.Rows[rowIndex].Cells[2];
}
}
}));
}
private void UpdateDataGridViewRowToken(DataGridViewRow dgvr, VDianShopLoginInfo param)
{
if (dgvr == null || param == null)
return;
dgvr.Cells["colLoginStatus"].Value = (param.LoginStatus == 1 ? "正常" : "未登录");
dgvr.Cells["colCookie"].Value = param.Cookies;
dgvr.Cells["colUpGoodAuth"].Value = param.UpGoodAuth;
dgvr.Cells["colApiAuth"].Value = param.ApiAuth;
dgvr.Cells["colApi2Auth"].Value = param.Api2Auth;
dgvr.Cells["colPhone"].Value = param.Phone;
}
private void RefreshDataGridView()
{
if (isLoading)
{
//BaseMsgForm.ShowError("当前正在加载,请稍等");
return;
}
this.statusBar.pgbTaskProgress.Maximum = GlobalConfig.VDianShopLoginList.Count;
this.dgvVDianShop.Rows.Clear();
Task.Run(() =>
{
isLoading = true;
for (int i = 0; i < GlobalConfig.VDianShopLoginList.Count; i++)
{
if (i % 5 == 0 || i == GlobalConfig.VDianShopLoginList.Count - 1)
{
if (this.Created)
{
this.Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在加载...";
this.statusBar.pgbTaskProgress.Value = (i + 1);
this.statusBar.pgbTaskProgress.Text = (i + 1) + "/" + GlobalConfig.VDianShopLoginList.Count;
}));
}
}
AddDataGridViewRow(GlobalConfig.VDianShopLoginList[i], true);
}
if (this.Created)
{
this.Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "加载完毕";
}));
}
isLoading = false;
});
}
private void DeleteVDianShop(int rowIndex)
{
string shopId = this.dgvVDianShop.Rows[rowIndex].Cells["colShopId"].Value.ParseToString();
dgvVDianShop.Rows.RemoveAt(rowIndex);
GlobalConfig.VDianShopLoginList.RemoveAll(v => v.ShopId == shopId);
}
private void btnCheck_Click(object sender, EventArgs e)
{
if (this.btnCheck.Text == "检测选中")
{
List<string> shopIdList = GetCheckedTokenList();
if (!shopIdList.Any())
{
BaseMsgForm.ShowError("请选择需要检测的店铺");
return;
}
CheckShopLogin(shopIdList.ToArray());
}
}
private List<string> GetCheckedTokenList()
{
List<string> shopIdList = new List<string>();
for (int i = 0; i < dgvVDianShop.Rows.Count; i++)
{
if (dgvVDianShop.Rows[i].Cells["colSelect"].Value.ParseToBool())
{
string shopId = dgvVDianShop.Rows[i].Cells["colShopId"].Value.ParseToString();
shopIdList.Add(shopId);
}
}
return shopIdList;
}
// 批量导入店铺
private void btnImport_Click(object sender, EventArgs e)
{
// ProductMappingVDianLoginForm.IsRun = true;
ImportShop();
}
void ImportShop()
{
BaseMsgForm.ShowInfo("微店店铺导入格式:店铺手机号-----店铺密码\r\n多个店铺请每个店铺新起一行。");
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "文本文件(*.txt)|*.txt";
openFileDialog.RestoreDirectory = true;
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog.FileName, System.Text.Encoding.Default))
{
string fileName = openFileDialog.FileName;
string importStr = sr.ReadToEnd().Trim();
var strArr = importStr.Replace("\r", "").Split('\n');
for (int i = 0; i < strArr.Length; i++)
{
//if (ProductMappingVDianLoginForm.IsRun == false)
// break;
//try
//{
// // 通用格式
// if (strArr[i].Contains("-----"))
// {
// var productArr = strArr[i].Split(new string[] { "-----" }, StringSplitOptions.RemoveEmptyEntries);
// if (productArr.Length >= 2)
// {
// var phone = productArr[0];
// var password = productArr[1];
// ProductMappingVDianLoginForm productMappingVDianLoginForm = new ProductMappingVDianLoginForm(phone, password);
// productMappingVDianLoginForm.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
// productMappingVDianLoginForm.ShowDialog();
// }
// }
//}
//catch (Exception ex)
//{
//}
}
}
this.btnImport.Enabled = true;
}
}
/// <summary>
/// 读取微店上货认证信息
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
private string request_vdian_upgood_auth_com(string wdCookie)
{
var spider_token = BaseClass.GetMd5(DateTime.Now.ToString()).Substring(0, 4).ToLower();
//https://thor.weidian.com/authentication/realname.getUserAuthInfoWithScopes/1.0?param=%7B%22scopes%22:%22BASIC,LICENSE%22%7D&wdtoken=3a5523f7
string referer = "https://weidian.com/pay/member/credential-status.html?essentials=twoParam&redirect=https://d.weidian.com/weidian-pc/pc-vue-item/?spider_token=" + spider_token;
string url = "https://thor.weidian.com/authentication/realname.queryAuthStatus/1.0?v=1.0&timestamp=" + BaseClass.DateTimeToTimestampSeconds(DateTime.Now);
url = "https://thor.weidian.com/authentication/realname.getUserAuthInfoWithScopes/1.0?param=%7B%22scopes%22:%22BASIC,LICENSE%22%7D";
return request_vdian(url, referer, wdCookie);
}
/// <summary>
/// 微店主题认证
/// </summary>
/// <param name="wdCookie"></param>
/// <returns></returns>
private string request_vdian_main_auth_com(string wdCookie)
{
string referer = "https://h5.weidian.com/m/shop-certify/status.html";
string url = "https://h5.weidian.com/m/shop-certify/status.html";
return request_vdian(url, referer, wdCookie);
}
public static List<string> CheckTokenStrList = new List<string>()
{
BaseClass.VDianApi + "api?param={{}}&public={{\"method\":\"vdian.order.expresslist\",\"access_token\":\"{0}\",\"version\":\"1.0\"}}" ,
BaseClass.VDianApi + "api?param={{}}&public={{\"method\":\"vdian.sku.attrs.get\",\"access_token\":\"{0}\",\"version\":\"1.0\",\"format\":\"json\"}}" ,
BaseClass.VDianApi + "api?param={{\"pageNum\":0,\"pageSize\":10}}&public={{\"method\":\"vdian.supplies.list\",\"format\":\"json\",\"access_token\":\"{0}\",\"version\":\"1.0\"}}",
BaseClass.VDianApi + "api?param={{}}&public={{\"method\":\"dinggou.get.versions\",\"access_token\":\"{0}\",\"version\":\"1.0\",\"format\":\"json\"}}",
BaseClass.VDianApi + "api?param={{}}&public={{\"method\":\"get.user.dinggou.info\",\"access_token\":\"{0}\",\"version\":\"1.0\",\"format\":\"json\"}}",
};
/// <summary>
/// 验证token
/// </summary>
/// <param name="access_token"></param>
/// <returns></returns>
private string request_vdian_api_auth(string access_token)
{
string baseUrl = CheckTokenStrList[Randomx.GetId(CheckTokenStrList.Count)];
string url = string.Format(baseUrl, access_token);
//url = string.Format(CheckTokenStrList[0], access_token);
var result = request_vdian(url, "https://api.vdian.com/api", "");
while (result.Contains("上限") && CheckTokenStrList.Count > 0)
{
Thread.Sleep(Randomx.GetId(300, 500));
CheckTokenStrList.Remove(baseUrl);
baseUrl = CheckTokenStrList[Randomx.GetId(CheckTokenStrList.Count)];
url = string.Format(baseUrl, access_token);
result = request_vdian(url, "https://api.vdian.com/api", "");
}
return result;
}
private string request_vdian(string url, string referer, string cookies)
{
HttpWebResponse response = null;
string responseText = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Accept = "*/*";
request.Headers.Add("Origin", @"https://weidian.com");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36";
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = referer;
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
request.Headers.Set(HttpRequestHeader.Cookie, cookies);
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
responseText = "error: " + e.Message;
}
catch (Exception ex)
{
if (response != null) response.Close();
responseText = "error: " + ex.Message;
}
if (response != null)
{
if (string.IsNullOrEmpty(responseText))
responseText = GetHtml.ReadResponse(response);
response.Close();
}
Thread.Sleep(500);
return responseText;
}
private void buttonX1_Click(object sender, EventArgs e)
{
GetHtml.OpenUrl("https://d.weidian.com/weidian-pc/pc-vue-item/");
}
private void btnLoginSelect_Click(object sender, EventArgs e)
{
//ProductMappingVDianLoginForm.IsRun = true;
if (this.btnLoginSelect.Text == "登录选中")
{
List<string> shopIdList = GetCheckedTokenList();
if (!shopIdList.Any())
{
BaseMsgForm.ShowError("请选择需要登录的店铺");
return;
}
foreach (var shopId in shopIdList)
{
//if (ProductMappingVDianLoginForm.IsRun == false)
// break;
var vDian = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopId);
if (vDian != null && !string.IsNullOrEmpty(vDian.Phone)/* && !string.IsNullOrEmpty(vDian.Password)*/)
{
//ProductMappingVDianLoginForm productMappingVDianLoginForm = new ProductMappingVDianLoginForm(vDian.Phone, vDian.Password);
//productMappingVDianLoginForm.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
//productMappingVDianLoginForm.ShowDialog();
}
}
}
}
private void btnAuthSelect_Click(object sender, EventArgs e)
{
//ProductMappingVDianLoginForm.IsRun = true;
//if (this.btnAuthSelect.Text == "授权选中")
//{
// List<string> shopIdList = GetCheckedTokenList();
// if (!shopIdList.Any())
// {
// BaseMsgForm.ShowError("请选择需要授权的店铺");
// return;
// }
// foreach (var shopId in shopIdList)
// {
// if (ProductMappingVDianLoginForm.IsRun == false)
// break;
// var vDian = GlobalConfig.VDianShopLoginList.FirstOrDefault(v => v.ShopId == shopId);
// ApiAuth(vDian);
// }
//}
}
private void ApiAuth(VDianShopLoginInfo vDian)
{
//if (vDian != null)
//{
// if (ProductMappingVDianLoginForm.lstVDianAppKey.Count > 0)
// {
// foreach (var appKey in ProductMappingVDianLoginForm.lstVDianAppKey)
// {
// if (ProductMappingVDianLoginForm.IsRun == false)
// break;
// ProductMappingVDianLoginForm productMappingVDianLoginForm2 = new ProductMappingVDianLoginForm(vDian, "apiAuth", appKey);
// if (ProductMappingVDianLoginForm.lstVDianAppKey.LastOrDefault() == appKey)
// productMappingVDianLoginForm2.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
// productMappingVDianLoginForm2.ShowDialog();
// }
// }
// else
// {
// if (ProductMappingVDianLoginForm.IsRun == false)
// return;
// ProductMappingVDianLoginForm productMappingVDianLoginForm2 = new ProductMappingVDianLoginForm(vDian, "apiAuth");
// productMappingVDianLoginForm2.SaveComplete += ProductMappingVDianLoginForm_SaveComplete;
// productMappingVDianLoginForm2.ShowDialog();
// }
//}
}
}
}