Beispiel #1
0
        /// <summary>
        /// 微信支付-预支付订单(可本地调试)
        /// 商户在小程序或网页中先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易后调起支付。</summary>
        /// <remarks>
        /// 支付流程
        /// 小程序:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_4&index=3
        /// 微信内网页 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_4
        ///
        /// 统一下单接口
        /// 小程序:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1
        /// 微信内网页:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
        /// 内容是一样的
        /// </remarks>
        public static UnifiedOrderReply UnifiedOrder(
            string appId, string appSecret, string payUrl,
            string body, double fee, string openId, string orderNo, string ip, string deviceInfo)
        {
            var mchId  = WechatConfig.MchId;
            var mchKey = WechatConfig.MchKey;

            // 构建参数
            string url       = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            var    nonceStr  = BuildNonceStr();
            var    tradeType = "JSAPI";
            var    dict      = new Dictionary <string, string>();

            dict.Add("appid", appId);
            dict.Add("body", body);
            dict.Add("mch_id", mchId);
            dict.Add("nonce_str", nonceStr);
            dict.Add("notify_url", payUrl);
            dict.Add("openid", openId);
            dict.Add("out_trade_no", orderNo);
            dict.Add("spbill_create_ip", ip);
            dict.Add("total_fee", Convert.ToInt32(fee * 100).ToString());
            dict.Add("trade_type", tradeType);
            var sign = BuildPaySign(dict, mchKey);

            dict.Add("sign", sign);
            //WechatConfig.Log("WechatUnifiedOrder-dict", openId, dict.ToJson());

            // 发送
            var xml   = dict.ToXml("xml");
            var reply = HttpHelper.Post(url, xml);

            WechatConfig.Log("WechatUnifiedOrder", openId, xml, reply);
            return(reply.ParseXml <UnifiedOrderReply>());
        }
        public static WebchatJsUserinfo GetUserInfo(string userAgent, string CODE)
        {
            WechatConfig      wechatconfig = AccessTokenService.GetWechatConfig();
            WebchatJsUserinfo userinfo     = new WebchatJsUserinfo();
            string            url          = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wechatconfig.Appid + "&secret=" + wechatconfig.AppSecret + "&code=" + CODE + "&grant_type=authorization_code";

            HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(url, null, userAgent, null);

            Stream       stream = response.GetResponseStream();
            StreamReader sr     = new StreamReader(stream);
            string       result = sr.ReadToEnd();

            WechatJsToken token = JsonConvert.DeserializeObject <WechatJsToken>(result);


            string url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.access_token + "&openid=" + token.openid + "&lang=zh_CN";

            HttpWebResponse res     = HttpWebResponseUtility.CreateGetHttpResponse(url2, null, userAgent, null);
            Stream          stream2 = res.GetResponseStream();
            StreamReader    sr2     = new StreamReader(stream2);
            string          result2 = sr2.ReadToEnd();

            userinfo = JsonConvert.DeserializeObject <WebchatJsUserinfo>(result2);

            return(userinfo);
        }
Beispiel #3
0
        private void clearwechatconfigcache(HttpContext context)
        {
            var config = new WechatConfig();

            config.ClearCache();
            WebUtil.WriteJson(context, new { status = true });
        }
Beispiel #4
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                var    config = new WechatConfig();
                string token  = config.Token;
                if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString["echostr"]))
                {
                    LogHelper.WriteDebug("validate", context.Request.RawUrl);
                    MessageHandler.Valid(token);
                }
                else
                {
                    var recMsg = MessageHandler.ConvertMsgToObject(token);  //将消息转换成对象
                    if (recMsg != null)
                    {
                        MessageProcessor msgProcessor = MessageProcessor.Instance; //处理消息,继承接口IMessageProcessor来处理接受到的消息

                        msgProcessor.ProcessMessage(recMsg);                       //处理消息
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteError("API.Server", "Process Request Error", ex);
                context.Response.Write("非法操作");
            }
        }
