コード例 #1
0
ファイル: WeiXinController.cs プロジェクト: fion45/FCStore
        public ActionResult API()
        {
            logger.Log(LogLevel.Trace, "F0");
            logger.Log(LogLevel.Trace, APPID);
            try
            {
                logger.Log(LogLevel.Trace, KeepAccessTokenHelper.APPID);
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Trace, ex.Message);
            }

            KeepAccessTokenHelper.APPID = APPID;
            logger.Log(LogLevel.Trace, "1");
            KeepAccessTokenHelper.APPSECRET = APPSECRET;
            logger.Log(LogLevel.Trace, Request.Url);
            logger.Log(LogLevel.Trace, "2");
            ACCESSTOKEN = KeepAccessTokenHelper.Instance.AccessToken;
            logger.Log(LogLevel.Trace, "3");
            WXHelper helper = new WXHelper(TOKEN, APPID, APPSECRET, ACCESSTOKEN);

            logger.Log(LogLevel.Trace, "4");
            string responseContent = helper.DealWith(Request, BuildMenu());

            Response.ContentEncoding = Encoding.UTF8;
            Response.Write(responseContent);
            Response.Flush();
            Response.End();
            return(new EmptyResult());
        }
コード例 #2
0
        /// <summary>
        /// 微信公众号引导页
        /// </summary>
        /// <param name="url">微信前端传递的跳转url</param>
        /// <returns>成功时,重定向至获取用户信息</returns>
        public ActionResult Index(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                url = WXHelper.DecodeBase64(url);
                string state = EncryptHelper.MD5Encrypt(url);
                //判断url根据MD5生成的密文在缓存中是否存在
                object objUrl = CacheHelper.GetCache(state);
                if (objUrl == null)
                {
                    CacheHelper.AddCache(state, url, 5);//不存在则将url和对应的密文存储在缓存中,存储时长为5分钟
                }
                else
                {
                    CacheHelper.SetCache(state, url, 5);//存在则将url和对应的密文在缓存中更新,更新存储时长为5分钟
                }
                return(Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect", appId, ConfigurationManager.AppSettings["zp_apppath"] + "/Recruitment/Auth/GetUserInfo", state)));
            }
            else
            {
                ViewData["errmsg"] = "重定向url不能为空!";
            }

            return(View());
        }
コード例 #3
0
        private void SendGroupMessageForm_Load(object sender, EventArgs e)
        {
            this.startdate.CustomFormat = "yyyy/MM/dd";
            this.startdate.Format       = DateTimePickerFormat.Custom;
            _startDate = DateTime.Now;

            this.starttime.CustomFormat = "HH:mm";
            this.starttime.Format       = DateTimePickerFormat.Custom;
            this.starttime.ShowUpDown   = true;
            _startTime = DateTime.Now;

            _currentSendType = ((EnumSendType)Convert.ToInt32(this.Tag));

            this.Send.Text = _currentSendType == EnumSendType.AutoSend ? "提交" : "发送";

            var isShow = _currentSendType == EnumSendType.AutoSend;

            if (!isShow)
            {
                this.SetStartDate.Hide();
            }

            wxHelper = SingleHepler <WXHelper> .Instance;

            CheckSomeEquipmentToDO(this.flowLayoutPanelWithEquipment);

            InitGroup(this.flowLayoutPanelWithGroup);
        }
コード例 #4
0
        public string GetUnifiedOrderResult(int accountid, int goodsid)
        {
            //统一下单
            EAccount account = DBBase.Get <EAccount>(accountid);
            EStore   goods   = DBBase.Get <EStore>(goodsid);

            if (goods.Type != "Damion" && goods.Type != "Vip")
            {
                return("-1");                       //不用用人民币购买
            }
            string    openid   = account.OpenID;    // "oWsnW06q3aPEkggMC9ZDB2ATohsA";
            int       totalfee = goods.Price * 100; // 100;
            WxPayData data     = new WxPayData();

            data.SetValue("body", "卡五梅-游戏充值");
            data.SetValue("attach", "kawumei");
            data.SetValue("out_trade_no", WXHelper.GenerateOutTradeNo());
            data.SetValue("total_fee", totalfee);//订单总金额,单位为分
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", goods.Name);
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", openid);
            WxPayData result = WXHelper.UnifiedOrder(data);

            Console.Write(result.ToXml());
            return(result.ToXml());
        }
コード例 #5
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            WeiXinCore.WeiXin wx = WXHelper.CreateWeiXinInstanceBySiteCode("VYIGO");
            //List<WeiXinCore.Models.TemplateMessageParam> list=new List<WeiXinCore.Models.TemplateMessageParam>();
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("first", "您好"));
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("orderMoneySum", "12.5"));
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("orderProductName", "测试商品"));
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("Remark", "我是备注"));
            //WeiXinCore.Models.SendTemplateMessageReturnObj obj = wx.SendTemplateMessage(TextBox1.Text,
            //    "IR3TlAC2Y3lW0jaksuPRwHrVHe5nmbWRcD6ZeUPZPlA",
            //    "http://www.baidu.com",list.ToArray());
            List <WeiXinCore.Models.TemplateMessageParam> list = new List <WeiXinCore.Models.TemplateMessageParam>();

            list.Add(new WeiXinCore.Models.TemplateMessageParam("first", "您好"));
            list.Add(new WeiXinCore.Models.TemplateMessageParam("delivername", "快递公司测试"));
            list.Add(new WeiXinCore.Models.TemplateMessageParam("ordername", "快递单号测试"));
            list.Add(new WeiXinCore.Models.TemplateMessageParam("Remark", "我是备注"));
            WeiXinCore.Models.SendTemplateMessageReturnObj obj = wx.SendTemplateMessage(TextBox1.Text,
                                                                                        "k4eMeEtKReeDvDRFAf8-Li9FuuHkaFPP1xQI6t3Jomo", "http://www.baidu.com", list.ToArray());

            //List<WeiXinCore.Models.TemplateMessageParam> list = new List<WeiXinCore.Models.TemplateMessageParam>();
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("first", "您好"));
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("OrderSn", "快递公司测试"));
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("OrderStatus", "快递单号测试"));
            //list.Add(new WeiXinCore.Models.TemplateMessageParam("Remark", "其他订单信息,物流信息: 圆通速递(上海),快递单号: 8031971890"));
            //WeiXinCore.Models.SendTemplateMessageReturnObj obj = wx.SendTemplateMessage(TextBox1.Text,
            //    "wmrxCKRq1hG3cHR0BXsuUnNq1chcbVosqYLqlsBBRCc",
            //    "http://www.baidu.com", list.ToArray());
            int i = 4;
        }
