コード例 #1
0
ファイル: webviewController.cs プロジェクト: soon14/vzan
        public ActionResult PlatStoreDescriptionRichText(int id = 0)
        {
            //string token = AccessTokenContainer.GetAccessToken(AccessTokenContainer.GetFirstOrDefaultAppId());
            string token = WxHelper.GetToken(webview_appid, webview_appsecret, false);

            ViewBag.appid     = AccessTokenContainer.GetFirstOrDefaultAppId();
            ViewBag.ticket    = JsApiTicketContainer.GetJsApiTicket(JsApiTicketContainer.GetFirstOrDefaultAppId());
            ViewBag.timestamp = JSSDKHelper.GetTimestamp();
            ViewBag.nonceStr  = JSSDKHelper.GetNoncestr();
            ViewBag.signature = JSSDKHelper.GetSignature(ViewBag.ticket, ViewBag.nonceStr, ViewBag.timestamp, GetPageUrl());
            log4net.LogHelper.WriteInfo(this.GetType(), $"token={token};appid={ViewBag.appid};ticket={ViewBag.ticket};timestamp={ ViewBag.timestamp};nonceStr={ViewBag.nonceStr};signature={ViewBag.signature};pageUrl={GetPageUrl()}");

            if (id == 0)
            {
                // string temp = RedisUtil.Get<string>("temp_psd_description_0");
                ViewBag.description = "";//temp ?? "";
            }
            else
            {
                PlatStore platStore = PlatStoreBLL.SingleModel.GetModel(id);
                if (platStore == null || platStore.State == -1)
                {
                    ViewBag.description = "";
                    return(Content("店铺不存在或已删除"));
                }
                ViewBag.description = platStore.StoreDescription;
            }
            return(View());
        }
コード例 #2
0
        /// <summary>
        /// 注册企业APP信息;
        /// </summary>
        public void Register()
        {
            //registerService.RegisterMpAccount(Config.AppId, Config.AppSecret, "全视物联");
            //registerService.RegisterMpJsApiTicket(Config.AppId, Config.AppSecret, "全视物联Js");

            if (registerService == null)
            {
                RegisterWeixinConfig();
            }
            if (hasRegistered)
            {
                return;
            }
            hasRegistered = true;

            AccessTokenContainer.Register(Config.AppId, Config.AppSecret);
            JsApiTicketContainer.Register(Config.AppId, Config.AppSecret);

            /* 改为在单元测试中注册和修改菜单,方便而且快捷;
             * if (Config.MenuDefine != null)  //删除并且注册新的菜单;
             * {
             *  CommonApi.DeleteMenu(AccessToken);
             *  CommonApi.CreateMenu(AccessToken, Config.MenuDefine);
             * }
             */

            // if (!string.IsNullOrEmpty(MessageReceiveToken) && !string.IsNullOrEmpty(MessageReceiveEncodingAESKey))
            //{
            //     MsgCrypt = new WXBizMsgCrypt(MessageReceiveToken, MessageReceiveEncodingAESKey, Config.AppId);
            // }
        }
コード例 #3
0
ファイル: webviewController.cs プロジェクト: soon14/vzan
        public ActionResult RichText(int id = 0)
        {
            //string token = AccessTokenContainer.GetAccessToken(AccessTokenContainer.GetFirstOrDefaultAppId());
            string token = WxHelper.GetToken(webview_appid, webview_appsecret, false);

            ViewBag.appid     = AccessTokenContainer.GetFirstOrDefaultAppId();
            ViewBag.ticket    = JsApiTicketContainer.GetJsApiTicket(JsApiTicketContainer.GetFirstOrDefaultAppId());
            ViewBag.timestamp = JSSDKHelper.GetTimestamp();
            ViewBag.nonceStr  = JSSDKHelper.GetNoncestr();

            ViewBag.signature = JSSDKHelper.GetSignature(ViewBag.ticket, ViewBag.nonceStr, ViewBag.timestamp, GetPageUrl());
            ViewBag.pageUrl   = GetPageUrl();
            if (id == 0)
            {
                ViewBag.description = "";
            }
            else
            {
                EntGoods good = EntGoodsBLL.SingleModel.GetModel(id);
                if (good == null)
                {
                    ViewBag.description = "";
                    return(Content("产品不存在或已删除"));
                }
                ViewBag.description = good.description;
            }
            return(View());
        }