Beispiel #5
0
        public ActionResult Index()
        {
            WechatConfig config = AccessTokenService.GetWechatConfig();

            ViewData["config"] = config;
            return(View());
        }
Beispiel #6
0
        public static async Task <WechatConfig> GetWechatConfig()
        {
            var config = CacheService.Get <WechatConfig>("WxConfig");

            if (config == null)
            {
                var token = await GetAccessToken();

                var url = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={token}&type=jsapi";

                config           = new WechatConfig();
                config.webHost   = WebConfig.WebHost;
                config.appId     = WebConfig.APPID;
                config.nonceStr  = "wechart";
                config.timestamp = ConvertDateTimeToInt(DateTime.Now).ToString();
                var jsUrl = $"{WebConfig.WebHost}/";
                var tiket = await HttpHelper.GetAsync <JsTicket>(url);

                var str = $"jsapi_ticket={tiket.ticket}&noncestr={config.nonceStr}&timestamp={config.timestamp}&url={jsUrl}";
                config.signature = HmacSha1Sign(str);
                CacheService.Set("WxConfig", config, new TimeSpan(0, 100, 0));

                LoggerHelper.Info($"重新获取WxConfig={JsonHelper.Serialize(config)}");
            }
            return(config);
        }
Beispiel #7
0
        //public ActionResult demo()
        //{
        //    string str = @"开始时间:2016-1-1" + "\r\n"
        //                                                 + "结束时间:2017-1-1" + "\r\n"
        //                                                + "沙尘天气等级:2" + "\r\n"
        //                                                + "PM10日均浓度最大值:2ug/m3" + "\r\n"
        //                                                 + "影响范围:济南,青岛";

        //    string oldpath = @"/Resource/Image/78041949.png";
        //    string avatarpath=@"/Resource/Image/avatar.png";
        //  //  string newpath = @"/Resource/Image/"+CommonTools.getRandomNumber(10000,99999999)+".png";
        //    string imagepath = ImageTools.composeImage(oldpath, avatarpath, @"/Resource/Image/" + CommonTools.getRandomNumber(10000, 99999999) + ".png");
        //    string textimagepath = ImageTools.composeText(oldpath, "我是贺苏\r\n邀请你来参加第二节", @"/Resource/Image/" + CommonTools.getRandomNumber(10000, 99999999) + ".png");
        //    string texttoimagepath = ImageTools.SaveTextToImage(str);
        //    ViewBag.imagepath = imagepath;
        //    ViewBag.textimagepath = textimagepath;
        //    ViewBag.texttoimagepath = texttoimagepath;
        //    return View();
        //}
        public ActionResult Index()
        {
            string       access_token = AccessTokenService.GetAccessToken();
            WechatConfig wechatconfig = AccessTokenService.GetWechatConfig();
            string       xml          = XmlSerializerHelper.ToXml(wechatconfig);


            ViewBag.Message  = access_token;
            ViewBag.Message2 = xml;

            return(View());
        }
