private void DataListBind()
        {
            this.rptAdminUserList.DataSource = VShopHelper.GetAdminUserMsgList(1);
            this.rptAdminUserList.DataBind();
            System.Collections.Generic.IList <MessageTemplate> aliFuWuMessageTemplates = VShopHelper.GetAliFuWuMessageTemplates();
            this.rptAliFuWuMessageTemplateList.DataSource = aliFuWuMessageTemplates;
            this.rptAliFuWuMessageTemplateList.DataBind();
            int num = 0;

            this.cbPowerListDistributors.Items.Clear();
            foreach (System.Data.DataRow dataRow in VShopHelper.GetAdminUserMsgDetail(true).Rows)
            {
                System.Web.UI.WebControls.ListItem item = new System.Web.UI.WebControls.ListItem(dataRow["DetailName"].ToString(), dataRow["DetailType"].ToString());
                this.cbPowerListDistributors.Items.Add(item);
                this.cbPowerListDistributors.Items[num].Selected = (dataRow["IsSelected"].ToString() == "1");
                num++;
            }
            num = 0;
            this.cbPowerListMember.Items.Clear();
            foreach (System.Data.DataRow dataRow2 in VShopHelper.GetAdminUserMsgDetail(false).Rows)
            {
                System.Web.UI.WebControls.ListItem item2 = new System.Web.UI.WebControls.ListItem(dataRow2["DetailName"].ToString(), dataRow2["DetailType"].ToString());
                this.cbPowerListMember.Items.Add(item2);
                this.cbPowerListMember.Items[num].Selected = (dataRow2["IsSelected"].ToString() == "1");
                num++;
            }
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);

            this.WeixinAppId   = masterSettings.WeixinAppId;
            this.hfAppID.Value = masterSettings.WeixinAppId;
            string token_Message = TokenApi.GetToken_Message(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret);

            this.hfWeiXinAccessToken.Value = token_Message;
            this.ShowQRImage();
        }
Exemple #2
0
        protected void btnBindUser_Click(object sender, EventArgs e)
        {
            string str  = this.txt_phone.Text.Trim();
            string text = this.txt_pwd.Text;

            if (string.IsNullOrEmpty(str))
            {
                this.ShowMsg("请输入邮箱!", false);
            }
            if (string.IsNullOrEmpty(text))
            {
                this.ShowMsg("请输入密码!", false);
            }
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);
            string       str3           = string.Empty;

            if (!string.IsNullOrEmpty(masterSettings.DistributorLogoPic))
            {
                str3 = Globals.DomainName + masterSettings.DistributorLogoPic;
            }
            CustomerServiceSettings settings = CustomerServiceManager.GetMasterSettings(false);
            string tokenValue = TokenApi.GetTokenValue(settings.AppId, settings.AppSecret);
            string str5       = FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5").ToLower();

            if (!string.IsNullOrEmpty(tokenValue))
            {
                Dictionary <string, string> parameters = new Dictionary <string, string>();
                parameters.Add("unit", str);
                parameters.Add("password", str5);
                parameters.Add("unitname", masterSettings.SiteName);
                parameters.Add("activated", "1");
                parameters.Add("logo", str3);
                parameters.Add("url", "");
                parameters.Add("tel", masterSettings.ShopTel);
                parameters.Add("contact", "");
                parameters.Add("location", "");
                string str6 = EnterpriseApi.CreateEnterprise(tokenValue, parameters);
                if (!string.IsNullOrWhiteSpace(str6))
                {
                    string jsonValue = Common.GetJsonValue(str6, "errcode");
                    Common.GetJsonValue(str6, "errmsg");
                    if (jsonValue == "10020")
                    {
                        string unitId = EnterpriseApi.GetUnitId(tokenValue, str);
                        if (!string.IsNullOrEmpty(unitId))
                        {
                            settings.unitid   = unitId;
                            settings.unit     = this.txt_phone.Text;
                            settings.password = this.txt_pwd.Text;
                            CustomerServiceManager.Save(settings);
                            this.ShowMsgAndReUrl("绑定成功。", true, "SaleService.aspx");
                        }
                    }
                    else
                    {
                        this.ShowMsgAndReUrl("账号不存在!", true, "SaleService.aspx");
                    }
                }
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var Token = TokenApi.GetAccessToken("wx98a0e4afc412cd23", "afd66cf094de6ec67ba3406d32c16b88");

            Console.WriteLine(Token.access_token);
            Console.WriteLine("2332");
        }