コード例 #6
0
        private void TimerSendFriendCircle_Load(object sender, EventArgs e)
        {
            this.startdate.CustomFormat = "yyyy/MM/dd";
            this.startdate.Format       = DateTimePickerFormat.Custom;
            _startDate = DateTime.Now;

            this.starttime.CustomFormat = "HH:mm";
            this.starttime.Format       = DateTimePickerFormat.Custom;
            this.starttime.ShowUpDown   = true;
            _startTime = DateTime.Now;

            _currentSendType = ((EnumSendType)Convert.ToInt32(this.Tag));

            _currentSelectContentType = EnumPublishContentType.PictureAndWord;

            this.Send.Text = _currentSendType == EnumSendType.AutoSend ? "提交" : "发送";

            var isShow = _currentSendType == EnumSendType.AutoSend;

            if (!isShow)
            {
                this.SetStartDate.Hide();
            }

            AddBtnWithAddContent();

            wxHelper = SingleHepler <WXHelper> .Instance;

            CheckSomeEquipmentToDO(this.flowLayoutPanelWithEquipment);

            InitGroup(this.flowLayoutPanelWithGroup);
        }
コード例 #7
0
        public virtual Task <IHttpActionResult> WX_Code_Open_Id([FromBody] WXCode code)
        {
            Console.WriteLine("code:{0}", code.code);
            var token = WXHelper.Get_token(code.code);

            Console.WriteLine("token:{0}", token);
            return(Task.FromResult <IHttpActionResult>(Ok(ApiResult <string> .Success(token))));
        }
コード例 #8
0
        /// <summary>
        /// 订单收货
        /// </summary>
        void ReceiveOrder()
        {
            string oid = string.Empty;

            if (Request["oid"] != null && Request["oid"] != "")
            {
                oid = Common.Common.NoHtml(Request["oid"]);
            }
            if (oid != null && oid != "")
            {
                MSProductOrderDAL OrderDal = new MSProductOrderDAL();
                if (OrderDal.UpdateOrderState("isReceive", oid))
                {
                    string buyName = string.Empty;
                    try
                    {
                        buyName = OrderDal.GetOrderValueByID("BuyName", oid).ToString();
                        if (strOpenID == null || strOpenID == "")
                        {
                            string         customerid  = OrderDal.GetOrderDetailValueByOID("CustomerID", oid).ToString();
                            MSCustomersDAL CustomerDal = new MSCustomersDAL();
                            try
                            {
                                strOpenID = CustomerDal.GetCustomerValueByID("OpenID", customerid).ToString();
                            }
                            catch (Exception)
                            {
                            }
                        }
                        WeiXinCore.WeiXin           wx        = WXHelper.CreateWeiXinInstanceBySiteCode("VYIGO");
                        List <TemplateMessageParam> paramList = new List <TemplateMessageParam>();
                        paramList.Add(new TemplateMessageParam("first", "尊敬的" + buyName));
                        paramList.Add(new TemplateMessageParam("OrderSn", oid));
                        paramList.Add(new TemplateMessageParam("OrderStatus", "已收货"));
                        paramList.Add(new TemplateMessageParam("Remark",
                                                               "请关注公众号【vgo2013】进入“服务中心进行查询”查看完整信息"));
                        wx.SendTemplateMessage(strOpenID, "wmrxCKRq1hG3cHR0BXsuUnNq1chcbVosqYLqlsBBRCc",
                                               "http://www.vgo2013.com/PalmShop/ShopCode/CustomerOrder.aspx?receive=1",
                                               paramList.ToArray(), "");
                        MSOrderLogDAL.AddMSOrderLog("提示客户订单【" + oid +
                                                    "】已确认收货,发送模板消息到客户OpenID【" + strOpenID + "】");
                    }
                    catch (Exception)
                    {
                    }
                    Response.Write("{\"success\":true}");
                }
                else
                {
                    Response.Write("{\"error\":true,\"msg\":\"操作失败,请稍后再操作\"}");
                }
            }
            else
            {
                Response.Write("{\"error\":true,\"msg\":\"操作失败,请稍后再操作\"}");
            }
            Response.End();
        }
コード例 #9
0
        public JsonResult <object> GetWxImage(GetWxImageRequest reques)
        {
            //var temp = WXHelper.GetWxaCode();
            string path = WXHelper.GetWxImage(reques.Pages, "1", reques.FileName);

            if (string.IsNullOrEmpty(path))
            {
                return(JsonError("生成小程序码失败"));
            }
            return(JsonNet(path));
        }
コード例 #10
0
 public string ReturnEchostr([FromQuery] string signature, [FromQuery] string nonce, [FromQuery] string timestamp, [FromQuery] string echostr)
 {
     if (WXHelper.IsMessageFromWX(signature, nonce, timestamp, WxToken))
     {
         return(echostr);
     }
     else
     {
         return("Failed to authenticate the request");
     }
 }
コード例 #11
0
ファイル: WeChatController.cs プロジェクト: haiyoufan/Apps
 public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
 {
     if (string.IsNullOrEmpty(WeChatToken))
     {
         return(Content("请先设置Token!"));
     }
     if (WXHelper.CheckSignature(WeChatToken, signature, timestamp, nonce))
     {
         return(Content(echostr));
     }
     else
     {
         return(Content("Failed:" + signature + ", " + WXHelper.GetSignature(timestamp, nonce, WeChatToken) + "。如果你在浏览器中看到这个,说明此URL可以植入微信后台。"));
     }
 }