コード例 #4
0
ファイル: HomeController.cs プロジェクト: kaypawn/Weixin
        public ActionResult UserInfoCallback(string code, string state, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            if (state != Session["State"] as string)
            {
                return(Content("验证失败!请从正规途径进入!"));
            }
            OAuthAccessTokenResult result   = OAuthApi.GetAccessToken(AppId, AppSecret, code);
            OAuthUserInfo          userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid);
            string ticket = string.Empty;

            timestamp = JSSDKHelper.GetTimestamp();
            nonceStr  = JSSDKHelper.GetNoncestr();
            JSSDKHelper jssdkhelper = new JSSDKHelper();

            ticket            = JsApiTicketContainer.TryGetJsApiTicket(AppId, AppSecret);
            signature         = JSSDKHelper.GetSignature(ticket, nonceStr, timestamp, Request.Url.AbsoluteUri.ToString());
            ViewBag.signature = signature;
            ViewBag.appid     = AppId;
            ViewBag.timestamp = timestamp;
            ViewBag.noncestr  = nonceStr;
            return(View(userInfo));
        }
コード例 #5
0
        private void GetSingInfo(HttpContext context)
        {
            try
            {
                var list      = new List <object>();
                var appid     = WebConfigurationManager.AppSettings["wxappid"].ToString();
                var appsecret = WebConfigurationManager.AppSettings["wxsecret"].ToString();
                var timeStamp = JSSDKHelper.GetTimestamp();
                var nonceStr  = JSSDKHelper.GetNoncestr();
                var url       = context.Request.Params["urlinfo"];
                if (!JsApiTicketContainer.CheckRegistered(appid))
                {
                    JsApiTicketContainer.Register(appid, appsecret);
                }
                string      jsapiticket = JsApiTicketContainer.GetTicket(appid);
                JSSDKHelper cd          = new JSSDKHelper();
                var         signature   = cd.GetSignature(jsapiticket, nonceStr, timeStamp, url);
                list.Add(new { appid1 = appid, timeStamp1 = timeStamp, nonceStr1 = nonceStr, signature1 = signature });

                string jsonstrlist = JsonHelper.GetJsonString(new jsonResult {
                    code = "succ", result = list, count = list.Count
                });
                context.Response.Write(jsonstrlist);
            }
            catch (Exception)
            {
                string jsonstrlist = JsonHelper.GetJsonString(new jsonResult {
                    code = "succ", result = "", count = 0
                });
                context.Response.Write(jsonstrlist);
            }
        }
コード例 #6
0
ファイル: GetAdvController.cs プロジェクト: jzxyouok/RedBag
        public ActionResult Index()
        {
            var     code        = Request.Params["code"];
            var     appid       = ConfigurationManager.AppSettings["AppID"];
            var     secret      = ConfigurationManager.AppSettings["AppSecret"];
            WxModel model       = new WxModel();
            var     ticket      = JsApiTicketContainer.GetJsApiTicket(appid);
            var     noncestr    = JSSDKHelper.GetNoncestr();
            var     timeSpan    = JSSDKHelper.GetTimestamp();
            var     signature   = JSSDKHelper.GetSignature(ticket, noncestr, timeSpan, Request.Url.AbsoluteUri);
            var     accessToken = OAuthApi.GetAccessToken(appid, secret, code);

            if (OAuthApi.Auth(accessToken.access_token, accessToken.openid).errcode == ReturnCode.合法的OpenID)
            {
                accessToken = OAuthApi.RefreshToken(appid, accessToken.refresh_token);
            }
            var accessUserInfo = OAuthApi.GetUserInfo(accessToken.access_token, accessToken.openid);

            model.UnioId    = accessUserInfo.openid;
            model.TimeStamp = timeSpan;
            model.Signature = signature;
            model.NonceStr  = noncestr;

            return(View(model));
        }
コード例 #7
0
        public static void Register(string corpId, string corpSecret, string name = null)
        {
            //记录注册信息,RegisterFunc委托内的过程会在缓存丢失之后自动重试
            RegisterFunc = () =>
            {
                using (FlushCache.CreateInstance())
                {
                    var bag = new AccessTokenBag()
                    {
                        Name              = name,
                        CorpId            = corpId,
                        CorpSecret        = corpSecret,
                        ExpireTime        = DateTime.MinValue,
                        AccessTokenResult = new AccessTokenResult()
                    };
                    Update(BuildingKey(corpId, corpSecret), bag);
                    return(bag);
                }
            };
            RegisterFunc();

            JsApiTicketContainer.Register(corpId, corpSecret);   //连带注册JsApiTicketContainer

            ProviderTokenContainer.Register(corpId, corpSecret); //连带注册ProviderTokenContainer
        }