Exemple #4
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            System.Data.DataTable dataTable      = ArticleHelper.GetNoImgMsgIdArticleList();
            SiteSettings          masterSettings = SettingsManager.GetMasterSettings(false);
            string text = TokenApi.GetToken(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret);

            text = JsonConvert.DeserializeObject <Token>(text).access_token;
            if (dataTable.Rows.Count > 0)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    string text2 = NewsApi.GetMedia_IDByPath(text, dataTable.Rows[i]["ImageUrl"].ToString());
                    text2 = NewsApi.GetJsonValue(text2, "media_id");
                    if (!string.IsNullOrEmpty(text2))
                    {
                        ArticleHelper.UpdateMedia_Id(0, Globals.ToNum(dataTable.Rows[i]["ArticleId"].ToString()), text2);
                    }
                }
            }
            dataTable = ArticleHelper.GetNoImgMsgIdArticleItemList();
            if (dataTable.Rows.Count > 0)
            {
                for (int j = 0; j < dataTable.Rows.Count; j++)
                {
                    string text3 = NewsApi.GetMedia_IDByPath(text, dataTable.Rows[j]["ImageUrl"].ToString());
                    text3 = NewsApi.GetJsonValue(text3, "media_id");
                    if (!string.IsNullOrEmpty(text3))
                    {
                        ArticleHelper.UpdateMedia_Id(1, Globals.ToNum(dataTable.Rows[j]["ID"].ToString()), text3);
                    }
                }
            }
            System.Web.HttpContext.Current.Response.Write("document.write('');");
            System.Web.HttpContext.Current.Response.End();
        }
Exemple #5
0
        protected void ChangePwd_Click(object sender, EventArgs e)
        {
            CustomerServiceSettings masterSettings = CustomerServiceManager.GetMasterSettings(false);

            if (string.IsNullOrEmpty(this.txt_phone.Text))
            {
                this.ShowMsg("请输入手机号码!", false);
            }
            if (string.IsNullOrEmpty(this.txt_pwd.Text))
            {
                this.ShowMsg("请输入密码!", false);
            }
            string tokenValue = TokenApi.GetTokenValue(masterSettings.AppId, masterSettings.AppSecret);

            if (!string.IsNullOrEmpty(tokenValue))
            {
                SiteSettings settings2 = SettingsManager.GetMasterSettings(false);
                string       str2      = string.Empty;
                if (!string.IsNullOrEmpty(settings2.DistributorLogoPic))
                {
                    str2 = Globals.DomainName + settings2.DistributorLogoPic;
                }
                string str3 = FormsAuthentication.HashPasswordForStoringInConfigFile(this.txt_pwd.Text, "MD5").ToLower();
                Dictionary <string, string> parameters = new Dictionary <string, string>();
                parameters.Add("unit", this.txt_phone.Text);
                parameters.Add("password", str3);
                parameters.Add("unitname", settings2.SiteName);
                parameters.Add("activated", "1");
                parameters.Add("logo", str2);
                parameters.Add("url", "");
                parameters.Add("tel", settings2.ShopTel);
                parameters.Add("contact", "");
                parameters.Add("location", "");
                string str4 = EnterpriseApi.UpdateEnterprise(tokenValue, parameters);
                if (!string.IsNullOrWhiteSpace(str4))
                {
                    string jsonValue = Common.GetJsonValue(str4, "errcode");
                    string str6      = Common.GetJsonValue(str4, "errmsg");
                    if (jsonValue == "0")
                    {
                        masterSettings.password = this.txt_pwd.Text;
                        CustomerServiceManager.Save(masterSettings);
                        this.ShowMsg("修改密码成功!", true);
                    }
                    else
                    {
                        this.ShowMsg("修改密码失败!(" + str6 + ")", false);
                    }
                }
                else
                {
                    this.ShowMsg("修改密码失败!", false);
                }
                this.enable = settings2.EnableSaleService;
            }
            else
            {
                this.ShowMsg("获取access_token失败!", false);
            }
        }
