using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using BP.Sys;
using BP.DA;
using Newtonsoft.Json;
using System.Linq;
using System.Xml;
using System.Net;
using BP.Port;
using System.Runtime.CompilerServices;
namespace BP.Cloud.WeXinAPI
{
public class Glo2021
{
///
/// 执行安装
///
///
///
public static string MainBuess(XmlDocument xd)
{
string infoType = xd.FirstChild["InfoType"].InnerText;
//推送suite_ticket协议每十分钟微信推送一次,判断是推送ticket的情况,取得ticket保存到缓存中
if (infoType.Equals("suite_ticket"))
{
string suitTicket = xd.FirstChild["SuiteTicket"].InnerText;
Glo.Suite_ticket = suitTicket;
HttpContext.Current.Cache.Insert("suitTicket", suitTicket);
//HttpContext.Current.Response.Write("success");
return "success";
}
//授权成功通知回调
if (infoType.Equals("create_auth"))
{
//授权成功通知回调推送给服务商.
string authCode = xd.FirstChild["AuthCode"].InnerText;
HttpContext.Current.Cache.Insert("authcode", authCode);
try
{
//根据临时授权码,获得永久授权码并安装应用.
return BP.Cloud.WeXinAPI.Glo.InstallIt(authCode);
}
catch (Exception ex)
{
return "err@安装失败,失败信息:" + ex.Message;
}
}
//取消安装的,安装修改.
if (infoType.Equals("cancel_auth"))
{
string authCorpId = xd.FirstChild["AuthCorpId"].InnerText;
BP.Cloud.Org org = new BP.Cloud.Org();
int i = org.Retrieve("CorpID", authCorpId);
if (i == 1)
org.DoDelete();
return "成功卸载,欢迎下次使用.";
}
//授权变更.
if (infoType.Equals("change_auth"))
{
string authCode = xd.FirstChild["AuthCode"].InnerText;
HttpContext.Current.Cache.Insert("authcode", authCode);
return "change_auth执行成功.";
}
//通讯录变更
if (infoType.Equals("change_contact"))
{
string changeType = xd.FirstChild["ChangeType"].InnerText;
string SuiteId = xd.FirstChild["SuiteId"].InnerText;//第三方应用ID
string corpID = xd.FirstChild["AuthCorpId"].InnerText;//授权企业的CorpID
BP.Cloud.Org org = new BP.Cloud.Org();
int i = org.Retrieve(BP.Cloud.OrgAttr.CorpID, corpID);
if (i == 0)
return "err@不应该查询不到 AuthCorpId= " + corpID + "的数据.";
switch (changeType)
{
case "create_user": //新建成员
return BP.Cloud.WeXinAPI.Glo.changeConCreateUser(xd, org);
case "update_user": //变更成员信息
return BP.Cloud.WeXinAPI.Glo.changeConUpdateUser(xd, org);
case "delete_user": //删除成员
return BP.Cloud.WeXinAPI.Glo.changeConUpdateUser(xd, org);
case "create_party": //新增部门
return BP.Cloud.WeXinAPI.Glo.changeConCreateDept(xd, org);
case "update_party": //更新部门
return BP.Cloud.WeXinAPI.Glo.changeConUpdateDept(xd, org);
case "delete_party": //删除部门
return BP.Cloud.WeXinAPI.Glo.changeConDelDept(xd, org);
default:
return "err@没有判断的类型" + changeType;
}
}
return "err@没有执行的判断." + infoType;
}
#region 通用的配置项 web.config 配置信息.
private static BP.WF.HttpWebResponseUtility _httpWebResponseUtility = null;
public static BP.WF.HttpWebResponseUtility HttpWebResponseUtility
{
get
{
if (_httpWebResponseUtility == null)
_httpWebResponseUtility = new BP.WF.HttpWebResponseUtility();
return _httpWebResponseUtility;
}
}
///
/// 企业ID
///
public static string CorpID
{
get
{
return BP.Difference.SystemConfig.AppSettings["CorpID"];
}
}
///
/// 推广包ID
///
public static string TemplateId
{
get
{
return BP.Difference.SystemConfig.AppSettings["TemplateId"];
}
}
///
/// 服务器域名
///
public static string Domain
{
get
{
return BP.Difference.SystemConfig.AppSettings["Domain"];
}
}
///
/// 服务商ProviderSecret
///
public static string ProviderSecret
{
get
{
return BP.Difference.SystemConfig.AppSettings["ProviderSecret"];
}
}
///
/// 服务商应用ID-SuiteID
///
public static string SuiteID
{
get
{
return BP.Difference.SystemConfig.AppSettings["SuiteID"];
}
}
///
/// 服务商应用ID-密钥
///
public static string SuiteID_Secret
{
get
{
return BP.Difference.SystemConfig.AppSettings["SuiteID_Secret"];
}
}
///
/// 我们应用的值
///
public static string Token
{
get
{
return BP.Difference.SystemConfig.AppSettings["Token"];
}
}
///
/// 用于消息内容加密 EncodingAESKey
///
public static string EncodingAESKey
{
get
{
return BP.Difference.SystemConfig.AppSettings["EncodingAESKey"];
}
}
#endregion web.config配置信息.
///
/// 动态的凭证(经常用)(全局)
///
private static string _Suite_ticket = null;
public static string Suite_ticket
{
get
{
if (_Suite_ticket == null)
_Suite_ticket = HttpContext.Current.Cache["suitTicket"] as string;
return _Suite_ticket;
}
set
{
_Suite_ticket = value;
HttpContext.Current.Cache.Insert("suitTicket", value);
}
}
///
/// 获取第三方应用凭证
/// 检查表里是否有SuitAccessToken,如果存在并有效则返回
///
///
public static string getSuitAccessToken()
{
String accessToken = "";
GloVar glovar = new GloVar();
glovar.No = "suiteAccessToken";
GloVar glovarEx = new GloVar();
glovarEx.No = "suiteAccessTokenExpiresIn";
if (glovar.RetrieveFromDBSources() > 0)
{
//有效则返回
if (glovarEx.RetrieveFromDBSources() > 0)
{
if (DataType.IsNullOrEmpty(glovarEx.Val) == false
&& DateTime.Compare(Convert.ToDateTime(DateTime.Now),
Convert.ToDateTime(glovarEx.Val)) < 0)
{
//如果没有失效,就直接返回表里数据.
accessToken = glovar.Val;
}
else
{
Dictionary dd = getSuitAccessToken_S();
//失效,重新取,更新
string suitToken = (string)dd["suite_access_token"];
string expiresIn = (string)dd["expires_in"];
glovar.Val = suitToken;
glovar.GroupKey = "WeiXin";
glovar.Update();
DateTime ss = DateTime.Now.AddSeconds(double.Parse(expiresIn));
glovarEx.Val = ss.ToString("yyyy-MM-dd HH:mm:ss");
glovarEx.GroupKey = "WeiXin";
glovarEx.Update();
}
}
}
else
{
//不存在,获取插入
Dictionary dd = getSuitAccessToken_S();
//失效,重新取,更新
string suitToken = (string)dd["suite_access_token"];
string expiresIn = (string)dd["expires_in"];
glovar.Val = suitToken;
glovar.GroupKey = "WeiXin";
glovar.Insert();
DateTime ss = DateTime.Now.AddSeconds(double.Parse(expiresIn));
glovarEx.Val = ss.ToString("yyyy-MM-dd HH:mm:ss");
glovarEx.GroupKey = "WeiXin";
glovarEx.Insert();
}
return accessToken;
}
///
/// 获取第三方应用凭证,服务器IP地址一定要先加入服务商的IP白明达中,否则验证失败。
///
///
public static Dictionary getSuitAccessToken_S()
{
//获取第三方应用凭证,获得suite_access_token以获取预授权码
IDictionary parameters = new Dictionary();
parameters.Add("suite_id", HttpUtility.UrlEncode(BP.Cloud.WeXinAPI.Glo.SuiteID));//应用suiteId
parameters.Add("suite_secret", HttpUtility.UrlEncode(BP.Cloud.WeXinAPI.Glo.SuiteID_Secret));//应用suiteSecret
parameters.Add("suite_ticket", BP.Cloud.WeXinAPI.Glo.Suite_ticket);//suite_ticket
string suiteUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token";
//根据参数:获得资源.
string res = Glo.HttpWebResponseUtility.HttpResponsePost_Json(suiteUrl,
JsonConvert.SerializeObject(parameters));
Dictionary dd = res.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (object)s.Split(':')[1].Trim('"'));
return dd;
}
///
/// 获取预授权码
/// 该API用于获取预授权码。预授权码用于企业授权时的第三方服务商安全验证。
///
///
public static void getPreAuthCode()
{
//获取第三方应用凭证
string suitAccessToken = getSuitAccessToken();
if (string.IsNullOrEmpty(suitAccessToken))
return;
string yuUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=" + suitAccessToken;
string res = Glo.HttpWebResponseUtility.HttpResponseGet(yuUrl);
Dictionary dd = res.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (object)s.Split(':')[1].Trim('"'));
string preAuthCode = (string)dd["pre_auth_code"];
if (string.IsNullOrEmpty(preAuthCode))
{
return;
}
//设置授权配置,该接口可对某次授权进行配置。可支持测试模式(应用未发布时)。
string resS = setSessionInfo(suitAccessToken, preAuthCode);
Dictionary ddresS = resS.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (object)s.Split(':')[1].Trim('"'));
string errcode = (string)ddresS["errcode"];
if (!errcode.Equals("0"))
{
return;
}
}
///
///设置授权配置
///该接口可对某次授权进行配置。可支持测试模式(应用未发布时)。
///请求方式:POST(HTTPS)
///请求地址: https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token=SUITE_ACCESS_TOKEN
///
public static string setSessionInfo(string suitAccessToken, string preAuthCode)
{
string url = "https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token=" + suitAccessToken;
string parameters = "{\"pre_auth_code\":\"" + preAuthCode + "\",\"session_info\":{\"appid\":[],\"auth_type\":0}}";
string res = Glo.HttpWebResponseUtility.HttpResponsePost_Json(url, parameters);
return res;
}
///
/// 获取企业凭证 第三方服务商在取得企业的永久授权码后,通过此接口可以获取到企业的access_token。
///获取后可通过通讯录、应用、消息等企业接口来运营这些应用。
///
///
public static string getAccessToken(BP.Cloud.Org org, string permanentCode)
{
//获取第三方应用凭证
string suitAccessToken = getSuitAccessToken();
// string permanentCode = CreateOrg();//获取永久授权码
IDictionary parameters = new Dictionary();
parameters.Add("auth_corpid", org.CorpID);//授权方corpid
parameters.Add("permanent_code", permanentCode);//永久授权码,通过get_permanent_code获取
string accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=" + suitAccessToken;
string res = Glo.HttpWebResponseUtility.HttpResponsePost_Json(accessTokenUrl, JsonConvert.SerializeObject(parameters));
Dictionary dd = res.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (object)s.Split(':')[1].Trim('"'));
string accessToken = (string)dd["access_token"];//授权方(企业)access_token,最长为512字节
string expires_in = (string)dd["expires_in"];
DateTime ss = DateTime.Now.AddSeconds(double.Parse(expires_in));
//更新accessToken到org表中
//BP.Cloud.Org org = new BP.Cloud.Org(corpid);
org.AccessToken = accessToken;
org.AccessTokenExpiresIn = ss.ToString("yyyy-MM-dd HH:mm:ss");
//org.Update();
return accessToken;
}
///
/// 组装安装授权页连接地址
///
public static string getInstallUr()
{
//获取第三方应用凭证
string suitAccessToken = getSuitAccessToken();
if (string.IsNullOrEmpty(suitAccessToken))
{
return "";
}
string yuUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=" + suitAccessToken;
string res = Glo.HttpWebResponseUtility.HttpResponseGet(yuUrl);
Dictionary dd = res.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (object)s.Split(':')[1].Trim('"'));
string preAuthCode = (string)dd["pre_auth_code"];
if (string.IsNullOrEmpty(preAuthCode))
{
return "";
}
//设置授权配置,该接口可对某次授权进行配置。可支持测试模式(应用未发布时)。
string resS = setSessionInfo(suitAccessToken, preAuthCode);
Dictionary ddresS = resS.Trim(new char[] { '{', '}' }).Split(',').ToDictionary(s => s.Split(':')[0].Trim('"'), s => (object)s.Split(':')[1].Trim('"'));
string errcode = (string)ddresS["errcode"];
if (!errcode.Equals("0"))
{
return "";
}
string redirect_uri = HttpUtility.UrlEncode(Glo.Domain + "WeChat/CallReg.aspx");
//跳转链接中,第三方服务商需提供suite_id、预授权码、授权完成回调URI和state参数。其中redirect_uri是授权完成后的回调网址,redirect_uri需要经过一次urlencode作为参数;state可填a - zA - Z0 - 9的参数值(不超过128个字节),用于第三方自行校验session,防止跨域攻击。
string urlInstall = "https://open.work.weixin.qq.com/3rdapp/install?suite_id=" + Glo.SuiteID +
"&pre_auth_code=" + preAuthCode + "&redirect_uri=" + redirect_uri + "&state=1";
return urlInstall;
}
///
/// 获取相应子节点的值
///
///
public static string JSON_SeleteNode(JToken json, string ReName)
{
try
{
string result = "";
if (json == null)
{
return result;
}
//这里6.0版块可以用正则匹配
var node = json.SelectToken("$.." + ReName);
if (node != null)
{
//判断节点类型
if (node.Type == JTokenType.String || node.Type == JTokenType.Integer || node.Type == JTokenType.Float)
{
//返回string值
result = node.Value