コード例 #8
0
ファイル: Global.asax.cs プロジェクト: xjh1230/sanfengli
 /// <summary>
 /// 注册所用微信公众号的账号信息
 /// </summary>
 private void RegisterSenparcWeixin()
 {
     //注册公众号
     AccessTokenContainer.Register(BaseClass.AppId, BaseClass.Secret);
     JsApiTicketContainer.Register(BaseClass.AppId, BaseClass.Secret);
     Config.DefaultCacheNamespace = BaseClass.DefaultCacheNamespace;
 }
コード例 #9
0
ファイル: CRMComm.cs プロジェクト: ganmkTrue/DTCMS_MVC
        /// <summary>
        /// 获取JSAPI_TICKET接口
        /// </summary>
        /// <returns></returns>
        public string GetJSAPI_Ticket(int accountId, string accessToken)
        {
            Model.weixin_account accountModel = accountBLL.GetModel(accountId); //公众平台账户信息
            string ticket = JsApiTicketContainer.TryGetTicket(accountModel.appid, accountModel.appsecret);

            return(ticket);
        }
コード例 #10
0
        public void ContainerTest()
        {
            //注册
            AccessTokenContainer.Register(base._appId, base._appSecret);

            //获取Ticket完整结果(包括当前过期秒数)
            var ticketResult = JsApiTicketContainer.GetJsApiTicketResult(base._appId);

            Assert.IsNotNull(ticketResult);

            //只获取Ticket字符串
            var ticket = JsApiTicketContainer.GetJsApiTicket(base._appId);

            Assert.AreEqual(ticketResult.ticket, ticket);
            Console.WriteLine(ticket);

            //getNewTicket
            {
                ticket = JsApiTicketContainer.TryGetJsApiTicket(base._appId, base._appSecret, false);
                Assert.AreEqual(ticketResult.ticket, ticket);

                ticket = JsApiTicketContainer.TryGetJsApiTicket(base._appId, base._appSecret, true);
                //Assert.AreNotEqual(ticketResult.ticket, ticket);//如果微信服务器缓存,此处会相同

                Console.WriteLine(ticket);
            }
        }
コード例 #11
0
        /// <summary>
        /// 注册应用凭证信息,此操作只是注册,不会马上获取Token,并将清空之前的Token
        /// </summary>
        /// <param name="appId">微信公众号后台的【开发】>【基本配置】中的“AppID(应用ID)”</param>
        /// <param name="appSecret">微信公众号后台的【开发】>【基本配置】中的“AppSecret(应用密钥)”</param>
        /// <param name="name">标记AccessToken名称(如微信公众号名称),帮助管理员识别</param>
        public static void Register(string appId, string appSecret, string name = null)
        {
            //记录注册信息,RegisterFunc委托内的过程会在缓存丢失之后自动重试
            RegisterFunc = () =>
            {
                using (FlushCache.CreateInstance())
                {
                    var bag = new AccessTokenBag()
                    {
                        //Key = appId,
                        Name                  = name,
                        AppId                 = appId,
                        AppSecret             = appSecret,
                        AccessTokenExpireTime = DateTime.MinValue,
                        AccessTokenResult     = new AccessTokenResult()
                    };
                    Update(appId, bag);
                    return(bag);
                }
            };
            RegisterFunc();

            //为JsApiTicketContainer进行自动注册
            JsApiTicketContainer.Register(appId, appSecret, name);

            //OAuthAccessTokenContainer进行自动注册
            OAuthAccessTokenContainer.Register(appId, appSecret, name);
        }
コード例 #12
0
ファイル: EssayController.cs プロジェクト: zanderzhg/Kard
        public async Task <ResultDto> JsSdkAsync(string url)
        {
            var configSection = _configuration.GetSection("WeChat:Web");
            //获取时间戳
            var timestamp = JSSDKHelper.GetTimestamp();
            //获取随机码
            var nonceStr  = JSSDKHelper.GetNoncestr();
            var appId     = configSection.GetValue <string>("AppId");
            var appSecret = configSection.GetValue <string>("AppSecret");
            //获取票证

            var jsTicket = await JsApiTicketContainer.TryGetJsApiTicketAsync(appId, appSecret);

            //获取签名
            //nonceStr = "Wm3WZYTPz0wzccnW";
            //jsTicket = "sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg";
            //timestamp = "1414587457";
            //url = "http://mp.weixin.qq.com?params=value";
            //url = url?? Request.GetAbsoluteUri();
            var signature = JSSDKHelper.GetSignature(jsTicket, nonceStr, timestamp, url);

            var resultDto = new ResultDto
            {
                Result  = true,
                Data    = new { appId, timestamp, nonceStr, signature },
                Message = "查询成功"
            };

            _logger.LogDebug(Serialize.ToJson(new { url, appId, jsTicket, timestamp, nonceStr, signature }));
            return(resultDto);
        }