コード例 #12
0
        public JsonResult <object> WXQrcode(WXQrcodeRequest request)
        {
            if (request == null)
            {
                return(JsonError("请求参数错误"));
            }
            if (!string.IsNullOrEmpty(request.ShareCode))
            {
                if (!_weCharUserInfoService.ExistShareCode(request.ShareCode))
                {
                    return(JsonError("该分享码不存在"));
                }
                request.Pages += "?sharecode=" + request.ShareCode;
            }
            var fileName    = request.Pages.Replace("/", "_").Replace("?", "-") + request.Width + ".jpg";
            var dirpath     = System.Web.HttpContext.Current.Server.MapPath("~/Upload/WecharImg/");
            var savePath    = dirpath + fileName;
            var servicePath = "/Upload/WecharImg/" + fileName;

            if (File.Exists(savePath))
            {
                return(JsonNet(servicePath));
            }

            lock (WXQrCodeSequenceLock)
            {
                using (var ms = new MemoryStream())
                {
                    var result = WXHelper.GetWxaCode(ms, request.Pages, request.Width);
                    if (result.errcode == Senparc.Weixin.ReturnCode.请求成功)
                    {
                        Image image = Image.FromStream(ms);
                        if (!Directory.Exists(dirpath))
                        {
                            Directory.CreateDirectory(dirpath);
                        }
                        image.Save(savePath);
                        image.Dispose();
                    }
                    else
                    {
                        return(JsonError(result.errmsg));
                    }
                }
            }

            return(JsonNet(servicePath));
        }
コード例 #13
0
        //2015.5.13 微信分享config
        // GET: /WxConfig/
        public ActionResult AjaxGetWxConfig(string url)
        {
            var    result    = new ServiceResult("获取微信config信息");
            string noncestr  = Guid.NewGuid().ToString().ToLower();
            string timestamp = DateTime.Now.Ticks.ToString().LenthShow(10, "");
            string signdata  = WXHelper.GetSignature(noncestr, timestamp, url);
            var    jsConfig  = new WxJsConfig()
            {
                Noncestr  = noncestr,
                Timestamp = timestamp,
                Signdata  = signdata.ToLower(),
                Url       = url.ToLower()
            };

            result.SetData("appId", "WX_ApplyId".ValueOfAppSettings());
            result.SetData("jsConfig", jsConfig);
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
コード例 #14
0
        public JsonResult <object> AddComment(AddCommentRequest request)
        {
            if (request == null)
            {
                return(JsonError("请求参数不能为空"));
            }
            if (string.IsNullOrEmpty(request.CommentContent))
            {
                throw new Exception("评论内容不能为空");
            }
            if (!_articleService.ExistData(request.ArticleID))
            {
                throw new Exception("文章不存在");
            }

            var baseInfo = GetBaseInfo();

            if (!_weCharUserInfoService.Exist(baseInfo.UnionID))
            {
                throw new Exception("微信账号不存在");
            }

            var msgObj = WXHelper.MsgCheck(request.CommentContent);

            if (msgObj.errcode == Senparc.Weixin.ReturnCode.请求成功)
            {
                CommentDomain domain = request.ToDomainModel();
                domain.UnionID    = baseInfo.UnionID;
                domain.ID         = Guid.NewGuid();
                domain.CreateTime = DateTime.Now;
                _commentService.NewCreate(domain);


                return(JsonNet("发表成功"));
            }
            if (msgObj.errcode == (Senparc.Weixin.ReturnCode) 40001)
            {
                WXHelper.RemoveAccessToken();
                //access_token失效 请重新获取
                return(JsonNet("发表错误,请重新发送"));
            }

            return(JsonError(msgObj.errcode.ToString()));
        }
コード例 #15
0
        /// <summary>
        /// 微信公众号引导页 使用微信SNSToken获取微信用户信息,包括用户UnionID信息
        /// </summary>
        /// <returns>成功时,返回带有用户信息的URL并重定向</returns>
        public ActionResult GetUserInfo2()
        {
            string code  = Request.QueryString["code"];
            string state = Request.QueryString["state"];

            try
            {
                if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state))
                {
                    WXHelper WXHelper       = new WXHelper();
                    string   strGetSnsToken = WXHelper.Request(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, secret, code), "", "GET");
                    JObject  jo1            = JsonConvert.DeserializeObject <JObject>(strGetSnsToken);

                    string        strResult = WXHelper.Request(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN ", jo1["access_token"].ToString(), jo1["openid"].ToString()), "", "GET");
                    OAuthUserInfo userInfo  = JsonConvert.DeserializeObject <OAuthUserInfo>(strResult);
                    if (userInfo != null)
                    {
                        object objUrl = CacheHelper.GetCache(state);
                        if (objUrl != null)
                        {
                            UriBuilder URL       = new UriBuilder(objUrl.ToString());
                            string     directUrl = URL.ToString();
                            directUrl += string.Format("?openid={0}&nickname={1}&sex={2}&province={3}&city={4}&country={5}&headimgurl={6}&unionid={7}",
                                                       userInfo.openid, userInfo.nickname, userInfo.sex, userInfo.province, userInfo.city, userInfo.country, userInfo.headimgurl, userInfo.unionid);

                            Response.Redirect(directUrl);
                        }
                    }
                }
                else
                {
                    ViewData["errmsg"] = "用户code获取失败!";
                }
            }
            catch (Exception ex)
            {
                ViewData["errmsg"] = ex.Message;
            }

            return(View());
        }