Exemple #6
0
        /// <summary>
        /// Exchanges an authorization code for an access token and refresh token
        /// </summary>
        /// <param name="authorizationCode">The authorization code</param>
        /// <returns>An access token, its expiration date, and a refresh token</returns>
        private async Task <(string accessToken, string refreshToken, DateTime expiration)> GetTokens(string authorizationCode)
        {
            string redirectUri  = Properties.Settings.Default.RedirectUri;
            string clientId     = Properties.Settings.Default.ClientId;
            string clientSecret = Properties.Settings.Default.ClientSecret.DecryptString();

            TokenApi tokenApi = new TokenApi()
            {
                AuthorizationHeader = new AuthorizationHeader(clientId, clientSecret)
            };

            dynamic json = await tokenApi.GetAccessCode(
                authorizationCode,
                redirectUri,
                errorCallback : (errorResponse) =>
            {
                MessageBox.Show(
                    errorResponse,
                    "Login failure",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            });

            int      expiresInSeconds = json.expires_in;
            DateTime expiration       = DateTime.UtcNow.AddSeconds(expiresInSeconds);

            return(json.access_token, json.refresh_token, expiration);
        }
        private void BindData()
        {
            this.rptAdminUserList.DataSource = VShopHelper.GetAdminUserMsgList(0);
            this.rptAdminUserList.DataBind();
            this.rptList.DataSource = VShopHelper.GetMessageTemplates();
            this.rptList.DataBind();
            int num = 0;

            this.cbPowerListDistributors.Items.Clear();
            foreach (DataRow row in VShopHelper.GetAdminUserMsgDetail(true).Rows)
            {
                ListItem item = new ListItem(row["DetailName"].ToString(), row["DetailType"].ToString());
                this.cbPowerListDistributors.Items.Add(item);
                this.cbPowerListDistributors.Items[num].Selected = row["IsSelected"].ToString() == "1";
                num++;
            }
            num = 0;
            this.cbPowerListMember.Items.Clear();
            foreach (DataRow row2 in VShopHelper.GetAdminUserMsgDetail(false).Rows)
            {
                ListItem item2 = new ListItem(row2["DetailName"].ToString(), row2["DetailType"].ToString());
                this.cbPowerListMember.Items.Add(item2);
                this.cbPowerListMember.Items[num].Selected = row2["IsSelected"].ToString() == "1";
                num++;
            }
            this.WeixinAppId   = this.siteSettings.WeixinAppId;
            this.hfAppID.Value = this.siteSettings.WeixinAppId;
            string str = TokenApi.GetToken_Message(this.siteSettings.WeixinAppId, this.siteSettings.WeixinAppSecret);

            this.hfWeiXinAccessToken.Value = str;
            this.ShowQRImage();
        }
Exemple #8
0
        public IActionResult Refresh([FromBody] TokenApi tokenApi)
        {
            if (tokenApi is null)
            {
                return(BadRequest("Invalid client request"));
            }
            Console.WriteLine(tokenApi.RefreshToken, tokenApi.AccessToken);

            string accessToken  = tokenApi.AccessToken;
            string refreshToken = tokenApi.RefreshToken;

            var principal = _tokenService.GetPrincipalFromExpiredToken(accessToken);
            var username  = principal.Identity.Name;

            var user = _repository.User.GetUserByEmail(username);

            if (user == null || user.RefreshToken != refreshToken || user.RefreshTokenExpiry <= DateTime.Now)
            {
                return(BadRequest("Invalid client request"));
            }

            var newAccessToken  = _tokenService.GenerateAccessToken(principal.Claims);
            var newRefreshToken = _tokenService.GenerateRefreshToken();

            user.RefreshToken = newRefreshToken;
            _repository.User.UpdateUser(user);
            _repository.Save();

            return(new ObjectResult(new
            {
                accessToken = newAccessToken,
                refreshToken = newRefreshToken
            }));
        }
Exemple #9
0
        private static void Send(MessageTemplate template, SiteSettings settings, MemberInfo user, bool sendFirst, MailMessage email, string innerSubject, string innerMessage, string smsMessage, TemplateMessage templateMessage)
        {
            if (template.SendEmail && (email != null))
            {
                if (sendFirst)
                {
                    EmailSender sender = CreateEmailSender(settings);
                    if ((sender == null) || !SendMail(email, sender))
                    {
                        Emails.EnqueuEmail(email, settings);
                    }
                }
                else
                {
                    Emails.EnqueuEmail(email, settings);
                }
            }
            bool sendSMS          = template.SendSMS;
            bool sendInnerMessage = template.SendInnerMessage;

            if ((template.SendWeixin && !string.IsNullOrWhiteSpace(template.WeixinTemplateId)) && (templateMessage != null))
            {
                TemplateApi.SendMessage(TokenApi.GetToken_Message(settings.WeixinAppId, settings.WeixinAppSecret), templateMessage);
            }
        }
Exemple #10
0
        private bool CreatMember(string OpenId, int ReferralUserId)
        {
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(true);
            string       tOKEN          = TokenApi.GetToken_Message(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret);
            string       nickName       = "";
            string       headImageUrl   = "";
            string       retInfo        = "";

            BarCodeApi.GetHeadImageUrlByOpenID(tOKEN, OpenId, out retInfo, out nickName, out headImageUrl);
            string     generateId = Globals.GetGenerateId();
            MemberInfo info       = new MemberInfo
            {
                GradeId        = MemberProcessor.GetDefaultMemberGrade(),
                UserName       = Globals.UrlDecode(nickName),
                OpenId         = OpenId,
                CreateDate     = DateTime.Now,
                SessionId      = generateId,
                SessionEndTime = DateTime.Now.AddYears(10),
                UserHead       = headImageUrl,
                ReferralUserId = ReferralUserId,
                Password       = HiCryptographer.Md5Encrypt("888888")
            };

            Globals.Debuglog(JsonConvert.SerializeObject(info), "_Debuglog.txt");
            return(MemberProcessor.CreateMember(info));
        }
Exemple #11
0
        protected override void Render(HtmlTextWriter writer)
        {
            base.Text = "";
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);

            this.htmlAppID = masterSettings.WeixinAppId;
            string weixinAppSecret = masterSettings.WeixinAppSecret;

            try
            {
                this.htmlToken = this.GetToken(this.htmlAppID, weixinAppSecret);
            }
            catch (Exception)
            {
            }
            this.htmlTimeStamp = WeixinSet.ConvertDateTimeInt(DateTime.Now).ToString();
            this.htmlSignature = this.GetSignature(this.htmlToken, this.htmlTimeStamp, this.htmlNonceStr, out this.htmlstring1);
            string token = TokenApi.GetToken(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret);

            MenuApi.GetMenus(token);
            base.Text = string.Concat(new string[]
            {
                "<script>wx.config({ debug: false,appId: '",
                this.htmlAppID,
                "',timestamp: '",
                this.htmlTimeStamp,
                "', nonceStr: '",
                this.htmlNonceStr,
                "',signature: '",
                this.htmlSignature,
                "',jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','getLocation']});</script>"
            });
            base.Render(writer);
        }