コード例 #13
0
        /// <summary>
        /// 赠送订单成功
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public ActionResult SendGiftSuccess(long?orderId)
        {
            var order = new OrderViewModel();

            if (orderId.HasValue)
            {
                var tempOrder = OrderService.GetOrder(this.UserInfo.UserId, orderId.Value, false);
                if (tempOrder != null)
                {
                    var user = UserService.GetUserByUserId(tempOrder.UserId);
                    if (user != null)
                    {
                        order.SendUserMobile = user.Mobile;
                        order.SendUserName   = user.WxNickName;
                        order.OrderId        = tempOrder.OrderId;

                        //获取时间戳
                        var timestamp = JSSDKHelper.GetTimestamp();
                        //获取随机码
                        var         nonceStr = JSSDKHelper.GetNoncestr();
                        string      ticket   = JsApiTicketContainer.TryGetTicket(AppId, AppSecret);
                        JSSDKHelper jsHelper = new JSSDKHelper();
                        //获取签名
                        var signature = jsHelper.GetSignature(ticket, nonceStr, timestamp, Request.Url.AbsoluteUri);

                        ViewData["AppId"]     = AppId;
                        ViewData["Timestamp"] = timestamp;
                        ViewData["NonceStr"]  = nonceStr;
                        ViewData["Signature"] = signature;
                    }
                }
            }

            return(View(order));
        }
コード例 #14
0
        public ActionResult SelectOutlet(string outletCn)
        {
            var jsapiticket = JsApiTicketContainer.GetTicket(_corpId, _secret);

            ViewBag.appId     = _corpId;
            ViewBag.noncestr  = JSSDKHelper.GetNoncestr();
            ViewBag.timestamp = JSSDKHelper.GetTimestamp();
            ViewBag.signature = JSSDKHelper.GetSignature(jsapiticket, ViewBag.nonceStr, ViewBag.timestamp, AbsoluteUri());

            WxIdentifyDto dto = HttpContext.Session.GetObjectFromJson <WxIdentifyDto>("WxIdentify");

            if (string.IsNullOrWhiteSpace(outletCn))
            {
                ModelState.AddModelError("", "需要输入网点编号");
                return(View("Identify", dto));
            }

            var outlet = _outletCache.GetList().FindLast(x => x.Cn == outletCn);

            if (outlet != null)
            {
                SelectOutlet(outlet.Id, dto);
                return(View("Identify", dto));
            }
            else
            {
                ModelState.AddModelError("", "此编号没有对应的网点");
                return(View("Identify", dto));
            }
        }
コード例 #15
0
        public async Task <ActionResult> Approval()
        {
            var workSetting = Senparc.Weixin.Config.SenparcWeixinSetting["企业微信审批"] as ISenparcWeixinSettingForWork;
            var url         = "https://sdk.weixin.senparc.com/Work/Approval";

            //获取 UI 信息包
            var jsApiTicket = await JsApiTicketContainer.GetTicketAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, false);

            var jsApiUiPackage = await JSSDKHelper.GetJsApiUiPackageAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, url, jsApiTicket, false);

            ViewData["jsApiUiPackage"] = jsApiUiPackage;
            ViewData["thirdNo"]        = DateTime.Now.Ticks + Guid.NewGuid().ToString("n");
            ViewData["corpId"]         = workSetting.WeixinCorpId;
            ViewData["agentId"]        = workSetting.WeixinCorpAgentId;

            //注意这里需要使用 WeixinCorpAgentId,而不是 CorpId
            var agentConfigJsApiTicket = await JsApiTicketContainer.GetTicketAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, true);

            var agentJsApiUiPackage = await JSSDKHelper.GetJsApiUiPackageAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, url, agentConfigJsApiTicket, true);

            ViewData["agentJsApiUiPackage"] = agentJsApiUiPackage;

            //TODO:需要删除:
            ViewData["jsApiTicket"]            = jsApiTicket;
            ViewData["agentConfigJsApiTicket"] = agentConfigJsApiTicket;

            return(View());
        }