コード例 #16
0
        public JsonResult <object> Temp(TempRequest reques)
        {
            var fileName    = "pages/index/index".Replace("/", "_") + 4301 + ".jpg";
            var dirpath     = System.Web.HttpContext.Current.Server.MapPath("~/Upload/WecharImg/");
            var savePath    = dirpath + fileName;
            var servicePath = "/Upload/WecharImg/" + fileName;

            lock (WXQrCodeSequenceLock)
            {
                using (var ms = new MemoryStream())
                {
                    var result = WXHelper.Temp(ms, "/pages/artcle/index?temp=1", 430, reques.R, reques.G, reques.B);
                    if (result.errcode == Senparc.Weixin.ReturnCode.请求成功)
                    {
                        Image image;
                        try
                        {
                            image = Image.FromStream(ms);
                        }
                        catch (System.ArgumentException)
                        {
                            WXHelper.RemoveAccessToken();
                            throw new Exception("生成图片失败");
                        }
                        if (!Directory.Exists(dirpath))
                        {
                            Directory.CreateDirectory(dirpath);
                        }
                        image.Save(savePath);
                        image.Dispose();
                    }
                    else
                    {
                        return(JsonError(result.errmsg));
                    }
                }
            }
            return(JsonNet(servicePath));
        }
コード例 #17
0
 private string GetJSApiTicket(string accessToken)
 {
     wxhelper = new WXHelper();
     return(wxhelper.GetTicketByToken(accessToken, "jsapi", false));
 }
コード例 #18
0
 private string GetJSApiTicket(string appid, string secret)
 {
     wxhelper = new WXHelper();
     return(wxhelper.GetTicket(appid, secret, "jsapi"));
 }
コード例 #19
0
 private string GetCardJSApiTicket(string accessToken)
 {
     wxhelper = new WXHelper();
     return(wxhelper.GetTicketByToken(accessToken, "wx_card", false));
 }
コード例 #20
0
 private string GetAccessToken(string appid, string secret)
 {
     wxhelper = new WXHelper();
     return(wxhelper.GetAccessToken(appid, secret, false));
 }
コード例 #21
0
        public override void OnPaySucceed(WXJSAPIPayNotifyInfo info)
        {
            ExceptionLog log = new ExceptionLog();

            log.Message = string.Format("Openid:{0},订单号:{1},附加消息:{2}",
                                        info.OpenId, info.OutTradeNo, info.Attach);
            ExceptionLogDAL.InsertExceptionLog(log);

            MSProductOrderDAL ptitleDal = new MSProductOrderDAL();
            int paystate = 0;

            try
            {
                paystate = Convert.ToInt32(ptitleDal.GetOrderValueByID("PayState", info.OutTradeNo).ToString());
            }
            catch (Exception)
            {
            }
            if (paystate == 0)
            {
                bool updatepayway   = ptitleDal.UpdateOrderPayWay(info.OutTradeNo, "wxpay");
                bool updateOrderNum = MSProductOrderDAL.UpdateOrderPayState(info.OutTradeNo, "1");
                MSOrderLogDAL.AddMSOrderLog("订单【" + info.OutTradeNo + "】支付成功,支付方式:微支付");
                if (updatepayway == true && updateOrderNum == true)
                {
                    string countcost = ptitleDal.GetOrderDetailValueByOID("UnitCost", info.OutTradeNo).ToString();
                    string strSiteCode = "VYIGO";
                    string pid = string.Empty; string pname = string.Empty;

                    #region -获取产品信息
                    try
                    {
                        countcost = ptitleDal.GetOrderDetailValueByOID("UnitCost", info.OutTradeNo).ToString();
                    }
                    catch (Exception)
                    {
                    }
                    try
                    {
                        pid = ptitleDal.GetOrderDetailValueByOID("PID", info.OutTradeNo).ToString();
                    }
                    catch (Exception)
                    {
                    }
                    if (pid != null && pid != "")
                    {
                        MSProductDAL ProductDal = new MSProductDAL();
                        pname = ProductDal.GetMSProductVaueByID("Ptitle", pid).ToString();
                    }
                    #endregion

                    WeiXinCore.WeiXin           wx        = WXHelper.CreateWeiXinInstanceBySiteCode(strSiteCode);
                    List <TemplateMessageParam> paramList = new List <TemplateMessageParam>();
                    paramList.Add(new TemplateMessageParam("first", "我们已收到您的货款,订单号为:" +
                                                           info.OutTradeNo + ";我们将尽快为您打包商品,请耐心等待: )"));
                    paramList.Add(new TemplateMessageParam("orderMoneySum", countcost + " 元"));
                    paramList.Add(new TemplateMessageParam("orderProductName", pname));
                    paramList.Add(new TemplateMessageParam("Remark", "如有问题请致电400-885-5790或直接在微信留言,小V将第一时间为您服务!"));
                    wx.SendTemplateMessage(info.OpenId, "IR3TlAC2Y3lW0jaksuPRwHrVHe5nmbWRcD6ZeUPZPlA",
                                           "http://www.vgo2013.com/PalmShop/ShopCode/OrderDetail.aspx?oid=" + info.OutTradeNo,
                                           paramList.ToArray(), "");
                    MSOrderLogDAL.AddMSOrderLog("发送模板消息到客户OpenID为【" + info.OpenId + "】大致为:我们已收到您的货款" + countcost + "元,产品名称【" + pname + "】我们将尽快为您打包商品,请耐心等待: )");
                    //JQDialog.SendWeiXinMsg(strSiteCode, info.OpenId,
                    //                       "您的订单号【" + info.OutTradeNo + "】已于" +
                    //                       DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") +
                    //                       "付款成功,支付金额:" + countcost +
                    //                       "元;在等待卖家发货,详情请进入我的订单查询!");
                }
            }
        }