Exemple #12
0
        private bool CreatMember(string OpenId, int ReferralUserId, string AceessTokenDefault = "")
        {
            if (string.IsNullOrEmpty(AceessTokenDefault))
            {
                SiteSettings masterSettings = SettingsManager.GetMasterSettings(true);
                AceessTokenDefault = TokenApi.GetToken_Message(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret);
            }
            string urlToDecode = "";
            string userHead    = "";
            string text        = "";

            BarCodeApi.GetHeadImageUrlByOpenID(AceessTokenDefault, OpenId, out text, out urlToDecode, out userHead);
            string     generateId = Globals.GetGenerateId();
            MemberInfo memberInfo = new MemberInfo();

            memberInfo.GradeId        = MemberProcessor.GetDefaultMemberGrade();
            memberInfo.UserName       = Globals.UrlDecode(urlToDecode);
            memberInfo.OpenId         = OpenId;
            memberInfo.CreateDate     = System.DateTime.Now;
            memberInfo.SessionId      = generateId;
            memberInfo.SessionEndTime = System.DateTime.Now.AddYears(10);
            memberInfo.UserHead       = userHead;
            memberInfo.ReferralUserId = ReferralUserId;
            memberInfo.Password       = HiCryptographer.Md5Encrypt("888888");
            Globals.Debuglog(JsonConvert.SerializeObject(memberInfo), "_DebuglogScanRegisterUserInfo.txt");
            return(MemberProcessor.CreateMember(memberInfo));
        }
Exemple #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable    noImgMsgIdArticleList = ArticleHelper.GetNoImgMsgIdArticleList();
            SiteSettings masterSettings        = SettingsManager.GetMasterSettings(false);
            string       str = JsonConvert.DeserializeObject <Token>(TokenApi.GetToken(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret)).access_token;

            if (noImgMsgIdArticleList.Rows.Count > 0)
            {
                for (int i = 0; i < noImgMsgIdArticleList.Rows.Count; i++)
                {
                    string jsonValue = NewsApi.GetJsonValue(NewsApi.GetMedia_IDByPath(str, noImgMsgIdArticleList.Rows[i]["ImageUrl"].ToString()), "media_id");
                    if (!string.IsNullOrEmpty(jsonValue))
                    {
                        ArticleHelper.UpdateMedia_Id(0, Globals.ToNum(noImgMsgIdArticleList.Rows[i]["ArticleId"].ToString()), jsonValue);
                    }
                }
            }
            noImgMsgIdArticleList = ArticleHelper.GetNoImgMsgIdArticleItemList();
            if (noImgMsgIdArticleList.Rows.Count > 0)
            {
                for (int j = 0; j < noImgMsgIdArticleList.Rows.Count; j++)
                {
                    string str3 = NewsApi.GetJsonValue(NewsApi.GetMedia_IDByPath(str, noImgMsgIdArticleList.Rows[j]["ImageUrl"].ToString()), "media_id");
                    if (!string.IsNullOrEmpty(str3))
                    {
                        ArticleHelper.UpdateMedia_Id(1, Globals.ToNum(noImgMsgIdArticleList.Rows[j]["ID"].ToString()), str3);
                    }
                }
            }
            HttpContext.Current.Response.Write("document.write('');");
            HttpContext.Current.Response.End();
        }
        private void ShowQRImage()
        {
            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);
            string       tICKET         = BarCodeApi.CreateTicket(TokenApi.GetToken_Message(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret), "1", "QR_SCENE", "604800");

            this.CodeTicket         = tICKET;
            this.imgQRCode.ImageUrl = BarCodeApi.GetQRImageUrlByTicket(tICKET);
        }
Exemple #15
0
        /// <summary>
        /// Retrievs a token from the token endpoint, which is passed along to any subsequent call. Don't reuse the token across multiple runs of
        /// your program as they expire.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public async Task <ApiResponse> GetTokenAsync(Configuration config = null)
        {
            Trace.WriteLine($"Starting {MethodBase.GetCurrentMethod().Name}");
            ITokenApi api    = new TokenApi(config);
            var       result = await api.ApiTokenGetAsync();

            Trace.WriteLine($"Ending {MethodBase.GetCurrentMethod().Name}");
            return(result);
        }
        public IWebClient TokenandWebClientSetupRemoteCall(out string token)
        {
            WebClientWrapper wclient = new WebClientWrapper(new MockWebClient());

            var apiCall = new TokenApi(Settings.Default.BaseUrl, 1, Settings.Default.ApiDeveloperId, Settings.Default.ApiKey, wclient);
            token = apiCall.GetToken("*****@*****.**", "P@ssword123");

            return wclient;
        }
        public IWebClient TokenandWebClientSetupRemoteCall(out string token)
        {
            WebClientWrapper wclient = new WebClientWrapper(new MockWebClient());

            var apiCall = new TokenApi(Settings.Default.BaseUrl, 1, Settings.Default.ApiDeveloperId, Settings.Default.ApiKey, wclient);

            token = apiCall.GetToken("*****@*****.**", "P@ssword123");

            return(wclient);
        }