コード例 #16
0
        public ActionResult VerifyOutlet(int taskId, string password)
        {
            var jsapiticket = JsApiTicketContainer.GetTicket(_corpId, _secret);

            ViewBag.appId     = _corpId;
            ViewBag.noncestr  = JSSDKHelper.GetNoncestr();
            ViewBag.timestamp = JSSDKHelper.GetTimestamp();
            ViewBag.signature = JSSDKHelper.GetSignature(jsapiticket, ViewBag.nonceStr, ViewBag.timestamp, AbsoluteUri());

            WxIdentifyDto dto = HttpContext.Session.GetObjectFromJson <WxIdentifyDto>("WxIdentify");

            if (dto != null && !string.IsNullOrEmpty(password) && dto.OutletPassword == password)
            {
                if (taskId != 0)
                {
                    _weixinAppService.SetIdentifyTime(taskId);
                    _context.Clients.All.SendAsync("getMessage", "keypoint " + string.Format("{0},{1}", dto.OutletName, dto.DepotId));
                }
                else
                {
                    string issuer = null;
                    foreach (var w in dto.Workers)
                    {
                        issuer += $"{w.Cn} {w.Name},";
                    }
                    _weixinAppService.SetIdentifyEvent(dto.RouteId, $"{dto.OutletCn} {dto.OutletName}", issuer);
                }
                return(View("Information2", dto));
            }
            else
            {
                ModelState.AddModelError("", "网点密码不符,请重新输入");
                return(View("Identify", dto));
            }
        }
コード例 #17
0
        public static async Task <WeixinResponse> WeixinSignResponse(this string url)
        {
            var response = new WeixinResponse();

            var timestamp = JSSDKHelper.GetTimestamp();
            var noncestr  = JSSDKHelper.GetNoncestr();

            var ticket = await JsApiTicketContainer.TryGetJsApiTicketAsync(AppId, AppSecret);

            if (ticket.IsNullOrEmpty())
            {
                response.Message = "获取ticket出错了~~";
            }

            var signature = JSSDKHelper.GetSignature(ticket, noncestr, timestamp, url);

            if (signature.IsNullOrEmpty())
            {
                response.Message = "获取signature出错了~~";
            }

            response.Timestamp = timestamp;
            response.Noncestr  = noncestr;
            response.Ticket    = ticket;
            response.Signature = signature;

            return(response);
        }
コード例 #18
0
ファイル: JSSDKController.cs プロジェクト: mc7246/WeiXinMPSDK
        /// <summary>
        /// 结合使用 agentConfig
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> AgentConfig()
        {
            //此处演示同时支持多个应用的注册,请参考 appsettings.json 文件
            var workSetting = Senparc.Weixin.Config.SenparcWeixinSetting["企业微信审批"] as ISenparcWeixinSettingForWork;
            var url         = "https://sdk.weixin.senparc.com/Work/Approval";

            //获取 UI 信息包

            /* 注意:
             * 所有应用中,jsApiUiPackage 是必备的
             */
            var jsApiTicket = await JsApiTicketContainer.GetTicketAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, false);

            var jsApiUiPackage = await JSSDKHelper.GetJsApiUiPackageAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, url, jsApiTicket, false);

            ViewData["jsApiUiPackage"] = jsApiUiPackage;

            /* 注意:
             * 1、这里需要使用 WeixinCorpAgentId,而不是 WeixinCorpId
             * 2、agentJsApiUiPackage 是否需要提供,请参考官方文档,此处演示了最复杂的情况
             */
            ViewData["thirdNo"] = DateTime.Now.Ticks + Guid.NewGuid().ToString("n");
            ViewData["corpId"]  = workSetting.WeixinCorpId;
            ViewData["agentId"] = workSetting.WeixinCorpAgentId;
            var agentConfigJsApiTicket = await JsApiTicketContainer.GetTicketAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, true);

            var agentJsApiUiPackage = await JSSDKHelper.GetJsApiUiPackageAsync(workSetting.WeixinCorpId, workSetting.WeixinCorpSecret, url, agentConfigJsApiTicket, true);

            ViewData["agentJsApiUiPackage"] = agentJsApiUiPackage;

            return(View());
        }