Beispiel #8
0
        //public ActionResult About()
        //{
        //    WechatTemplateMessage msgData = new WechatTemplateMessage
        //    {
        //        touser = "******",
        //        template_id = "KqDQm6LejvmNDrTWIQuRYoflIpi7JKgvUNsQfqf8i70",
        //        url = "http://www.baidu.com",
        //        data = new
        //        {

        //            welcome = new
        //            {
        //                value = "训练提醒通知",
        //                color = "#173177"
        //            },
        //            first = new
        //            {
        //                value = "2015年6月7日",
        //                color = "#173177"
        //            },
        //            second = new
        //            {
        //                value = "踢皮球",
        //                color = "#173177"
        //            },
        //        }
        //    };



        //    string access_token = AccessTokenService.GetAccessToken();
        //    string operate="SendTemplateMessage";
        //    string postdata = JsonConvert.SerializeObject(msgData);

        //    string result=WechatService.wechatApi(operate,access_token,postdata);

        //    ViewBag.Message = JsonConvert.SerializeObject(msgData);
        //    ViewBag.result = result;
        //    return View();
        //}

        //public ActionResult SendMessage()
        //{
        //    WechatTemplateMessage msgData = new WechatTemplateMessage
        //    {
        //        touser = "******",
        //        template_id = "S0jkUpR2R7C6PIpnJHRD1GxIad27dln4vEOtD7uRl4A",
        //        url = "http://www.baidu.com",
        //        data = new
        //        {

        //            first = new
        //            {
        //                value = "宝贝,你好,训练时间到了",
        //                color = "#173177"
        //            },
        //            keyword1 = new
        //            {
        //                value = "踢皮球运动",
        //                color = "#173177"
        //            },
        //            keyword2 = new
        //            {
        //                value = "30分钟",
        //                color = "#173177"
        //            },
        //            remark = new
        //            {
        //                value = "只有坚持不懈的努力,才能有进步,加油!",
        //                color = "#173177"
        //            },
        //        }
        //    };



        //    string access_token = AccessTokenService.GetAccessToken();
        //    string postdata = JsonConvert.SerializeObject(msgData);
        //    string result = WechatMessageServices.SendTempletMessge(access_token, postdata);


        //    ViewBag.Message = JsonConvert.SerializeObject(msgData);
        //    ViewBag.result = result;
        //    return View();
        //}

        //public ActionResult Contact()
        //{
        //    UserListItem[] u = new UserListItem[2];
        //    u[0] = new UserListItem { openid = "oChqYt13RL8dBi0zKHo0kao-aSHo", lang = "zh_CN" };
        //    u[1] = new UserListItem { openid = "oChqYt1b0t1U2_b_U9ag1JQyrebM", lang = "zh_CN" };

        //    UserList ulist = new UserList
        //    {
        //        user_list = u
        //    };



        //    string postdata = JsonConvert.SerializeObject(ulist);
        //    string access_token = AccessTokenService.GetAccessToken();
        //    string operate = "GetUserListInfo";

        //    string result = WechatService.wechatApi(operate, access_token, postdata);

        //    ViewBag.Message = postdata;
        //    ViewBag.result = result;

        //    return View();
        //}

        //public ActionResult Jstest()
        //{
        //    string userAgent=Request.UserAgent;
        //    string access_token = AccessTokenService.GetAccessToken();
        //    string url=string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi",access_token);
        //    //  result = HttpWebResponseUtility.CreateGetHttpResponse(url,null,userAgent,null);


        //    HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(url, null, userAgent, null);

        //    Stream stream = response.GetResponseStream();
        //    StreamReader sr = new StreamReader(stream);
        //    string result = sr.ReadToEnd();
        //    WechatJsTicket ticket = JsonConvert.DeserializeObject<WechatJsTicket>(result);

        //    string jsapi_ticket = ticket.ticket;
        //    string url2 = Request.Url.ToString();

        //    string string1 = "jsapi_ticket=" + jsapi_ticket +
        //          "&noncestr=" + "zhaozheng" +
        //          "&timestamp=" + "1414587457" +
        //          "&url=" + url2;
        //    string x = SkyEncrypt.SHA1(string1);
        //    ViewBag.signature = x;
        //    return View();

        //}

        //public ActionResult js()
        //{
        //    string userAgent = Request.UserAgent;
        //    string access_token = AccessTokenService.GetAccessToken();
        //    string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);
        //    //  result = HttpWebResponseUtility.CreateGetHttpResponse(url,null,userAgent,null);


        //    HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(url, null, userAgent, null);

        //    Stream stream = response.GetResponseStream();
        //    StreamReader sr = new StreamReader(stream);
        //    string result = sr.ReadToEnd();
        //    WechatJsTicket ticket = JsonConvert.DeserializeObject<WechatJsTicket>(result);

        //    string jsapi_ticket = ticket.ticket;
        //    string url2 = Request.Url.ToString();

        //    string string1 = "jsapi_ticket=" + jsapi_ticket +
        //          "&noncestr=" + "zhaozhengo" +
        //          "&timestamp=" + "1414587487" +
        //          "&url=" + url2;
        //    string x = SkyEncrypt.SHA1(string1);
        //    ViewBag.signature = x;
        //    return View();

        //}

        //public ActionResult wechatjs()
        //{

        //    string access_token = AccessTokenService.GetAccessToken();
        //    string userAgent = Request.UserAgent;
        //    string  jsapi_ticket = WechatJsServices.GetJsapi_ticket(access_token, userAgent);

        //    string timestamp = TimeHelp.GetTimeStamp(DateTime.Now, 10);
        //    string nonceStr = "zhaozheng";
        //    string currentUrl = Request.Url.ToString();
        //    string signature = WechatJsServices.GetSignature(jsapi_ticket, nonceStr, timestamp, currentUrl);

        //    WechatConfig wechatconfig = AccessTokenService.GetWechatConfig();


        //    ViewBag.timestamp = int.Parse(timestamp);
        //    ViewBag.nonceStr = nonceStr;
        //    ViewBag.appid = wechatconfig.Appid;
        //    ViewBag.signature = signature;
        //    ViewBag.jsapi_ticket = jsapi_ticket;
        //    ViewBag.currentUrl = currentUrl;



        //    return View();
        //}

        public ActionResult GetUserInfo()
        {
            WechatConfig wechatconfig = AccessTokenService.GetWechatConfig();

            string REDIRECT_URI = System.Web.HttpUtility.UrlEncode("http://wx.zzd123.com/Home/GetUserId");

            string SCOPE = "snsapi_userinfo";

            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wechatconfig.Appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=" + SCOPE + "&state=STATE#wechat_redirect";

            return(Redirect(url));
        }
        public static WechatConfig GetWechatConfig()
        {
            Configuration      config     = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appsection = config.GetSection("appSettings") as AppSettingsSection;


            WechatConfig wechatConfig = new WechatConfig();

            wechatConfig.Appid                  = appsection.Settings["WechatAppID"].Value;
            wechatConfig.AppSecret              = appsection.Settings["WechatAppSecret"].Value;
            wechatConfig.AccessToken            = appsection.Settings["WechatAccessToken"].Value;
            wechatConfig.AccessTokenExpiredTime = appsection.Settings["WechatAccessTokenExpiredTime"].Value;

            return(wechatConfig);
        }
        public static string GetAccessToken()
        {
            string access_token = "";

            WechatConfig wechatConfig = AccessTokenService.GetWechatConfig();

            if (DateTime.Now < DateTime.Parse(wechatConfig.AccessTokenExpiredTime))
            {
                access_token = wechatConfig.AccessToken;
            }
            else
            {
                access_token = AccessTokenService.RefrenshToken(wechatConfig.Appid, wechatConfig.AppSecret);
            }
            return(access_token);
        }