Exemple #18
0
        /// <summary>
        /// 发布微信菜单到微信公众号服务器。
        /// </summary>
        /// <returns></returns>
        public PublishWxMenuResponse PublishMenus()
        {
            var resp = new PublishWxMenuResponse();
            IList <WxMenuDto> initMenus = this.GetInitMenus(MenuClient.Weixin);
            Menu menu = new Menu();

            foreach (var info in initMenus.OrderBy(p => p.Sequence))
            {
                if ((info.Chilren == null) || (info.Chilren.Count == 0))
                {
                    menu.menu.button.Add(this.BuildMenu(info));
                    continue;
                }
                SubMenu item = new SubMenu
                {
                    name = info.Name
                };
                foreach (var info2 in info.Chilren.OrderBy(x => x.Sequence))
                {
                    item.sub_button.Add(this.BuildMenu(info2));
                }
                menu.menu.button.Add(item);
            }
            string json           = JsonConvert.SerializeObject(menu.menu);
            var    masterSettings = GetOfficalAccount();

            if (string.IsNullOrEmpty(masterSettings.AppId) || string.IsNullOrEmpty(masterSettings.AppSecret))
            {
                resp.AddMessage("您的服务号配置存在问题,请您先检查配置!").SetSuccess(false);
            }
            else
            {
                string token = TokenApi.GetToken(masterSettings.AppId, masterSettings.AppSecret);
                try
                {
                    token = (JsonConvert.DeserializeObject(token, typeof(Token)) as Token).access_token;
                    if (MenuApi.CreateMenus(token, json).Contains("ok"))
                    {
                        resp.AddMessage("成功的把自定义菜单保存到了微信").SetSuccess(true);
                    }
                    else
                    {
                        resp.AddMessage("操作失败!服务号配置信息错误或没有微信自定义菜单权限,请检查配置信息以及菜单的长度。")
                        .SetSuccess(false);
                    }
                }
                catch (Exception exception)
                {
                    resp.AddMessage(exception.Message + "---" + token + "---" + masterSettings.AppId + "---" + masterSettings.AppSecret)
                    .SetSuccess(false).Error = exception;
                }
            }

            return(resp);
        }
Exemple #19
0
        /// <summary>
        /// 接口访问凭据
        /// </summary>
        /// <param name="key">The key<see cref="object"/></param>
        /// <returns></returns>
        public string GetAccessToken(object key = null)
        {
            if (key == null)
            {
                return(WeChatApisContext.Current.TokenApi.SafeGet().AccessToken);
            }
            var api = new TokenApi();

            api.SetKey(key);
            return(api.SafeGet().AccessToken);
        }
Exemple #20
0
        private void BtnSave_Click(object sender, EventArgs e)
        {
            IList <MenuInfo> initMenus = VShopHelper.GetInitMenus(this.wid);

            Hishop.Weixin.MP.Domain.Menu.Menu menu = new Hishop.Weixin.MP.Domain.Menu.Menu();
            foreach (MenuInfo info in initMenus)
            {
                if ((info.Chilren == null) || (info.Chilren.Count == 0))
                {
                    menu.menu.button.Add(this.BuildMenu(info));
                }
                else
                {
                    SubMenu item = new SubMenu {
                        name = info.Name
                    };
                    foreach (MenuInfo info2 in info.Chilren)
                    {
                        item.sub_button.Add(this.BuildMenu(info2));
                    }
                    menu.menu.button.Add(item);
                }
            }
            bll     = new Chenduo.BLL.sf_website();
            website = bll.GetModelByWid(this.wid);
            if (website == null)
            {
                return;
            }

            string json = JsonConvert.SerializeObject(menu.menu);

            //SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);
            //if (string.IsNullOrEmpty(masterSettings.WeixinAppId) || string.IsNullOrEmpty(masterSettings.WeixinAppSecret))
            //{
            //    base.Response.Write("<script>alert('您的服务号配置存在问题,请您先检查配置!');location.href='PayConfig.aspx'</script>");
            //}
            //else if (MenuApi.CreateMenus(JsonConvert.DeserializeObject<Token>(TokenApi.GetToken(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret)).access_token, json).Contains("\"ok\""))
            //{
            //    this.ShowMsg("成功的把自定义菜单保存到了微信", true);
            //}
            if (string.IsNullOrEmpty(website.appid) || string.IsNullOrEmpty(website.appsecret))
            {
                base.Response.Write("<script>alert('您的服务号配置存在问题,请您先检查配置!');location.href='PayConfig.aspx'</script>");
            }
            else if (MenuApi.CreateMenus(JsonConvert.DeserializeObject <Token>(TokenApi.GetToken(website.appid, website.appsecret)).access_token, json).Contains("\"ok\""))
            {
                this.ShowMsg("成功的把自定义菜单保存到了微信", true);
            }
            else
            {
                this.ShowMsg("操作失败!服务号配置信息错误或没有微信自定义菜单权限", false);
            }
        }