コード例 #19
0
        public async Task <ActionResult> Test()
        {
            //注册
            await AccessTokenContainer.RegisterAsync(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret);

            var accessToken = AccessTokenContainer.TryGetAccessToken("wx4b58f9e96371d9ff", "43c5c4d9b8207634eb293a72ddad5bb1", true);

            var token = await AccessTokenContainer.TryGetAccessTokenAsync(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, false);

            //获取Ticket完整结果(包括当前过期秒数)
            var ticketResult = JsApiTicketContainer.GetJsApiTicketResult(TenPayV3Info.AppId);

            // //只获取Ticket字符串
            var ticket = JsApiTicketContainer.GetJsApiTicket(TenPayV3Info.AppId);

            //getNewTicket
            {
                ticket = JsApiTicketContainer.TryGetJsApiTicket(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, false);


                ticket = JsApiTicketContainer.TryGetJsApiTicket(TenPayV3Info.AppId, TenPayV3Info.Sub_AppSecret, true);
                //Assert.AreNotEqual(ticketResult.ticket, ticket);//如果微信服务器缓存,此处会相同
            }
            return(Content(token));
        }
コード例 #20
0
        /// <summary>
        /// 转账
        /// </summary>
        /// <returns></returns>
        public ActionResult TransferAccount(long orderId)
        {
            var payTipViewModel = new PayTipViewModel();
            var orderViewModel  = OrderService.GetOrderViewModel(this.UserInfo.UserId, orderId);

            payTipViewModel.OrderId      = orderViewModel.OrderId;
            payTipViewModel.PayMoney     = orderViewModel.ProductCount * orderViewModel.Price;
            payTipViewModel.IsPaySuccess = orderViewModel.Status == OrderStatus.Paid.GetHashCode();
            payTipViewModel.Message      = payTipViewModel.IsPaySuccess ? "支付成功" : "支付失败";
            payTipViewModel.BuyCount     = orderViewModel.ProductCount;

            //获取时间戳
            var timestamp = JSSDKHelper.GetTimestamp();
            //获取随机码
            var         nonceStr = JSSDKHelper.GetNoncestr();
            string      ticket   = JsApiTicketContainer.TryGetTicket(AppId, AppSecret);
            JSSDKHelper jsHelper = new JSSDKHelper();
            //获取签名
            var signature = jsHelper.GetSignature(ticket, nonceStr, timestamp, Request.Url.AbsoluteUri);

            ViewData["AppId"]     = AppId;
            ViewData["Timestamp"] = timestamp;
            ViewData["NonceStr"]  = nonceStr;
            ViewData["Signature"] = signature;

            ViewBag.uid = DotNet.Common.CryptographyHelper.Base64Encrypt(this.UserInfo.UserId.ToString());
            return(View(payTipViewModel));
        }
コード例 #21
0
        public static ShareInfo GetPayInfo(string prepayid)
        {
            var shareInfo = new ShareInfo();

            //检查是否已经注册jssdk
            if (!JsApiTicketContainer.CheckRegistered(ConfigHelper.WeChatAppId))
            {
                JsApiTicketContainer.Register(ConfigHelper.WeChatAppId, ConfigHelper.WeChatSecret);
            }
            JsApiTicketResult jsApiTicket = JsApiTicketContainer.GetJsApiTicketResult(ConfigHelper.WeChatAppId);
            JSSDKHelper       jssdkHelper = new JSSDKHelper();

            shareInfo.Ticket    = jsApiTicket.ticket;
            shareInfo.CorpId    = ConfigHelper.WeChatAppId.ToLower();
            shareInfo.Noncestr  = JSSDKHelper.GetNoncestr().ToLower();
            shareInfo.Timestamp = JSSDKHelper.GetTimestamp().ToLower();
            shareInfo.Package   = "prepay_id=" + prepayid.ToLower();

            RequestHandler requestHandler = new RequestHandler(HttpContext.Current);

            requestHandler.SetParameter("appId", shareInfo.CorpId);
            requestHandler.SetParameter("timeStamp", shareInfo.Timestamp);
            requestHandler.SetParameter("nonceStr", shareInfo.Noncestr);
            requestHandler.SetParameter("package", shareInfo.Package);
            requestHandler.SetParameter("signType", "MD5");

            requestHandler.SetKey(tenPayV3Info.Key);
            requestHandler.CreateMd5Sign();
            requestHandler.GetRequestURL();
            requestHandler.CreateSHA1Sign();
            shareInfo.PaySign = (requestHandler.GetAllParameters()["sign"]).ToString();
            return(shareInfo);
        }