Beispiel #11
0
        public ActionResult WechatLogin(string redirectUrl)
        {
            // string sourceUrl = Request.UrlReferrer.ToString();

            string userAgent = Request.UserAgent;

            WechatConfig wechatconfig = AccessTokenService.GetWechatConfig();

            // string REDIRECT_URI = System.Web.HttpUtility.UrlEncode("http://peiban.zzd123.com/Ucenter/Register");
            string REDIRECT_URI = System.Web.HttpUtility.UrlEncode(redirectUrl);

            string SCOPE = "snsapi_userinfo";
            //string STATE = sourceUrl;
            string STATE = "statecanshu";

            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wechatconfig.Appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=" + SCOPE + "&state=" + STATE + "#wechat_redirect";

            return(Redirect(url));
        }
        /// <summary>
        /// 获取微信配置
        /// </summary>
        /// <param name="mp_id"></param>
        /// <returns></returns>
        public ServiceResult <WxMP_AuthorizeAccessTokenOutput> GetAccessToken(WxMP_AuthorizeAccessTokenInput input)
        {
            try
            {
                input.CheckNull(nameof(WxMP_AuthorizeAccessTokenInput));

                var result = new ServiceResult <WxMP_AuthorizeAccessTokenOutput>();
                result.data = new WxMP_AuthorizeAccessTokenOutput();
                WechatConfig wechatConfig = null;
                //微信配置
                if (input.wid == 0)
                {
                    input.guid.CheckEmpty(nameof(input.guid));
                    wechatConfig = _middleDB.WechatConfig.FirstOrDefault(w => w.Guid == input.guid);
                }
                else
                {
                    wechatConfig = _middleDB.WechatConfig.FirstOrDefault(w => w.Id == input.wid);
                }
                if (wechatConfig == null)
                {
                    return(ServiceResult <WxMP_AuthorizeAccessTokenOutput> .Failed(StatusCodes.Status404NotFound, "微信配置获取失败,请联系系统客服"));
                }
                //数据库中
                if (!string.IsNullOrEmpty(wechatConfig.AccessToken) &&
                    DateTime.Now < (wechatConfig.TokenUpdateTime ?? DateTime.Now.AddMinutes(-1)))
                {
                    result.data.access_token = wechatConfig.AccessToken;
                }
                else
                {
                    //双重验证
                    if (string.IsNullOrEmpty(result.data.access_token))
                    {
                        lock (lock_token)
                        {
                            if (string.IsNullOrEmpty(result.data.access_token))
                            {
                                //从微信获取
                                var token = WxMPContext.BaseAPI.GetAccessToken(wechatConfig.AppId, wechatConfig.AppSecret);
                                if (token.errcode != 0)
                                {
                                    result.data.access_token = token.errmsg;
                                    return(result);
                                }
                                //修改
                                wechatConfig.Token           = token.access_token;
                                wechatConfig.TokenUpdateTime = DateTime.Now.AddMinutes(60);
                                _middleDB.SaveChanges();

                                result.data.access_token = token.access_token;
                            }
                        }
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                return(ServiceResult <WxMP_AuthorizeAccessTokenOutput> .Exception(ex.Message));
            }
        }
Beispiel #13
0
        public async Task  CreateOrUpdateWechatConfig(List <WechatConfigDto> input)
        {
            //_wechat.Delete(r => 1 == 1);
            foreach (var item in input)
            {
                if (item.Id > 0)
                {
                    var re = _wechat.GetAll().AsNoTracking().Where(r => r.Id == item.Id).FirstOrDefault();
                    re.Name      = item.Name;
                    re.PageName  = item.PageName;
                    re.PageRuslt = item.PageRuslt;
                    re.Value     = item.Value;
                    re.AgentId   = item.AgentId;
                    re.Secret    = item.Secret;
                    await _wechat.UpdateAsync(re);
                }
                else
                {
                    WechatConfig wechat = new WechatConfig
                    {
                        Name      = item.Name,
                        PageName  = item.PageName,
                        PageRuslt = item.PageRuslt,
                        Value     = item.Value,
                        AgentId   = item.AgentId,
                        Secret    = item.Secret
                    };
                    await _wechat.InsertAsync(wechat);
                }
            }
            //foreach (var item in input)
            //{
            //    if (item.Id==0)
            //    {
            //        WechatConfig wechat = new WechatConfig();
            //        ObjectMapper.Map(wechat, item);
            //        await _wechat.InsertAsync(wechat);
            //    }
            //    else
            //    {
            //        WechatConfig wechat = new WechatConfig();
            //        ObjectMapper.Map(wechat, item);
            //        await _wechat.UpdateAsync(wechat);
            //    }
            //}

            //List<WechatConfig> config = new List<WechatConfig>();
            //if (input.Count>0)
            //{
            //    ObjectMapper.Map(input, config);
            //    foreach (var item in config)
            //    {
            //        await _wechat.InsertOrUpdateAsync(item);
            //    }
            //}
            //if (input.Id.HasValue)
            //{
            //    return await UpdateWechatConfig(input);
            //}
            //else
            //{
            //    return await CreateWechatConfig(input);
            //}
        }