コード例 #22
0
        public async Task <string> WxPost([FromQuery] string signature, [FromQuery] string nonce, [FromQuery] string timestamp)
        {
            // WX message validataion
            if (WXHelper.IsMessageFromWX(signature, nonce, timestamp, WxToken))
            {
                using (var reader = new StreamReader(Request.Body))
                {
                    var body = reader.ReadToEnd();

                    if (String.IsNullOrEmpty(body))
                    {
                        return("Failed to get message");
                    }

                    // Parse WX Message
                    WXMsg  msg      = WXHelper.ParseWXMsgFromBodyString(body);
                    string wxUserId = msg.FromUserName.Trim();

                    string responseXML = "";

                    // Only care about Text message
                    if (msg.MsgType == WXMsgType.Text)
                    {
                        if (!conMap.activeConversations.ContainsKey(wxUserId))
                        {
                            // Create a DirectlineCline and initialize the waltermark
                            var createdCon = await botClient.Conversations.StartConversationAsync();

                            conMap.activeConversations.Add(wxUserId, new ConversationInfo(createdCon, ""));
                        }

                        // Create a Bot Message Activity
                        Activity userMessage = new Activity
                        {
                            From = new ChannelAccount(wxUserId),
                            Text = msg.Content,
                            Type = ActivityTypes.Message
                        };

                        // Post the message to Bot
                        var thisConverstaionID = conMap.activeConversations[wxUserId].Conversation.ConversationId;
                        await botClient.Conversations.PostActivityAsync(thisConverstaionID, userMessage);

                        // Get Activity Set from Bot
                        var activitySet = await botClient.Conversations.GetActivitiesAsync(thisConverstaionID, conMap.activeConversations[wxUserId].Waltermark);

                        conMap.activeConversations[wxUserId].Waltermark = activitySet.Watermark;

                        var activities = from x in activitySet.Activities
                                         where x.From.Id == botId
                                         select x;

                        var returnString = "";
                        foreach (Activity activity in activities)
                        {
                            returnString += activity.Text + "||";
                        }

                        responseXML = WXHelper.ConstructWXTextMessage(msg, returnString);
                    }
                    return(responseXML);
                }
            }
            else
            {
                return("");
            }
        }
コード例 #23
0
        /// <summary>
        /// 小程序微店首页模板
        /// </summary>
        /// <returns></returns>
        public ActionResult SmallProgVHomepage()
        {
            //Models.VshopHomeSiteViewModel model = new Models.VshopHomeSiteViewModel();
            //未开通微店就进不去首页设置
            //VShopInfo vshop =
            //model.VShop = vshop;
            //model.ShopId = CurrentSellerManager.ShopId;
            //model.SlideImage = _iSlideAdsService.GetSlidAds(CurrentSellerManager.ShopId, SlideAdInfo.SlideAdType.VShopHome).ToList();
            //model.Banner = _iNavigationService.GetSellerNavigations(CurrentSellerManager.ShopId, PlatformType.WeiXin).ToList();
            var vshop = _iVShopService.GetVShopByShopId(CurrentSellerManager.ShopId);

            if (vshop == null)
            {
                //throw new Mall.Core.MallException("未开通微店");
            }
            ViewBag.IsOpenVShop = vshop != null;
            ViewBag.VShopId     = vshop == null ? 0 : vshop.Id;
            ViewBag.ShopId      = CurrentSellerManager.ShopId;
            string crrentTemplateName = "t1";
            //var curr = _iTemplateSettingsService.GetCurrentTemplate(CurrentSellerManager.ShopId);
            //if (null != curr)
            //{
            //    crrentTemplateName = curr.CurrentTemplateName;
            //}

            var helper         = new GalleryHelper();
            var themes         = helper.LoadThemes(CurrentSellerManager.ShopId);
            var CurTemplateObj = themes.FirstOrDefault(t => t.ThemeName.Equals(crrentTemplateName.ToLower()));

            if (CurTemplateObj == null)
            {
                CurTemplateObj = themes.FirstOrDefault(t => t.ThemeName.Equals("t1"));
            }
            if (CurTemplateObj == null)
            {
                throw new MallException("错误的模板:" + crrentTemplateName);
            }
            ViewBag.CurrentTemplate = CurTemplateObj;
            ViewBag.CurUrl          = Request.Scheme + "://" + Request.Host.ToString();
            var siteSetting = SiteSettingApplication.SiteSettings;

            if (!string.IsNullOrWhiteSpace(siteSetting.WeixinAppletId) && !string.IsNullOrWhiteSpace(siteSetting.WeixinAppletSecret))
            {
                ViewBag.IsHaveApplet = true;
            }

            //获取指定页面小程序码
            try
            {
                var            wxhelper    = new WXHelper();
                var            accessToken = wxhelper.GetAccessToken(SiteSettings.WeixinAppletId, SiteSettings.WeixinAppletSecret);
                var            data        = "{\"path\":\"pages/vShopHome/vShopHome?id=" + vshop.Id + "\",\"width\":600}";
                HttpWebRequest request     = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken); //创建url
                request.Method      = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                byte[] load = Encoding.UTF8.GetBytes(data);
                request.ContentLength = load.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(load, 0, load.Length);
                HttpWebResponse response        = (HttpWebResponse)request.GetResponse();
                Stream          s               = response.GetResponseStream();
                byte[]          mg              = StreamToBytes(s);
                MemoryStream    ms              = new MemoryStream(mg);
                string          qrCodeImagePath = string.Empty;
                qrCodeImagePath = "data:image/gif;base64," + Convert.ToBase64String(ms.ToArray());
                ms.Dispose();
                ViewBag.QrCodeImagePath = qrCodeImagePath;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

            return(View(themes.Where(t => t.ThemeName != crrentTemplateName.ToLower()).ToList()));
        }