Exemple #21
0
        /// <summary>
        /// 刷新访问凭据
        /// </summary>
        /// <param name="key">The key<see cref="object"/></param>
        public void RefreshAccessToken(object key = null)
        {
            if (key == null)
            {
                WeChatApisContext.Current.TokenApi.Update();
                return;
            }
            var api = new TokenApi();

            api.SetKey(key);
            api.Update();
        }
        public void TestLogin()
        {
            Mock <IWebClient> mockWebClient = new Mock <IWebClient>();

            mockWebClient.Setup(x => x.UploadString(new Uri(BaseUri, @"v2/account/token"), "POST", "{\"email\":\"[email protected]\",\"password\":\"Password@123\",\"hospitalId\":1,\"userTypeId\":1}")).Returns("{ \"$id\": \"1\", \"data\": [ { \"$id\": \"2\", \"access_token\": \"jq8_ntQSXkBFl8HaDX8dshTOjgweE6gbMQ-TgPmhZJ039ejlSFEmopkjIQdbfW3ymE96fkG7Jw2VjpaEc71CBta7ZGaUSncwi7bEO1d2c5wkwAQJ1d0Obk90rNRFcLaCn9QU7pfQlyJcCdRtS2icYmKfUzJmwlsuN7q2qyqtKRgWzM0aEPRL5E4hExwub5wEPdAIfpseFX6jCdEZeMuu_PScHdqdds5cVZtqA8_CHeQOD0YrHWYK11CPTJ0HoL8rz0HvZ-csnwo-KXcB1g3DNxrcbEtn2lq2LNn-1OkzvpFZ1ZpH5G1CKkEIfBw5wQgrihcG0m69vGizCn_ww2AgvelqXiM-uZOqer7VeQyimudhn22zc2CHQoLnknQzeJcX118eCjhcnND6yWDjiQXnSg\" } ] }");
            mockWebClient.Setup(x => x.Headers).Returns(new WebHeaderCollection());

            string url = Settings.Default.BaseUrl;

            var apiCall = new TokenApi(url, 1, Settings.Default.ApiDeveloperId, Settings.Default.ApiKey, mockWebClient.Object);

            Assert.IsNotNullOrEmpty(apiCall.GetToken("*****@*****.**", "Password@123"));
        }
        public void GetQuoteDataHazardPackingTypes()
        {
            TokenApi tokenApi = new TokenApi();

            String token = tokenApi.GetToken("*****@*****.**", "123456789").Token;

            GetQuoteDataApi getQuoteData = new GetQuoteDataApi(token);

            List <GeneralType> hazardPackingTypesFromApi = getQuoteData.Request().Quote.hazardPackingTypes;
            List <GeneralType> hazardPackingTypessFromDB = _quoteService.GetHazardPackingTypes();

            hazardPackingTypessFromDB.Should().BeEquivalentTo(hazardPackingTypesFromApi, "Hazard Packing Types are different");
        }
        public void GetQuoteDateFreightClass()
        {
            TokenApi tokenApi = new TokenApi();

            String token = tokenApi.GetToken("*****@*****.**", "123456789").Token;

            GetQuoteDataApi getQuoteData = new GetQuoteDataApi(token);

            List <GeneralType> freightClassesFromApi = getQuoteData.Request().Quote.freightClasses;
            List <GeneralType> freightClassesFromDB  = _quoteService.GetFreightClass();

            freightClassesFromDB.Should().BeEquivalentTo(freightClassesFromApi, "Freight Classes are different");
        }
        public void GetQuoteDataDisabledDate()
        {
            TokenApi tokenApi = new TokenApi();

            String token = tokenApi.GetToken("*****@*****.**", "123456789").Token;

            GetQuoteDataApi getQuoteData = new GetQuoteDataApi(token);

            List <DisabledDate> disablesDateFromApi = getQuoteData.Request().Quote.disabledDates;
            List <DisabledDate> disablesDateFromDB  = _quoteService.GetDisabledDates();

            disablesDateFromDB.Should().BeEquivalentTo(disablesDateFromApi, "Disabled Date are different");
        }
Exemple #26
0
        public T GetResponse <T>(string call)
        {
            var request  = GetRequest(call);
            var response = Client.Execute(request);

            Logger.Instance.AddLog(LogType.Debug, "请求返回" + response.StatusCode.ToString());
            if (response.StatusCode == HttpStatusCode.Forbidden)
            {
                TokenApi.GetNewToken();
                Token = BaseData.Instance.config["部落冲突"]["Token"];
                return(GetResponse <T>(call));
            }
            return(JsonConvert.DeserializeObject <T>(response.Content));
        }
