Ejemplo n.º 1
0
        public ApiResult SaveForCloud([FromUri] int tenant_id, [FromUri] string appaccount_id, [FromBody] UpdateAppAccountArgument model)
        {
            var appAccount = new AppAccountInfo
            {
                AppAccountId = appaccount_id,
                TenantId     = model.tenant_id,
                Name         = model.name,
                Type         = model.type,
                SourceId     = model.source_id,
                AppId        = model.app_id,
                AppSecret    = model.app_secret,
                AgentId      = model.agent_id,
                State        = (AppAccountState)model.state,
                Tag          = model.tag,
                CreateBy     = model.create_by,
                ModifyBy     = model.modify_by
            };

            ProviderGateway.AppAccountProvider.AddOrUpdate(tenant_id, appAccount, false);

            return(new ApiResult
            {
                ErrCode = 0
            });
        }
Ejemplo n.º 2
0
        internal static void SaveMultiTenant(AppAccountInfo info)
        {
            var metaObject = _MetaObjectProvider.GetObjectMeta(MultiTenantMetaObjectName, info.TenantId);
            var objectData = new ObjectData(metaObject);

            objectData.ID           = new Guid(info.AppAccountId);
            objectData.TenantID     = info.TenantId;
            objectData["Name"]      = info.Name;
            objectData["Type"]      = info.Type;
            objectData["SourceId"]  = info.SourceId;
            objectData["AppId"]     = info.AppId;
            objectData["AppSecret"] = info.AppSecret;
            objectData["State"]     = (int)info.State;
            objectData["AgentId"]   = info.AgentId;
            objectData["Tag"]       = info.Tag;
            objectData.ModifiedBy   = info.ModifyBy;
            objectData.ModifiedTime = DateTime.Now;

            var isExist = _DataAccessProvider.IsExists(MultiTenantMetaObjectName, info.TenantId, info.AppAccountId);

            if (isExist)
            {
                _DataAccessProvider.Update(objectData);
            }
            else
            {
                objectData.CreatedBy   = info.CreateBy;
                objectData.CreatedTime = DateTime.Now;
                _DataAccessProvider.Add(objectData);
            }
        }