コード例 #24
0
        /// <summary>
        /// 提交订单
        /// </summary>
        void submitOrder()
        {
            string oid = string.Empty; string cid = string.Empty; string cname = string.Empty;

            #region -获取页面请求值
            try
            {
                oid = Request.Form.Get("ordernum").ToString();
            }
            catch (Exception)
            {
                oid = "";
            }
            try
            {
                cname = Request.Form.Get("cname").ToString();
            }
            catch (Exception)
            {
                cname = "";
            }
            try
            {
                cid = Request.Form.Get("cid").ToString();
            }
            catch (Exception)
            {
                cid = "";
            }
            #endregion
            strSiteCode = "VYIGO"; string customerid = string.Empty; string openid = string.Empty;
            if (oid != null && oid != "" && cid != null && cid != "")
            {
                MSOrderLogistics    olModel  = new MSOrderLogistics();
                MSOrderLogisticsDAL olDal    = new MSOrderLogisticsDAL();
                MSProductOrderDAL   OrderDal = new MSProductOrderDAL();
                olModel.ID = cid; olModel.OID = oid; olModel.CName = cname;

                customerid = OrderDal.GetOrderValueByID("CustomerID", oid).ToString();

                if (customerid != null && customerid != "")
                {
                    MSCustomersDAL customerDal = new MSCustomersDAL();
                    openid = customerDal.GetCustomerValueByID("OpenID", customerid).ToString();
                }

                if (olDal.AddOrderLogistics(olModel) && OrderDal.UpdateOrderState("IsSend", oid))
                {
                    string buyName = string.Empty;
                    try
                    {
                        buyName = OrderDal.GetOrderValueByID("BuyName", oid).ToString();
                        WeiXinCore.WeiXin           wx        = WXHelper.CreateWeiXinInstanceBySiteCode(strSiteCode);
                        List <TemplateMessageParam> paramList = new List <TemplateMessageParam>();
                        paramList.Add(new TemplateMessageParam("first", "亲,宝贝已经启程了,好想快点来到你身边"));
                        paramList.Add(new TemplateMessageParam("delivername", cname));
                        paramList.Add(new TemplateMessageParam("ordername", cid));
                        paramList.Add(new TemplateMessageParam("remark",
                                                               "请关注公众号【vgo2013】进入“快点我”查看完整物流信息"));
                        SendTemplateMessageReturnObj temobj = wx.SendTemplateMessage(openid,
                                                                                     "k4eMeEtKReeDvDRFAf8-Li9FuuHkaFPP1xQI6t3Jomo",
                                                                                     "http://www.vgo2013.com/PalmShop/ShopCode/CopyOrder.aspx?oid=" + oid,
                                                                                     paramList.ToArray(), "");
                        MSOrderLogDAL.AddMSOrderLog("提示客户订单【" + oid + "】已经发货,发送模板消息到客户OpenID【" + openid + "】");
                        bool flag = true;
                        if (flag)
                        {
                        }
                    }
                    catch { }

                    errormsg = JQDialog.alertOKMsgBox(3, "操作成功!", "OrderDelivery.aspx", "succeed");
                }
                else
                {
                    errormsg = JQDialog.alertOKMsgBoxGoBack(3, "操作失败,请重新操作!", false);
                }
            }
            else
            {
                errormsg = JQDialog.alertOKMsgBoxGoBack(3, "操作失败,请重新操作!", false);
            }
        }
コード例 #25
0
ファイル: WXMsgRecordJob.cs プロジェクト: damoOnly/e-commerce
        public void Execute(XmlNode node)
        {
            ErrorLog.Write("start go WXMsgRecordJob");
            DateTime startTime = DateTime.Now;
            DateTime endTime   = DateTime.Now;
            int      pageSize  = 50;
            bool     update    = false;
            WXLog    log       = WXHelper.GetWXLog("IsSuccess=0 ORDER BY StartTime ASC");

            if (log.Id != 0)
            {
                update    = true;
                startTime = log.StartTime;
            }
            else
            {
                log = WXHelper.GetWXLog("IsSuccess=1 ORDER BY StartTime DESC");
                if (log.Id != 0)
                {
                    if (log.StartTime.Date.AddDays(1) == DateTime.Now.Date)
                    {
                        return;
                    }
                    startTime = log.EndTime.AddSeconds(1);
                }
                else
                {
                    startTime = startTime.AddDays(-1).Date;
                }
            }
            endTime = startTime.Date.AddDays(1).AddSeconds(-1);


            SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);
            WebUtils     webUtils       = new WebUtils();
            string       returnString   = string.Empty;
            DataTable    dtMsg          = CreateEmptyDataTable();
            DataRow      dr             = null;

            for (int i = 0; i < 2147483647; i++)
            {
                StringBuilder strJson = new StringBuilder();
                strJson.Append("{");
                strJson.AppendFormat("\"endtime\":{0},", DataHelper.ConvertUniversalTime(endTime));
                strJson.AppendFormat("\"pageindex\":{0},", i + 1);
                strJson.AppendFormat("\"pagesize\":{0},", pageSize);
                strJson.AppendFormat("\"starttime\":{0}", DataHelper.ConvertUniversalTime(startTime));
                strJson.Append("}");
                ErrorLog.Write("请求微信服务器,获取客服聊天记录" + strJson.ToString());
                returnString = webUtils.DoPost(string.Format(wx_MsgRecord_URL, TokenApi.GetToken_Message(masterSettings.WeixinAppId, masterSettings.WeixinAppSecret)), strJson.ToString());
                ErrorLog.Write(returnString);
                WXMsgPackage package = null;
                try
                {
                    package = Newtonsoft.Json.JsonConvert.DeserializeObject <WXMsgPackage>(returnString);
                }
                catch (Exception ex)
                {
                    ErrorLog.Write(ex.ToString());
                }

                if (package == null || package.RecordList == null || package.RecordList.Length == 0)
                {
                    break;
                }

                foreach (WXMsgRecord record in package.RecordList)
                {
                    dr             = dtMsg.NewRow();
                    dr["Id"]       = i;
                    dr["OpenId"]   = record.OpenId;
                    dr["OperCode"] = record.OperCode;
                    dr["Text"]     = record.Text;
                    dr["Worker"]   = record.Worker;
                    if (string.IsNullOrEmpty(record.Worker) || record.Worker.Trim() == "")
                    {
                        dr["WorkerNo"] = "";
                    }
                    else
                    {
                        dr["WorkerNo"] = record.Worker.Substring(0, record.Worker.IndexOf('@'));
                    }
                    DateTime d = DataHelper.ConvertTimeFromUniversal(record.UniversalTime);
                    dr["Time"]        = d;
                    dr["HappenDate"]  = d.Date;
                    dr["HappenMonth"] = d.ToString("yyyy-MM");
                    dtMsg.Rows.Add(dr);
                }
                //break;
            }
            WXLog newLog = new WXLog();

            newLog.AddTime    = DateTime.Now;
            newLog.UpdateTime = DateTime.Now;
            newLog.StartTime  = startTime;
            newLog.EndTime    = endTime;
            newLog.Type       = 1;
            if (dtMsg.Rows.Count <= 0)
            {
                newLog.IsSuccess = true;
                newLog.Remark    = "当前查询时间没有记录";
                WXHelper.InsertLog(newLog);
                return;
            }

            bool b = WXHelper.BathAddWXMsgRecord(dtMsg);

            ErrorLog.Write(Newtonsoft.Json.JsonConvert.SerializeObject(newLog));
            if (b)
            {
                newLog.IsSuccess = true;
                if (update)
                {
                    newLog.Id     = log.Id;
                    newLog.Remark = "修复聊天记录成功";
                    WXHelper.UpdateLog(newLog);
                }
                else
                {
                    newLog.Remark = "更新聊天记录完成";
                    WXHelper.InsertLog(newLog);
                }
            }
            else
            {
                newLog.IsSuccess = false;
                if (update)
                {
                    newLog.Id     = log.Id;
                    newLog.Remark = "修复聊天记录失败";
                    WXHelper.UpdateLog(newLog);
                }
                else
                {
                    newLog.Remark = "更新聊天记录失败";
                    WXHelper.InsertLog(newLog);
                }
            }
        }