Exemple #27
0
        public void GetBillingAddress(String email, String password)
        {
            TokenApi tokenApi = new TokenApi();
            String   token    = tokenApi.GetToken(email, password).Token;

            tokenApi.SetToken(token);

            GetCustomerBillingAddressApi getCustomerBillingAddressApi = new GetCustomerBillingAddressApi();
            List <Client> client = new ClientRepository().GetClient();

            BilingAddressTemp apiResultBillingAddress = getCustomerBillingAddressApi.Request();

            Address billingAddressFromBD = _billingAdressService.GetBillingAddress("*****@*****.**");

            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.AddressAccessorials, apiResultBillingAddress.BillingAddress.AddressAccessorials, "Assesorials are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.AddressId, apiResultBillingAddress.BillingAddress.AddressId, "AddressId are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.City, apiResultBillingAddress.BillingAddress.City, "Citys are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.CommercialType, apiResultBillingAddress.BillingAddress.CommercialType, "CommercialType are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.CompanyName, apiResultBillingAddress.BillingAddress.CompanyName, "CompanyName are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.Country, apiResultBillingAddress.BillingAddress.Country, "Country are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.DeliveryFromTime, apiResultBillingAddress.BillingAddress.DeliveryFromTime, "DeliveryFromTime are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.DeliveryInstructions, apiResultBillingAddress.BillingAddress.DeliveryInstructions, "DeliveryInstructions are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.DeliveryToTime, apiResultBillingAddress.BillingAddress.DeliveryToTime, "DeliveryToTime are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.IsCanada, apiResultBillingAddress.BillingAddress.IsCanada, "IsCanada are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.Lat, apiResultBillingAddress.BillingAddress.Lat, "Lat are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.Long, apiResultBillingAddress.BillingAddress.Long, "Long are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.PickUpInstructions, apiResultBillingAddress.BillingAddress.PickUpInstructions, "PickUpInstructions are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.PostalCode, apiResultBillingAddress.BillingAddress.PostalCode, "PostalCode are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ShippingFromTime, apiResultBillingAddress.BillingAddress.ShippingFromTime, "ShippingFromTime are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ShippingToTime, apiResultBillingAddress.BillingAddress.ShippingToTime, "ShippingToTime are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.State, apiResultBillingAddress.BillingAddress.State, "State are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.StateCode, apiResultBillingAddress.BillingAddress.StateCode, "StateCode are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.StreetLine1, apiResultBillingAddress.BillingAddress.StreetLine1, "StreetLine1 are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.StreetLine2, apiResultBillingAddress.BillingAddress.StreetLine2, "StreetLine2 are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.AddressContactId, apiResultBillingAddress.BillingAddress.ContactPerson.AddressContactId, "AddressContactId in Contact are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.Email, apiResultBillingAddress.BillingAddress.ContactPerson.Email, "Email in Contact are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.Ext, apiResultBillingAddress.BillingAddress.ContactPerson.Ext, "Ext in Contact are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.FirstName, apiResultBillingAddress.BillingAddress.ContactPerson.FirstName, "FirstName in Contact are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.isPrimary, apiResultBillingAddress.BillingAddress.ContactPerson.isPrimary, "isPrimary in Contact are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.LastName, apiResultBillingAddress.BillingAddress.ContactPerson.LastName, "LastName in Contact are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.Phone, apiResultBillingAddress.BillingAddress.ContactPerson.Phone, "Phone in Contact are not equel"));
            AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.ContactPerson.Position, apiResultBillingAddress.BillingAddress.ContactPerson.Position, "Position in Contact are not equel"));

            if (billingAddressFromBD.Location != null && apiResultBillingAddress.BillingAddress.Location != null)
            {
                AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.Location.AddressId, apiResultBillingAddress.BillingAddress.Location.AddressId, "AddressId in Location are not equel"));
                AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.Location.IsDefault, apiResultBillingAddress.BillingAddress.Location.IsDefault, "IsDefault in Location are not equel"));
                AssertsAccumulator.Accumulate(() => Assert.AreEqual(billingAddressFromBD.Location.Name, apiResultBillingAddress.BillingAddress.Location.Name, "Position in Location are not equel"));
            }
        }
Exemple #28
0
        static void Main(string[] args)
        {
            var basePath = "http://*****:*****@admin.com",
                Password = "******"
            });

            var recipesApi = new RecipesApi(basePath, token.Trim('"'));
            var itemsList  = recipesApi.RecipesGet();
            var item       = recipesApi.RecipesRecepieIdGet(itemsList.First().Id);
        }