Ejemplo n.º 3
0
        protected string GetOpenId(AppAccountInfo appAccount, string code)
        {
            var extend = new Dictionary <string, string>
            {
                { TemplateConst.ExtendCode, code },
                { TemplateConst.ExtendToken, ProviderGateway.TokenProvider.GetToken(appAccount) }
            };

            var requestTemplate = new DefaultApiTemplate(appAccount, TemplateConst.GetOpenId, extend);
            //TODO:这块会出现空引用需要加一下判断
            var openId = requestTemplate.GetResponse()[TemplateConst.OpenId];

            if (string.IsNullOrWhiteSpace(openId))
            {
                var message = string.Format("未获取到OpenId:tenantId={0},appAccountId={1},code={2}", appAccount.TenantId, appAccount.Id, code);
                AppConnectLogHelper.Error(message);
                throw new SDKResultException(message);
            }

            var cookie = CookieHelper.GetCookie();

            if (cookie.OpenIds == null)
            {
                cookie.OpenIds = new Dictionary <string, string>();
            }
            cookie.OpenIds.Add(appAccount.AppId, openId);
            CookieHelper.SetCookie(cookie);

            return(openId);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 增加开放平台帐号信息
        /// </summary>
        /// <param name="info"></param>
        internal static int Insert(AppAccountInfo info)
        {
            var db = Database.GetDatabase(DatabaseName.AppConnect);
            int id = 0;

            SafeProcedure.ExecuteNonQuery(db, "dbo.AppAccount_Insert", parameterMapper =>
            {
                parameterMapper.AddWithValue("@AppAccountId", info.AppAccountId);
                parameterMapper.AddWithValue("@TenantId", info.TenantId);
                parameterMapper.AddWithValue("@Name", info.Name);
                parameterMapper.AddWithValue("@Type", info.Type);
                parameterMapper.AddWithValue("@SourceId", info.SourceId);
                parameterMapper.AddWithValue("@AppId", info.AppId);
                parameterMapper.AddWithValue("@AppSecret", info.AppSecret);
                parameterMapper.AddWithValue("@AgentId", info.AgentId);
                parameterMapper.AddWithValue("@State", (short)info.State);
                parameterMapper.AddWithValue("@Tag", info.Tag);
                parameterMapper.AddWithValue("@UserId", info.CreateBy);
                parameterMapper.AddTypedDbNull("@Id", ParameterDirectionWrap.Output, DbType.Int32);
            }, o =>
            {
                id = (int)o.GetValue("@Id");
            });
            return(id);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 增加开放平台帐号信息
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="info"></param>
        /// <param name="isSaveMultiTenant"></param>
        public string Add(int tenantId, AppAccountInfo info, bool isSaveMultiTenant = true)
        {
            ArgumentHelper.AssertIsTrue(tenantId > 0, "TenantId is 0");
            ArgumentHelper.AssertIsTrue(info != null, "AppAccountInfo is null");
            ArgumentHelper.AssertIsTrue(info.TenantId > 0, "AppAccountInfo.TenantId is 0");
            ArgumentHelper.AssertNotNullOrEmpty(info.Name, "AppAccountInfo.AppAccountName is null or empty");
            ArgumentHelper.AssertNotNullOrEmpty(info.AppId, "AppAccountInfo.AppId is null or empty");
            ArgumentHelper.AssertNotNullOrEmpty(info.AppSecret, "AppAccountInfo.AppSecret is null or empty");

            AppAccountDao.Insert(info);

            if (isSaveMultiTenant && info.TenantId > 1)
            {
                try
                {
                    AppAccountDao.SaveMultiTenant(info);
                }
                catch (Exception ex)
                {
                    AppConnectLogHelper.Error("保存多租赁信息出错,AppAccountId=" + info.AppAccountId, ex);
                }
            }

            return(info.AppAccountId);
        }
Ejemplo n.º 6
0
        public MessageSendResult Send(AppAccountInfo appAccount, MessageInfo message)
        {
            var result = new MessageSendResult();

            if (appAccount == null)
            {
                appAccount = ProviderGateway.AppAccountProvider.Get(message.AppAccountId);
            }
            var token = ProviderGateway.TokenProvider.GetToken(appAccount);

            if (string.IsNullOrWhiteSpace(message.ToOpenId))
            {
                var appUsers  = ProviderGateway.AppUserAccountProvider.GetListByUserId(message.TenantId, message.ToUser.Split('|'), appAccount.AppId);
                var toOpenIds = new List <string>();
                foreach (var appUser in appUsers)
                {
                    toOpenIds.Add(appUser.OpenId);
                }
                message.ToOpenId = string.Join("|", toOpenIds);
            }

            var description = new StringBuilder();

            foreach (var detail in message.Content.Detail)
            {
                if (string.IsNullOrWhiteSpace(detail.Text))
                {
                    description.AppendFormat("{0}\n", detail.Value);
                }
                else
                {
                    description.AppendFormat("{0}:{1}\n", detail.Text, detail.Value);
                }
            }
            var picUrl = MediaDataHelper.GetPicUrl(message.ProductId, appAccount.Type.ToString());

            AppConnectLogHelper.DebugFormat("调用企业微信发送消息:Token{0};ToOpenId{1}; AgentId{2} ContentUrl{3}, ContentTitle{4}, description:{5}, pic:{6},tenantId:{7}", token, message.ToOpenId, appAccount.AgentId, message.Content.Url, message.Content.Title, description.ToString(), picUrl, appAccount.TenantId);

            if (string.IsNullOrEmpty(message.Content.Url))
            {
                message.Content.Url = AppConnectHostConfig.Cache[0] + string.Format("/Common/Error?title={0}&message={1}", HttpUtility.UrlEncode("友情提醒"), HttpUtility.UrlEncode("抱歉,此消息暂不支持在此查看,请在电脑浏览器中查看"));
            }
            WorkMessageSendResult sendResult = new WorkMessageSendResult();

            sendResult = WeChatSDK.Work.Message.SendNews(token, message.ToOpenId, Convert.ToInt32(appAccount.AgentId), message.Content.Title, description.ToString(), message.Content.Url, picUrl);
            if (sendResult.ErrCode == 0)
            {
                result.State = MessageState.Success;
                AppConnectLogHelper.DebugFormat("企业微信发送消息成功{0}", JsonConvert.SerializeObject(sendResult));
            }
            else
            {
                result.State = MessageState.Failed;
                AppConnectLogHelper.ErrorFormat("企业微信发送消息失败,errorCode:{0},errorMsg:{1},tenantId:{2},userId:{3}", sendResult.ErrCode, sendResult.ErrMsg, appAccount.TenantId, message.ToOpenId);
            }

            result.ErrMsg = SerializeHelper.Serialize(sendResult);
            return(result);
        }
Ejemplo n.º 7
0
        public List <MessageInfo> Build(AppAccountInfo appAccount, List <int> userIds, MessageInfo message)
        {
            var result = new List <MessageInfo>();

            if (string.IsNullOrWhiteSpace(message.ToOpenId))
            {
                if (userIds == null)
                {
                    userIds = message.ToUser.Split('|').Select(i => Convert.ToInt32(i)).ToList();
                }
                foreach (var userId in userIds)
                {
                    result.Add(new MessageInfo
                    {
                        Id              = message.Id,
                        BatchId         = message.BatchId,
                        TenantId        = message.TenantId,
                        FromUser        = message.FromUser,
                        ToUser          = userId.ToString(),
                        ToOpenId        = message.ToOpenId,
                        AppAccountId    = appAccount.AppAccountId,
                        TemplateIdShort = message.TemplateIdShort,
                        TemplateId      = message.TemplateId,
                        Content         = message.Content,
                        ContentJson     = message.ContentJson,
                        State           = message.State,
                        MessageId       = message.MessageId,
                        Result          = message.Result
                    });
                }
            }
            else
            {
                var openIds = message.ToOpenId.Split('|');
                foreach (var openId in openIds)
                {
                    result.Add(new MessageInfo
                    {
                        Id              = message.Id,
                        BatchId         = message.BatchId,
                        TenantId        = message.TenantId,
                        FromUser        = message.FromUser,
                        ToUser          = message.ToUser,
                        ToOpenId        = openId,
                        AppAccountId    = appAccount.AppAccountId,
                        TemplateIdShort = message.TemplateIdShort,
                        TemplateId      = message.TemplateId,
                        Content         = message.Content,
                        ContentJson     = message.ContentJson,
                        State           = message.State,
                        MessageId       = message.MessageId,
                        Result          = message.Result
                    });
                }
            }
            return(result);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 获取Ticket
        /// </summary>
        /// <param name="account"></param>
        /// <param name="ticketType"></param>
        /// <param name="getNewToken"></param>
        /// <returns></returns>
        public string GetTicket(AppAccountInfo account, string ticketType, bool getNewToken = false)
        {
            ArgumentHelper.AssertIsTrue(account != null, "AppAccountInfo is null");
            ArgumentHelper.AssertNotNullOrEmpty(ticketType, "ticketType is null or empty");

            var token          = ProviderGateway.TokenProvider.GetToken(account);
            var ticketInstance = TicketFactory.GetTicketIntance(account);

            return(ticketInstance.GetTicket(account, token, ticketType, getNewToken));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 获取Ticket实例
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        internal static TicketBase GetTicketIntance(AppAccountInfo account)
        {
            switch (account.Type)
            {
            case 21:    //钉钉
                return(DingTalkTicket.Intance);

            default:
                throw new ArgumentException("开放平台帐号类型无效[GetTicketIntance]:type=" + account.Type);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获取绑定批次Id
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public string GetBindBatchId(int tenantId, string appAccountId, int type, string redirectUrl)
        {
            var            appAccountPublic   = new AppAccountInfo();
            var            appAccountPublicId = string.Empty;
            AppAccountInfo appAccountPrivate  = null;

            //根据类型初始化信息
            if (string.IsNullOrWhiteSpace(appAccountId))
            {
                //公共账户方式
                appAccountPublic   = ProviderGateway.AppAccountProvider.GetPublicByType(type);
                appAccountPublicId = appAccountPublic.AppAccountId;
            }
            else
            {
                //私有账户方式
                appAccountPrivate = ProviderGateway.AppAccountProvider.Get(appAccountId);

                if (tenantId != 0 && tenantId != appAccountPrivate.TenantId)
                {
                    return(string.Empty);
                }

                tenantId = appAccountPrivate.TenantId;
                switch (appAccountPrivate.Type)
                {
                case 11:
                case 12:
                    appAccountPublic   = ProviderGateway.AppAccountProvider.GetPublicByType(appAccountPrivate.Type);
                    appAccountPublicId = appAccountPublic.AppAccountId;
                    break;

                default:
                    appAccountPublicId = appAccountPrivate.AppAccountId;
                    break;
                }
            }

            //记录回调信息
            var batchId         = Guid.NewGuid().ToString();
            var callbackContent = new CallbackContentInfo
            {
                BatchId           = batchId,
                TenantId          = tenantId,
                AppAccountPublic  = appAccountPublicId,
                AppAccountPrivate = appAccountPrivate == null ? null : appAccountPrivate.AppAccountId,
                Content           = redirectUrl,
                State             = CallbackContentState.RegisterBind
            };

            ProviderGateway.CallbackContentProvider.Add(callbackContent);

            return(batchId);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="account"></param>
        /// <param name="getNewToken"></param>
        /// <returns></returns>
        internal string GetToken(AppAccountInfo account, bool getNewToken = false)
        {
            var tokenInfo = GetTokenFromStorage(account);

            //未存储Token或者已经过期,重新获取Token
            if (getNewToken || tokenInfo == null || tokenInfo.ExpireTime <= DateTime.Now)
            {
                tokenInfo = GetTokenFromSDk(account);
                AdjustExpireTime(tokenInfo);
                SaveToken(tokenInfo);
            }
            return(tokenInfo.AccessToken);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 获取Ticket
        /// </summary>
        /// <param name="account"></param>
        /// <param name="token"></param>
        /// <param name="ticketType"></param>
        /// <param name="getNewTicket"></param>
        /// <returns></returns>
        internal string GetTicket(AppAccountInfo account, string token, string ticketType = TokenType.JsApi, bool getNewTicket = false)
        {
            var tokenInfo = GetTicketFromStorage(account, ticketType);

            //未存储Ticket或者已经过期,重新获取Ticket
            if (getNewTicket || tokenInfo == null || tokenInfo.ExpireTime <= DateTime.Now)
            {
                tokenInfo = GetTicketFromSDk(account, token, ticketType);
                AdjustExpireTime(tokenInfo);
                SaveTicket(tokenInfo);
            }
            return(tokenInfo.AccessToken);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// 数据映射
 /// </summary>
 /// <param name="record">记录</param>
 /// <param name="info">实体</param>
 private static void BuildInfo(IRecord record, AppAccountInfo info)
 {
     info.Id           = record.Get <int>("Id");
     info.AppAccountId = record.Get <string>("AppAccountId");
     info.TenantId     = record.Get <int>("TenantId");
     info.Name         = record.Get <string>("Name");
     info.Type         = record.Get <short>("Type");
     info.SourceId     = record.Get <string>("SourceId");
     info.AppId        = record.Get <string>("AppId");
     info.AppSecret    = record.Get <string>("AppSecret");
     info.AgentId      = record.Get <string>("AgentId");
     info.State        = (AppAccountState)record.Get <short>("State");
     info.Tag          = record.Get <string>("Tag");
 }
Ejemplo n.º 14
0
        public void TestAdd()
        {
            var appAccount = new AppAccountInfo();

            appAccount.AppAccountId = Guid.NewGuid().ToString();
            appAccount.TenantId     = 204233;
            appAccount.Name         = "开发公共";
            appAccount.Type         = 12;
            appAccount.SourceId     = "111";
            appAccount.AppId        = "222";
            appAccount.AppSecret    = "3333";
            appAccount.State        = AppAccountState.Enable;

            ProviderGateway.AppAccountProvider.Add(204233, appAccount);
        }
Ejemplo n.º 15
0
        protected override TokenInfo GetTicketFromSDk(AppAccountInfo account, string token, string ticketType)
        {
            var ticket = DingTalkSDK.JsApi.GetTicket(token);

            if (string.IsNullOrWhiteSpace(ticket.Ticket))
            {
                var ex = new SDKResultException(string.Format("未获取到钉钉Ticket:AppId={0},AppSecret={1},TicketType={2},ErrCode={3},ErrMsg={4}", account.AppId, account.AppSecret, ticketType, ticket.ErrCode, ticket.ErrMsg));
                AppConnectLogHelper.Error(ex);
                throw ex;
            }

            return(new TokenInfo
            {
                AppId = account.AppId + account.AppSecret + ticketType,
                AccessToken = ticket.Ticket,
                ExpireTime = DateTime.Now.AddSeconds(ticket.ExpiresIn)
            });
        }
Ejemplo n.º 16
0
        protected override TokenInfo GetTokenFromSDk(AppAccountInfo account)
        {
            var token = WeChatSDK.Work.Token.GetToken(account.AppId, account.AppSecret);

            if (string.IsNullOrWhiteSpace(token.AccessToken))
            {
                var ex = new SDKResultException(string.Format("未获取到企业微信AccessToken:AppId={0},AppSecret={1},ErrCode={2},ErrMsg={3}", account.AppId, account.AppSecret, token.ErrCode, token.ErrMsg));
                AppConnectLogHelper.Error(ex);
                throw ex;
            }

            return(new TokenInfo
            {
                AppId = account.AppId + account.AppSecret,
                AccessToken = token.AccessToken,
                ExpireTime = DateTime.Now.AddSeconds(token.ExpiresIn)
            });
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 更新开放平台帐号信息
        /// </summary>
        /// <param name="info"></param>
        internal static void Update(AppAccountInfo info)
        {
            var db = Database.GetDatabase(DatabaseName.AppConnect);

            SafeProcedure.ExecuteNonQuery(db, "dbo.AppAccount_Update", parameterMapper =>
            {
                parameterMapper.AddWithValue("@AppAccountId", info.AppAccountId);
                parameterMapper.AddWithValue("@TenantId", info.TenantId);
                parameterMapper.AddWithValue("@Name", info.Name);
                parameterMapper.AddWithValue("@Type", info.Type);
                parameterMapper.AddWithValue("@SourceId", info.SourceId);
                parameterMapper.AddWithValue("@AppId", info.AppId);
                parameterMapper.AddWithValue("@AppSecret", info.AppSecret);
                parameterMapper.AddWithValue("@AgentId", info.AgentId);
                parameterMapper.AddWithValue("@State", (short)info.State);
                parameterMapper.AddWithValue("@Tag", info.Tag);
                parameterMapper.AddWithValue("@UserId", info.ModifyBy);
            });
        }
Ejemplo n.º 18
0
 /// <summary>
 /// 增加或更新开放平台账户
 /// </summary>
 /// <param name="tenantId"></param>
 /// <param name="info"></param>
 /// <param name="isSaveMultiTenant"></param>
 public string AddOrUpdate(int tenantId, AppAccountInfo info, bool isSaveMultiTenant = true)
 {
     if (string.IsNullOrEmpty(info.AppAccountId))
     {
         return(Add(info.TenantId, info, isSaveMultiTenant));
     }
     else
     {
         var existAppAccount = Get(info.AppAccountId);
         if (existAppAccount == null)
         {
             return(Add(info.TenantId, info, isSaveMultiTenant));
         }
         else
         {
             Update(info.TenantId, info, isSaveMultiTenant);
             return(existAppAccount.AppAccountId);
         }
     }
 }
Ejemplo n.º 19
0
        internal static void AddOrUpdateCLoud(int tenantId, int userId, AppAccountInfo info)
        {
            var metaObject = CloudDataHelper.GetMetaObject(tenantId, "AppConnect.AppUser");
            List <ObjectData> objectDatas = new List <ObjectData>();
            ObjectData        objectdata  = new ObjectData(metaObject);

            objectdata.ID              = Guid.NewGuid();
            objectdata.CreatedBy       = userId;
            objectdata.CreatedTime     = DateTime.Now;
            objectdata.ModifiedBy      = userId;
            objectdata.ModifiedTime    = DateTime.Now;
            objectdata["StdIsDeleted"] = false;
            objectdata["TenantId"]     = tenantId;
            objectdata["StaffID"]      = info.CreateBy;
            objectdata["UserEmail"]    = info.CreateBy;


            objectDatas.Add(objectdata);
            CloudDataHelper.Add(metaObject, objectDatas);
        }
Ejemplo n.º 20
0
        internal static IMessage GetIntance(AppAccountInfo account)
        {
            switch (account.Type)
            {
            case 12:    //微信服务号
                return(WeChatServiceMessage.Intance);

            case 13:    //微信企业号
                return(WeChatEnterpriseMessage.Intance);

            case 14:
                return(WeChatWorkMessage.Intance);

            case 21:
                return(DingTalkMessage.Intance);

            default:
                throw new ArgumentException("开放平台帐号类型无效:type=" + account.Type);
            }
        }
Ejemplo n.º 21
0
        internal static AppAccountInfo GetMultiTenant(int tenantId, string appAccountId)
        {
            var objectData = _DataAccessProvider.GetEntity(MultiTenantMetaObjectName, tenantId, appAccountId);

            var appAccountInfo = new AppAccountInfo();

            appAccountInfo.AppAccountId = objectData.ID.ToString();
            appAccountInfo.Name         = objectData["Name"] as string;
            appAccountInfo.Type         = Convert.ToInt32(objectData["Type"]);
            appAccountInfo.SourceId     = objectData["SourceId"] as string;
            appAccountInfo.AppId        = objectData["AppId"] as string;
            appAccountInfo.AppSecret    = objectData["AppSecret"] as string;
            appAccountInfo.State        = (AppAccountState)Convert.ToInt32(objectData["State"]);
            appAccountInfo.AgentId      = objectData["AgentId"] as string;
            appAccountInfo.Tag          = objectData["Tag"] as string;
            appAccountInfo.CreateBy     = objectData.CreatedBy;
            appAccountInfo.ModifyBy     = objectData.ModifiedBy;
            appAccountInfo.TenantId     = objectData.TenantID;

            return(appAccountInfo);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 获取Token实例
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        internal static TokenBase GetTokenIntance(AppAccountInfo account)
        {
            switch (account.Type)
            {
            case 11:    //微信订阅号
            case 12:    //微信服务号
                return(WeChatServiceToken.Intance);

            case 13:    //微信企业号
                return(WeChatEnterpriseToken.Intance);

            case 14:
                return(WeChatWorkToken.Intance);

            case 21:
                return(DingTalkToken.Intance);

            default:
                throw new ArgumentException("开放平台帐号类型无效:type=" + account.Type);
            }
        }
Ejemplo n.º 23
0
        public ApiResult Create([FromUri] int tenant_id, [FromBody] AddAppAccountArgument model)
        {
            var appAccount = new AppAccountInfo
            {
                AppAccountId = Guid.NewGuid().ToString(),
                TenantId     = model.tenant_id,
                Name         = model.name,
                Type         = model.type,
                SourceId     = model.source_id,
                AppId        = model.app_id,
                AppSecret    = model.app_secret,
                AgentId      = model.agent_id,
                State        = ServiceInterface.Model.Enum.AppAccountState.Enable,
                Tag          = model.tag
            };

            var appAccountId = ProviderGateway.AppAccountProvider.Add(tenant_id, appAccount);

            return(new AddAppAccountResult
            {
                AppAccountId = appAccountId
            });
        }
Ejemplo n.º 24
0
        public ApiResult Update([FromBody] UpdateAppAccountArgument model, [FromUri] int tenant_id, [FromUri] string appaccount_id = "", [FromUri] string tag = "")
        {
            var appAccount = new AppAccountInfo
            {
                AppAccountId = _AppAccountId,
                TenantId     = model.tenant_id,
                Name         = model.name,
                Type         = model.type,
                SourceId     = model.source_id,
                AppId        = model.app_id,
                AppSecret    = model.app_secret,
                AgentId      = model.agent_id,
                State        = (AppAccountState)model.state,
                Tag          = model.tag
            };

            ProviderGateway.AppAccountProvider.Update(tenant_id, appAccount);

            return(new ApiResult
            {
                ErrCode = 0
            });
        }
Ejemplo n.º 25
0
        public List <MessageInfo> Build(AppAccountInfo appAccount, List <int> userIds, MessageInfo message)
        {
            var result = new List <MessageInfo>();

            result.Add(new MessageInfo
            {
                Id              = message.Id,
                BatchId         = message.BatchId,
                TenantId        = message.TenantId,
                FromUser        = message.FromUser,
                ToUser          = message.ToUser,
                ToOpenId        = message.ToOpenId,
                AppAccountId    = appAccount.AppAccountId,
                TemplateIdShort = message.TemplateIdShort,
                TemplateId      = message.TemplateId,
                Content         = message.Content,
                ContentJson     = message.ContentJson,
                State           = message.State,
                MessageId       = message.MessageId,
                Result          = message.Result
            });

            return(result);
        }
Ejemplo n.º 26
0
        public BindResult Bind(Dictionary <string, string> openIds, string batch, string userName, string password, string captcha)
        {
            var result = new BindResult
            {
                NeedCaptcha = false
            };

            var callback         = ProviderGateway.CallbackContentProvider.GetByBatchId(batch);
            var appAccountPublic = ProviderGateway.AppAccountProvider.Get(callback.AppAccountPublic);

            if (!openIds.ContainsKey(appAccountPublic.AppId))
            {
                result.Result  = 2;
                result.Message = "用户公有OpenId无效";
                return(result);
            }
            AppAccountInfo appAccountPrivate = null;

            if (callback.TenantId != 0)
            {
                appAccountPrivate = ProviderGateway.AppAccountProvider.Get(callback.AppAccountPrivate);
                if (!openIds.ContainsKey(appAccountPrivate.AppId))
                {
                    result.Result  = 2;
                    result.Message = "用户私有OpenId无效";
                    return(result);
                }
            }
            var openIdPublic = openIds[appAccountPublic.AppId];

            var currentAppUserAccount = ProviderGateway.AppUserAccountProvider.GetByOpenId(appAccountPublic.AppId, openIdPublic);

            if (currentAppUserAccount != null && currentAppUserAccount.State == AppUserAccountState.Activated)
            {
                result.Result  = 8;
                result.Message = "您已经绑定过了,无需重复绑定";
                return(result);
            }

            //验证发送时间
            if (RedisHelper.IsExist(RedisConstName.SendCheck + userName))
            {
                result.Result  = 6;
                result.Message = "绑定过于频繁";
                return(result);
            }

            // 校验邮箱是否存在
            var userId = Proxy.BeisenUserProxy.GetSecurityByUserName(userName);

            if (userId <= 0)
            {
                result.Result  = 5;
                result.Message = "未找到对应账户";
                return(result);
            }
            var tenantId = Proxy.BeisenUserProxy.GetTenantId(userId);

            var oldAppUserAccount = ProviderGateway.AppUserAccountProvider.GetByUserId(tenantId, userId, appAccountPublic.AppId);

            if (oldAppUserAccount != null && oldAppUserAccount.State == AppUserAccountState.Activated)
            {
                result.Result  = 7;
                result.Message = "帐号已绑定";
                return(result);
            }

            var newAppUserAccountMaster = new AppUserAccountInfo
            {
                AppId           = appAccountPublic.AppId,
                OpenId          = openIdPublic,
                TenantId        = tenantId,
                UserId          = userId,
                BeisenAccount   = userName,
                Type            = _type,
                State           = AppUserAccountState.Inactive,
                MasterAccountId = 0
            };
            var masterAccountId = ProviderGateway.AppUserAccountProvider.AddOrUpdate(tenantId, newAppUserAccountMaster);

            //增加私有关联关系
            if ((appAccountPublic.Type == 11 || appAccountPublic.Type == 12) && callback.TenantId != 0 && masterAccountId != 0)
            {
                var newAppAccountUser = new AppUserAccountInfo
                {
                    AppId           = appAccountPrivate.AppId,
                    OpenId          = openIds[appAccountPrivate.AppId],
                    TenantId        = tenantId,
                    UserId          = userId,
                    BeisenAccount   = userName,
                    Type            = _type,
                    State           = AppUserAccountState.Inactive,
                    MasterAccountId = masterAccountId
                };
                ProviderGateway.AppUserAccountProvider.AddOrUpdate(tenantId, newAppAccountUser);
            }
            // 记录发邮件记录
            var bindBatch = new BindBatchInfo
            {
                TenantId         = tenantId,
                AppUserAccountId = masterAccountId,
                BeisenAccount    = userName,
                Type             = _type,
                State            = BindBatchState.UnUse
            };
            var bindBatchId = ProviderGateway.BindBatchProvider.Add(tenantId, bindBatch);

            // 发送激活邮件
            string activateCode = CryptographyHelper.AESEncrypt(tenantId + "_" + bindBatchId);
            string emailBody    = GetEmailBody(userName, AppConnectHostConfig.Cache[0] + HostConst.UserActivate + "?code=" + activateCode);
            var    emailBatch   = EmailProxy.SendEmail(0, "iTalent登录邮件验证", "", userName, emailBody);

            RedisHelper.SetRedis(RedisConstName.SendCheck + userName, DateTime.Now.Ticks.ToString(), 180);
            ProviderGateway.BindBatchProvider.UpdateBatchId(tenantId, bindBatchId, emailBatch);

            return(result);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 从存储获取Ticket
        /// </summary>
        /// <param name="account"></param>
        /// <param name="ticketType"></param>
        /// <returns></returns>
        private static TokenInfo GetTicketFromStorage(AppAccountInfo account, string ticketType)
        {
            var result = TokenDao.Get(account.AppId + account.AppSecret + ticketType);

            return(result);
        }
Ejemplo n.º 28
0
        public List <MessageInfo> Build(AppAccountInfo appAccount, List <int> userIds, MessageInfo message)
        {
            var result = new List <MessageInfo>();

            if (string.IsNullOrWhiteSpace(message.ToOpenId))
            {
                if (userIds == null)
                {
                    userIds = message.ToUser.Split('|').Select(i => Convert.ToInt32(i)).ToList();
                }
                if (userIds.Count <= 1000)
                {
                    result.Add(new MessageInfo
                    {
                        Id              = message.Id,
                        BatchId         = message.BatchId,
                        TenantId        = message.TenantId,
                        FromUser        = message.FromUser,
                        ToUser          = message.ToUser,
                        AppAccountId    = appAccount.AppAccountId,
                        TemplateIdShort = message.TemplateIdShort,
                        TemplateId      = message.TemplateId,
                        Content         = message.Content,
                        ContentJson     = message.ContentJson,
                        State           = message.State,
                        MessageId       = message.MessageId,
                        Result          = message.Result
                    });
                }
                else
                {
                    var toUserList = new List <string>();
                    var toUser     = new List <int>();
                    for (var i = 1; i <= userIds.Count; i++)
                    {
                        toUser.Add(userIds[i]);
                        if (i % 1000 == 0)
                        {
                            toUserList.Add(string.Join("|", toUser));
                            toUser = new List <int>();
                        }
                    }

                    foreach (var user in toUserList)
                    {
                        result.Add(new MessageInfo
                        {
                            Id              = message.Id,
                            BatchId         = message.BatchId,
                            TenantId        = message.TenantId,
                            FromUser        = message.FromUser,
                            ToUser          = user,
                            AppAccountId    = appAccount.AppAccountId,
                            TemplateIdShort = message.TemplateIdShort,
                            TemplateId      = message.TemplateId,
                            Content         = message.Content,
                            ContentJson     = message.ContentJson,
                            State           = message.State,
                            MessageId       = message.MessageId,
                            Result          = message.Result
                        });
                    }
                }
            }
            else
            {
                var messageOpenIdList = message.ToOpenId.Split('|');
                if (messageOpenIdList.Length <= 1000)
                {
                    result.Add(new MessageInfo
                    {
                        Id              = message.Id,
                        BatchId         = message.BatchId,
                        TenantId        = message.TenantId,
                        FromUser        = message.FromUser,
                        ToUser          = message.ToUser,
                        ToOpenId        = message.ToOpenId,
                        AppAccountId    = appAccount.AppAccountId,
                        TemplateIdShort = message.TemplateIdShort,
                        TemplateId      = message.TemplateId,
                        Content         = message.Content,
                        ContentJson     = message.ContentJson,
                        State           = message.State,
                        MessageId       = message.MessageId,
                        Result          = message.Result
                    });
                }
                else
                {
                    var toOpenIdList = new List <string>();
                    var toOpenId     = new List <string>();
                    for (var i = 1; i <= messageOpenIdList.Length; i++)
                    {
                        toOpenId.Add(messageOpenIdList[i]);
                        if (i % 1000 == 0)
                        {
                            toOpenIdList.Add(string.Join("|", toOpenId));
                            toOpenId = new List <string>();
                        }
                    }

                    foreach (var openId in toOpenIdList)
                    {
                        result.Add(new MessageInfo
                        {
                            Id              = message.Id,
                            BatchId         = message.BatchId,
                            TenantId        = message.TenantId,
                            FromUser        = message.FromUser,
                            ToUser          = message.ToUser,
                            ToOpenId        = openId,
                            AppAccountId    = appAccount.AppAccountId,
                            TemplateIdShort = message.TemplateIdShort,
                            TemplateId      = message.TemplateId,
                            Content         = message.Content,
                            ContentJson     = message.ContentJson,
                            State           = message.State,
                            MessageId       = message.MessageId,
                            Result          = message.Result
                        });
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 29
0
        public BindResult Bind(Dictionary <string, string> openIds, string batch, string userName, string password, string captcha)
        {
            var result = new BindResult
            {
                NeedCaptcha = false
            };

            var callback         = ProviderGateway.CallbackContentProvider.GetByBatchId(batch);
            var appAccountPublic = ProviderGateway.AppAccountProvider.Get(callback.AppAccountPublic);

            if (!openIds.ContainsKey(appAccountPublic.AppId))
            {
                result.Result  = 2;
                result.Message = "用户公有OpenId无效";
                return(result);
            }
            AppAccountInfo appAccountPrivate = null;

            if (callback.TenantId != 0 && !string.IsNullOrEmpty(callback.AppAccountPrivate))
            {
                appAccountPrivate = ProviderGateway.AppAccountProvider.Get(callback.AppAccountPrivate);
                if (!openIds.ContainsKey(appAccountPrivate.AppId))
                {
                    result.Result  = 2;
                    result.Message = "用户私有OpenId无效";
                    return(result);
                }
            }
            var openIdPublic = openIds[appAccountPublic.AppId];

            var currentAppUserAccount = ProviderGateway.AppUserAccountProvider.GetByOpenId(appAccountPublic.AppId, openIdPublic);

            if (currentAppUserAccount != null && currentAppUserAccount.State == AppUserAccountState.Activated)
            {
                result.Result  = 8;
                result.Message = "您已经绑定过了,无需重复绑定";
                return(result);
            }

            //验证绑定时间
            //if (RedisHelper.IsExist(RedisConstName.MobileCheck + userName))
            //{
            //    result.Result = 6;
            //    result.Message = "绑定过于频繁";
            //    return result;
            //}

            var users = ProviderGateway.StaffProvider.GetByUserName(userName);

            if (users == null || users.Count <= 0)
            {
                result.Result  = 5;
                result.Message = "未找到对应账户";
                return(result);
            }

            var userId   = users.First().Key;
            var tenantId = Proxy.BeisenUserProxy.GetTenantId(userId);
            //判断用户是否已经绑定
            var oldAppUserAccount = ProviderGateway.AppUserAccountProvider.GetByUserId(tenantId, userId, appAccountPublic.AppId);

            if (oldAppUserAccount != null && oldAppUserAccount.State == AppUserAccountState.Activated)
            {
                result.Result  = 7;
                result.Message = "帐号已绑定";
                return(result);
            }

            var newAppUserAccountMaster = new AppUserAccountInfo
            {
                AppId           = appAccountPublic.AppId,
                OpenId          = openIdPublic,
                TenantId        = tenantId,
                UserId          = userId,
                BeisenAccount   = userName,
                Type            = _type,
                State           = AppUserAccountState.Activated,
                MasterAccountId = 0
            };
            var masterAccountId = ProviderGateway.AppUserAccountProvider.AddOrUpdate(tenantId, newAppUserAccountMaster);

            //增加私有关联关系
            if ((appAccountPublic.Type == 11 || appAccountPublic.Type == 12) && callback.TenantId != 0 && masterAccountId != 0 && !string.IsNullOrEmpty(callback.AppAccountPrivate))
            {
                var newAppAccountUser = new AppUserAccountInfo
                {
                    AppId           = appAccountPrivate.AppId,
                    OpenId          = openIds[appAccountPrivate.AppId],
                    TenantId        = tenantId,
                    UserId          = userId,
                    BeisenAccount   = userName,
                    Type            = _type,
                    State           = AppUserAccountState.Activated,
                    MasterAccountId = masterAccountId
                };
                ProviderGateway.AppUserAccountProvider.AddOrUpdate(tenantId, newAppAccountUser);
            }

            result.RedirectUrl = callback.Content;
            //RedisHelper.SetRedis(RedisConstName.MobileCheck + userName, DateTime.Now.Ticks.ToString(), 300);
            return(result);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// 通过SDK获取Ticket
 /// </summary>
 /// <param name="account"></param>
 /// <param name="token"></param>
 /// <param name="ticketType"></param>
 /// <returns></returns>
 protected abstract TokenInfo GetTicketFromSDk(AppAccountInfo account, string token, string ticketType);