コード例 #26
0
        public EAccount PlatformLogin(string userInfo)
        {
            LogHelper.DebugLog("PlatformLogin:"******"\p{Cs}", "");
            string   iconUrl    = pars[3];
            string   longitude  = pars[4];
            string   latitude   = pars[5];
            string   address    = pars[6];
            string   systemName = pars[7];

            if (platform == "WX" && !iconUrl.Contains("http:"))
            {
                string         json           = HttpService.Get(WXHelper.getCodeRequestUrl(iconUrl));
                TokenAndOpenID tokenAndOpenID = JsonConvert.DeserializeObject <TokenAndOpenID>(json);
                if (tokenAndOpenID != null)
                {
                    openID = tokenAndOpenID.openid;
                    string   json2    = HttpService.Get(WXHelper.getUserInfoUrl(tokenAndOpenID.access_token, tokenAndOpenID.openid));
                    UserInfo userinfo = JsonConvert.DeserializeObject <UserInfo>(json2);
                    if (userinfo != null)
                    {
                        nickName = userinfo.nickname;
                        iconUrl  = userinfo.headimgurl;
                    }
                }
            }

            EAccount user = DBBase.Query <EAccount>("OpenID='" + openID + "'").FirstOrDefault();

            if (user == null)
            {
                user = new EAccount()
                {
                    OpenID          = openID,
                    NickName        = nickName,
                    Face            = iconUrl,
                    Longitude       = longitude,
                    Latitude        = latitude,
                    Address         = address,
                    PlatformName    = platform,
                    CreateTime      = DateTime.Now,
                    LastLoginTime   = DateTime.Now,
                    SystemName      = systemName,
                    LastGetGoldTime = DateTime.Now,
                    Gold            = 1000,
                    Diamond         = 0
                };
                user = (EAccount)DBBase.Create(user);
            }
            else
            {
                //修改客户端推送ID
                user.Longitude     = longitude;
                user.Latitude      = latitude;
                user.Address       = address;
                user.SystemName    = systemName;
                user.LastLoginTime = DateTime.Now;

                double dayNum = (DateTime.Now - user.LastGetGoldTime).TotalDays;
                user.Gold           += user.Vip * (int)dayNum * 10;
                user.LastGetGoldTime = DateTime.Now;
                DBBase.Change(user);
            }
            //创建登录记录
            ELoginRecord loginRecord = new ELoginRecord()
            {
                AccountID = user.ID,
                LoginTime = DateTime.Now
            };

            DBBase.Create(loginRecord);

            int referrerCount = DBBase.Query <EAccount>("ReferrerID=" + user.ID + "").Count();

            if (referrerCount > user.TaskProcess)
            {
                user.TaskProcess = referrerCount;
                int taskGetDiamon = 0;
                if (user.TaskProcess == 1)
                {
                    taskGetDiamon = 10;
                }
                else if (user.TaskProcess == 10)
                {
                    taskGetDiamon = 100;
                }
                else if (user.TaskProcess == 20)
                {
                    taskGetDiamon = 200;
                }
                else if (user.TaskProcess == 50)
                {
                    taskGetDiamon = 500;
                }
                user.Diamond += taskGetDiamon;
                DBBase.Change(user);
            }

            List <EBattleServers> serverList = DBBase.Query <EBattleServers>();
            EBattleServers        server     = serverList.FirstOrDefault(c => c.ID == 1);

            user.CurBattleIP    = server.IP;
            user.CurBattlePort  = server.Port;
            user.CurTaskProcess = referrerCount;
            return(user);
        }