Exemple #29
0
        public static string GetToken(string appid, string secret)
        {
            string token = TokenApi.GetToken(appid, secret);

            if (!string.IsNullOrEmpty(token))
            {
                Dictionary <string, string> dictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(token);
                if ((dictionary != null) && dictionary.ContainsKey("access_token"))
                {
                    return(dictionary["access_token"]);
                }
            }
            return(string.Empty);
        }
        public void ProcessRequest(HttpContext context)
        {
            wid = context.Session[DTKeys.SESSION_WEB_ID] as string;
            if (string.IsNullOrEmpty(wid))
            {
                return;
            }
            context.Response.ContentType = "text/plain";
            int result = 0;

            int.TryParse(context.Request["id"].ToString(), out result);
            if (result > 0)
            {
                CustomerServiceInfo     customer       = CustomerServiceHelper.GetCustomer(result);
                CustomerServiceSettings masterSettings = CustomerServiceManager.GetMasterSettings(false);
                string tokenValue = TokenApi.GetTokenValue(masterSettings.AppId, masterSettings.AppSecret);
                if (!string.IsNullOrEmpty(tokenValue))
                {
                    string str2 = CustomerApi.DeleteCustomer(tokenValue, customer.unit, customer.userver);
                    if (!string.IsNullOrWhiteSpace(str2))
                    {
                        string jsonValue = Common.GetJsonValue(str2, "errcode");
                        string str4      = Common.GetJsonValue(str2, "errmsg");
                        if (jsonValue == "0")
                        {
                            if (CustomerServiceHelper.DeletCustomer(result))
                            {
                                context.Response.Write("{\"type\":\"success\",\"data\":\"\"}");
                            }
                            else
                            {
                                context.Response.Write("{\"type\":\"error\",\"data\":\"删除客服失败!\"}");
                            }
                        }
                        else
                        {
                            context.Response.Write("{\"type\":\"error\",\"data\":\"" + str4 + "\"}");
                        }
                    }
                    else
                    {
                        context.Response.Write("{\"type\":\"error\",\"data\":\"删除客服失败!\"}");
                    }
                }
                else
                {
                    context.Response.Write("{\"type\":\"error\",\"data\":\"获取access_token失败!\"}");
                }
            }
        }
Exemple #31
0
        /// <summary>
        /// 支付成功微信提醒
        /// </summary>
        /// <param name="context"></param>
        private void sendPaySuccessMsg(System.Web.HttpContext context)
        {
            try
            {
                context.Response.ContentType = "application/json";
                string orderId = context.Request["orderid"];
                string uid     = context.Request["uid"];
                WriteLog("进入");
                string result = string.Empty;
                WriteLog("参数:" + orderId + " " + uid);
                MemberInfo member    = MemberProcessor.GetMember(int.Parse(uid));
                OrderInfo  orderInfo = OrderHelper.GetOrderInfo(orderId);

                SiteSettings    masterSettings  = SettingsManager.GetMasterSettings(false);
                TemplateMessage templateMessage = new TemplateMessage();
                templateMessage.Url        = "";                                            //单击URL
                templateMessage.TemplateId = "Rx4a6JWjSRlIwctN0SuwGa82cjpzBnpZQWdwHz9CWQE"; //Globals.GetMasterSettings(true).WX_Template_01;// "b1_ARggaBzbc5owqmwrZ15QPj9Ksfs0p5i64C6MzXKw";//消息模板ID
                templateMessage.Touser     = member.OpenId;                                 //用户OPENID


                TemplateMessage.MessagePart[] messateParts = new TemplateMessage.MessagePart[] {
                    new TemplateMessage.MessagePart {
                        Name = "first", Value = "您好,微信支付已成功!"
                    },
                    new TemplateMessage.MessagePart {
                        Name = "keyword1", Value = orderInfo.OrderId
                    },
                    new TemplateMessage.MessagePart {
                        Name = "keyword2", Value = orderInfo.GetTotal().ToString("F2") + "元"
                    },
                    new TemplateMessage.MessagePart {
                        Name = "keyword3", Value = orderInfo.ModeName
                    },
                    new TemplateMessage.MessagePart {
                        Name = "keyword4", Value = orderInfo.PayDate.ToString()
                    },
                    new TemplateMessage.MessagePart {
                        Name = "remark", /*Color = "#FF0000"*/ Value = "多谢您的惠顾!下单成功,正在等待接单,请留意接单通知!"
                    }
                };
                templateMessage.Data = messateParts;
                TemplateApi.SendMessage(TokenApi.GetToken_Message(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret), templateMessage);
                result = "ok";
                context.Response.Write("{\"result\":\"" + result + "\"}");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }
        public Mock<IWebClient> TokenandWebClientSetup(out string token)
        {
            string tokenResult = "Sample_Token";

            Mock<IWebClient> mockWebClient = new Mock<IWebClient>();

            mockWebClient.Setup(x => x.UploadString(new Uri(BaseUri, @"v2/account/token"), "POST",
                "{\"email\":\"[email protected]\",\"password\":\"Password@123\",\"hospitalId\":1,\"userTypeId\":1}"))
                .Returns("{\"$id\": \"1\",\"data\": [{\"$id\": \"2\",\"access_token\": \"" + tokenResult + "\"} ] }");

            mockWebClient.Setup(x => x.Headers).Returns(new WebHeaderCollection());

            var apiCall = new TokenApi(Settings.Default.BaseUrl, 1, Settings.Default.ApiDeveloperId, Settings.Default.ApiKey, mockWebClient.Object);
            //token = apiCall.GetToken("*****@*****.**", "P@ssword123");
            token = apiCall.GetToken("*****@*****.**", "Password@123");

            Assert.AreEqual(token, tokenResult);

            return mockWebClient;
        }