コード例 #22
0
ファイル: WxManager.cs プロジェクト: zuoxianhe/cms
        public async Task <(bool Success, string Ticket, string ErrorMessage)> GetJsApiTicketAsync(string mpAppId, string mpAppSecret)
        {
            var    success      = false;
            var    errorMessage = string.Empty;
            string ticket       = null;

            try
            {
                ticket = await JsApiTicketContainer.TryGetJsApiTicketAsync(mpAppId, mpAppSecret);

                success = true;
            }
            catch (ErrorJsonResultException ex)
            {
                if (ex.JsonResult.errcode == ReturnCode.调用接口的IP地址不在白名单中)
                {
                    var startIndex = ex.JsonResult.errmsg.IndexOf("invalid ip ", StringComparison.Ordinal) + 11;
                    var endIndex   = ex.JsonResult.errmsg.IndexOf(" ipv6", StringComparison.Ordinal);
                    var ip         = ex.JsonResult.errmsg.Substring(startIndex, endIndex - startIndex);
                    errorMessage = $"调用接口的IP地址不在白名单中,请进入微信公众平台,将本服务器的IP地址 {ip} 添加至白名单";
                }
                else
                {
                    errorMessage = $"API 调用发生错误:{ex.JsonResult.errmsg}";
                }
            }
            catch (Exception ex)
            {
                errorMessage = $"执行过程发生错误:{ex.Message}";
            }

            return(success, ticket, errorMessage);
        }
コード例 #23
0
        public void ContainerTest()
        {
            //注册
            JsApiTicketContainer.Register(base._corpId, base._corpSecret);

            //获取Ticket完整结果(包括当前过期秒数)
            var ticketResult = JsApiTicketContainer.GetTicketResult(base._corpId, base._corpSecret);

            Assert.IsNotNull(ticketResult);
            Console.WriteLine(ticketResult.ticket);

            //只获取Ticket字符串
            var ticket = JsApiTicketContainer.GetTicket(base._corpId, base._corpSecret);

            Assert.AreEqual(ticketResult.ticket, ticket);

            //getNewTicket
            {
                ticket = JsApiTicketContainer.TryGetTicket(base._corpId, base._corpSecret, false);
                Assert.AreEqual(ticketResult.ticket, ticket);

                ticket = JsApiTicketContainer.TryGetTicket(base._corpId, base._corpSecret, true);
                Assert.AreEqual(ticketResult.ticket, ticket);//现在微信服务器有Ticket缓存,短时间内一致
                Console.WriteLine(ticketResult.ticket);
            }
        }
コード例 #24
0
ファイル: webviewController.cs プロジェクト: soon14/vzan
        /// <summary>
        /// 拼享惠产品描述编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult PinRichText(int id = 0)
        {
            string token = WxHelper.GetToken(webview_appid, webview_appsecret, false);

            ViewBag.appid     = AccessTokenContainer.GetFirstOrDefaultAppId();
            ViewBag.ticket    = JsApiTicketContainer.GetJsApiTicket(JsApiTicketContainer.GetFirstOrDefaultAppId());
            ViewBag.timestamp = JSSDKHelper.GetTimestamp();
            ViewBag.nonceStr  = JSSDKHelper.GetNoncestr();

            ViewBag.signature = JSSDKHelper.GetSignature(ViewBag.ticket, ViewBag.nonceStr, ViewBag.timestamp, Server.UrlDecode(GetPageUrl()));
            ViewBag.pageUrl   = GetPageUrl();

            if (id == 0)
            {
                //string temp = RedisUtil.Get<string>(PinGoodsBLL.key_new_pin_goods);
                ViewBag.description = ""; //temp ?? "";
            }
            else
            {
                PinGoods good = PinGoodsBLL.SingleModel.GetModel(id);
                if (good == null)
                {
                    ViewBag.description = "";
                    return(Content("产品不存在或已删除"));
                }
                ViewBag.description = good.description;
            }
            return(View("RichText"));
        }
コード例 #25
0
        public CommonApiTest()
        {
            //全局只需注册一次
            AccessTokenContainer.Register(_appId, _appSecret);

            //全局只需注册一次
            JsApiTicketContainer.Register(_appId, _appSecret);
        }
コード例 #26
0
        /// <summary>
        /// 注册公众号
        /// </summary>
        /// <typeparam name="UserKeyType">用户唯一Id类型</typeparam>
        /// <typeparam name="TenantKeyType">租户唯一Id类型</typeparam>
        /// <param name="key">获取公众号信息Key</param>
        /// <param name="appId">公众号AppId</param>
        /// <param name="appSecret">公众号AppSecret</param>
        /// <param name="token">公众号Token</param>
        /// <param name="encodingAESKey">公众号EncodingAESKey</param>
        /// <param name="name">公众号名称</param>
        /// <param name="userId">用户Id</param>
        /// <param name="tenantId">租户Id</param>
        public static void RegisterMpAccount <UserKeyType, TenantKeyType>(string key, string appId, string appSecret, string token, string encodingAESKey, string name = null, UserKeyType userId = default(UserKeyType), TenantKeyType tenantId = default(TenantKeyType))
        {
            MpInfoContainer <UserKeyType, TenantKeyType> .Register(key, appId, appSecret, token, encodingAESKey, name, userId, tenantId);

            AccessTokenContainer.Register(appId, appSecret, name);
            JsApiTicketContainer.Register(appId, appSecret, name);
            WxCardApiTicketContainer.Register(appId, appSecret, name);
        }