コード例 #27
0
        public override void OnPaySucceed(AliWapPayCallBackInfo info)
        {
            ExceptionLog log = new ExceptionLog();

            log.Message = string.Format("订单号:{0},支付宝交易号:{1}",
                                        info.out_trade_no, info.trade_no);
            ExceptionLogDAL.InsertExceptionLog(log);

            if (info.result.ToLower() == "success")
            {
                oid   = info.out_trade_no;
                payid = info.trade_no;

                MSProductOrderDAL ptitleDal = new MSProductOrderDAL();
                int paystate = 0;
                try
                {
                    paystate = Convert.ToInt32(ptitleDal.GetOrderValueByID("PayState", info.out_trade_no).ToString());
                }
                catch (Exception)
                {
                }
                if (paystate == 0)
                {
                    bool updatepayway   = ptitleDal.UpdateOrderPayWay(info.out_trade_no, "alipay");
                    bool updateOrderNum = MSProductOrderDAL.UpdateOrderPayState(info.out_trade_no, "1");
                    MSOrderLogDAL.AddMSOrderLog("订单【" + info.out_trade_no + "】支付成功,支付方式:支付宝支付");
                    if (updatepayway == true && updateOrderNum == true)
                    {
                        string countcost = string.Empty; string pid = string.Empty; string pname = string.Empty;
                        #region -获取用户数据
                        string strOpenID = string.Empty; string customerid = string.Empty;
                        try
                        {
                            customerid = ptitleDal.GetOrderValueByID("CustomerID", info.out_trade_no).ToString();
                        }
                        catch (Exception)
                        {
                        }
                        if (customerid != null && customerid != "")
                        {
                            MSCustomersDAL CustomerDal = new MSCustomersDAL();
                            try
                            {
                                strOpenID = CustomerDal.GetCustomerValueByID("OpenID", customerid).ToString();
                            }
                            catch (Exception)
                            {
                            }
                        }
                        #endregion
                        #region -获取产品信息
                        try
                        {
                            countcost = ptitleDal.GetOrderDetailValueByOID("UnitCost", info.out_trade_no).ToString();
                        }
                        catch (Exception)
                        {
                        }
                        try
                        {
                            pid = ptitleDal.GetOrderDetailValueByOID("PID", info.out_trade_no).ToString();
                        }
                        catch (Exception)
                        {
                        }
                        if (pid != null && pid != "")
                        {
                            MSProductDAL ProductDal = new MSProductDAL();
                            pname = ProductDal.GetMSProductVaueByID("Ptitle", pid).ToString();
                        }
                        #endregion
                        string      strSiteCode = GetSiteCode();
                        WXConfigDAL dal         = new WXConfigDAL();

                        WeiXinCore.WeiXin           wx        = WXHelper.CreateWeiXinInstanceBySiteCode(strSiteCode);
                        List <TemplateMessageParam> paramList = new List <TemplateMessageParam>();
                        paramList.Add(new TemplateMessageParam("first",
                                                               "我们已收到您的货款,订单号为:" + info.out_trade_no +
                                                               ";我们将尽快为您打包商品,请耐心等待: )"));
                        paramList.Add(new TemplateMessageParam("orderMoneySum", countcost + " 元"));
                        paramList.Add(new TemplateMessageParam("orderProductName", pname));
                        paramList.Add(new TemplateMessageParam("Remark", "如有问题请致电400-885-5790或直接在微信留言,小V将第一时间为您服务!"));
                        wx.SendTemplateMessage(strOpenID, "IR3TlAC2Y3lW0jaksuPRwHrVHe5nmbWRcD6ZeUPZPlA",
                                               "http://www.vgo2013.com/PalmShop/ShopCode/OrderDetail.aspx?oid=" + info.out_trade_no,
                                               paramList.ToArray(), "");
                        MSOrderLogDAL.AddMSOrderLog("发送模板消息到客户OpenID为【" + strOpenID + "】大致为:我们已收到您的货款" + countcost + "元,产品名称【" + pname + "】我们将尽快为您打包商品,请耐心等待: )");
                    }
                }
            }
        }
コード例 #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string code  = Request.QueryString["code"];
                string state = Request.QueryString["state"];

                #region 使用微信AccessToken获取微信用户信息,但不包括用户UnionID信息
                if (!string.IsNullOrEmpty(code))
                {
                    OAuthToken oauthToken = JsonConvert.DeserializeObject <OAuthToken>(new WXHelper().Request(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, secret, code), "", "GET"));

                    string      accesstoken = string.Empty;
                    AccessToken token       = JsonConvert.DeserializeObject <AccessToken>(new WXHelper().Request(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, secret), "", "GET"));

                    if (token != null && !string.IsNullOrEmpty(token.access_token))
                    {
                        accesstoken = token.access_token;
                    }

                    if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid))
                    {
                        string        strResult = new WXHelper().Request(string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, oauthToken.openid), "", "GET");
                        OAuthUserInfo userInfo  = JsonConvert.DeserializeObject <OAuthUserInfo>(strResult);

                        if (userInfo != null)
                        {
                            object objUrl = CacheHelper.GetCache(state);
                            if (objUrl != null)
                            {
                                UriBuilder URL       = new UriBuilder(objUrl.ToString());
                                string     directUrl = URL.ToString();
                                directUrl += string.Format("?openid={0}&nickname={1}&sex={2}&province={3}&city={4}&country={5}&headimgurl={6}&unionid={7}",
                                                           userInfo.openid, userInfo.nickname, userInfo.sex, userInfo.province, userInfo.city, userInfo.country, userInfo.headimgurl, userInfo.unionid);

                                Response.Redirect(directUrl);
                            }
                        }
                    }
                }
                #endregion

                #region 使用微信SNSToken获取微信用户信息,包括用户UnionID信息
                if (!string.IsNullOrEmpty(code))
                {
                    WXHelper WXHelper       = new WXHelper();
                    string   strGetSnsToken = WXHelper.Request(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, secret, code), "", "GET");
                    JObject  jo1            = JsonConvert.DeserializeObject <JObject>(strGetSnsToken);

                    string        strResult = WXHelper.Request(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN ", jo1["access_token"].ToString(), jo1["openid"].ToString()), "", "GET");
                    OAuthUserInfo userInfo  = JsonConvert.DeserializeObject <OAuthUserInfo>(strResult);
                    if (userInfo != null)
                    {
                        object objUrl = CacheHelper.GetCache(state);
                        if (objUrl != null)
                        {
                            UriBuilder URL       = new UriBuilder(objUrl.ToString());
                            string     directUrl = URL.ToString();
                            directUrl += string.Format("?openid={0}&nickname={1}&sex={2}&province={3}&city={4}&country={5}&headimgurl={6}&unionid={7}",
                                                       userInfo.openid, userInfo.nickname, userInfo.sex, userInfo.province, userInfo.city, userInfo.country, userInfo.headimgurl, userInfo.unionid);

                            Response.Redirect(directUrl);
                        }
                    }
                }
                #endregion
            }
        }