コード例 #27
0
        public string GetJsApi_Ticket()
        {
            var    appid     = _settingManager.GetSettingValue(AppSettings.Weixin.AppId);
            var    appsecret = _settingManager.GetSettingValue(AppSettings.Weixin.AppSecret);
            string ticket    = JsApiTicketContainer.TryGetJsApiTicket(appid, appsecret);

            return(ticket);
        }
コード例 #28
0
        public ActionResult ShowContent(string code, string state)
        {
            #region 获取用户code
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            if (state != Session["State"] as string)
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return(Content("验证失败!请从正规途径进入!"));
            }

            //企业号:通过验证,获取access_token
            var accessToken = Senparc.Weixin.QY.CommonAPIs.CommonApi.GetToken(CorpId, CorpSecret);
            if (accessToken.errcode != ReturnCode_QY.请求成功)
            {
                return(Content("错误:" + accessToken.errmsg));
            }
            //下面2个数据也可以自己封装成一个类,储存在数据库中(建议结合缓存)
            //如果可以确保安全,可以将access_token存入用户的cookie中,每一个人的access_token是不一样的
            //Session["OAuthAccessTokenStartTime"] = DateTime.Now;
            //Session["OAuthAccessToken"] = accessToken;

            //因为这里还不确定用户是否关注本微信,所以只能试探性地获取一下
            try
            {
                //已关注,可以得到详细信息
                userInfo             = Senparc.Weixin.QY.AdvancedAPIs.OAuth2Api.GetUserId(accessToken.access_token, code);
                ViewData["ByBase"]   = true;
                ViewData["UserId"]   = userInfo.UserId;
                ViewData["DeviceId"] = userInfo.DeviceId;
                string NickName = MailListApi.GetMember(accessToken.access_token, userInfo.UserId).name;
                Session["NickName"] = NickName;
            }
            catch (ErrorJsonResultException ex)
            {
                //未关注,只能授权,无法得到详细信息
                //这里的 ex.JsonResult 可能为:"{\"errcode\":40003,\"errmsg\":\"invalid openid\"}"
                return(Content("用户已授权,授权Token:" + accessToken.access_token + "ex:" + ex.Message));
            }
            #endregion
            #region
            //获取时间戳
            var timestamp = Senparc.Weixin.QY.Helpers.JSSDKHelper.GetTimestamp();
            //获取随机码
            var    nonceStr = Senparc.Weixin.QY.Helpers.JSSDKHelper.GetNoncestr();
            string ticket   = JsApiTicketContainer.TryGetTicket(CorpId, CorpSecret, false);
            //获取签名
            var signature = Senparc.Weixin.QY.Helpers.JSSDKHelper.GetSignature(ticket, nonceStr, timestamp, Request.Url.AbsoluteUri);
            #endregion
            var jssdkUiPackage = new Senparc.Weixin.QY.Helpers.JsSdkUiPackage(CorpId, timestamp.ToString(), nonceStr, signature);
            return(View(jssdkUiPackage));
        }
コード例 #29
0
        public (string, string, string, string) getJsSdkSign(string url)
        {
            var    timestamp    = JSSDKHelper.GetTimestamp();
            var    nonceStr     = JSSDKHelper.GetNoncestr();
            string jsapi_ticket = JsApiTicketContainer.TryGetJsApiTicket(_options.Value.AppId, _options.Value.AppSecret);
            string strurl       = url;
            var    signature    = JSSDKHelper.GetSignature(jsapi_ticket, nonceStr, timestamp, strurl);

            return(timestamp, nonceStr, signature, _options.Value.AppId);
        }
コード例 #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string ticket = string.Empty;

        timestamp = JSSDKHelper.GetTimestamp();
        nonceStr  = JSSDKHelper.GetNoncestr();
        appID     = "wx422044a7a4be9609";
        ticket    = JsApiTicketContainer.GetJsApiTicket(appID);
        signature = JSSDKHelper.GetSignature(ticket, nonceStr, timestamp, Request.Url.AbsoluteUri.ToString());
    }