Exemple #1
0
 /// <summary>
 /// 必须传入Debug,Url,可选传入:WeChatPublic
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public string CreateWxConfig(WeChatParam param)
 {
     try
     {
         var noncestr    = PayUtil.GetNoncestr();
         var timestamp   = PayUtil.GetTimestamp();
         var jsapiTicket = Token.GetJsapiTicket(param);
         var appId       = GetConfig.GetAppid(param);
         var packageReq  = new RequestHandler();
         packageReq.SetParameter("noncestr", noncestr);
         packageReq.SetParameter("jsapi_ticket", jsapiTicket);
         packageReq.SetParameter("timestamp", timestamp);
         packageReq.SetParameter("url", param.Url);
         var signature = packageReq.CreateSHA1Sign();
         // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
         // 必填,公众号的唯一标识
         // 必填,生成签名的时间戳
         // 必填,生成签名的随机串
         // 必填,签名,见附录1
         // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
         var result = "wx.config({debug:" + (param.Debug ? "true" : "false") + ", appId: '" + appId + "', timestamp: " + timestamp + ", nonceStr: '" + noncestr + "', signature: '" + signature + "',jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','showAllNonBaseMenuItem','translateVoice','startRecord','stopRecord','onRecordEnd','playVoice','pauseVoice','stopVoice','uploadVoice','downloadVoice','chooseImage','previewImage','uploadImage','downloadImage','getNetworkType','openLocation','getLocation','hideOptionMenu','showOptionMenu','closeWindow','scanQRCode','chooseWXPay','openProductSpecificView','addCard','chooseCard','openCard'] });";//'checkJsApi',
         return(result);
     }
     catch (Exception ex)
     {
         return("var error='" + ex.Message.Replace("\r\n", "").Replace("\n", "").Replace("\t", "").Replace("<br>", "").Replace("'", "\"") + "';");
     }
 }
Exemple #2
0
        /// <summary>
        /// 获取access_token。会缓存,过期后自动重新获取新的token。
        /// </summary>
        public static string GetAccessToken(WeChatParam param = null)
        {
            var appId  = GetConfig.GetAppid(param);
            var secret = GetConfig.GetSecret(param);

            if (!AccessTokensCache.ContainsKey(appId) || AccessTokensCache[appId] == null ||
                AccessTokensCache[appId].ExpireTime < DateTime.Now)
            {
                var result = HttpHelper.Get <TokenResult>(ApiList.GetTokenUrl, new HttpParam
                {
                    { "grant_type", "client_credential" },
                    { "appid", appId },
                    { "secret", secret }
                });
                if (!result.IsSuccess)
                {
                    throw new WxException(result.errcode, result.errmsg);
                }
                AccessTokensCache[appId] = new TokenCache
                {
                    AccessToken = result.access_token,
                    ExpireTime  = DateTime.Now.AddSeconds(result.expires_in - 60)
                };
            }
            return(AccessTokensCache[appId].AccessToken);
        }
Exemple #3
0
        /// <summary>
        /// 传入:ToUser,TemplateId,Url,Data(Dictionary&lt;string,string>)
        /// </summary>
        public static WeChatResult SendTemplate(WeChatParam msg)
        {
            var sss = new Dictionary <string, object>();

            foreach (var dic in msg.Data)
            {
                sss.Add(dic.Key, new
                {
                    value = dic.Value,
                    color = "#173177"
                });
            }
            var param = JSON.ToJSON(new
            {
                touser      = msg.ToUser,
                template_id = msg.TemplateId,
                url         = msg.Url,
                topcolor    = "#FF0000",
                data        = sss
            });
            var result = HttpHelper.Post <WeChatResult>(new HttpParam()
            {
                Url       = ApiList.MessageTemplateSendUrl,
                PostParam =
                    param,
                GetParam = "access_token=" + TokenHelper.GetAccessToken()
            });

            return(result);
        }
Exemple #4
0
        /// <summary>
        ///
        /// </summary>
        public static string GetJsapiTicket(WeChatParam param)
        {
            var appId = GetConfig.GetAppid(param);

            if (!AccessTicketsCache.ContainsKey(appId) || AccessTicketsCache[appId] == null ||
                AccessTicketsCache[appId].ExpireTime < DateTime.Now)
            {
                var result = HttpHelper.Get <TokenResult>(ApiList.GetticketUrl, new HttpParam
                {
                    { "access_token", GetAccessToken(param) },
                    { "type", "jsapi" }
                });
                if (result.errmsg != "ok")
                {
                    throw new WxException(result.errcode, result.errmsg);
                }

                AccessTicketsCache[appId] = new TokenCache
                {
                    JsapiTicket = result.ticket,
                    ExpireTime  = DateTime.Now.AddSeconds(result.expires_in - 3)
                };
            }
            return(AccessTicketsCache[appId].JsapiTicket);
        }
Exemple #5
0
 private string GetMsgData(WeChatParam msg)
 {
     //var settings = new JsonSerializerSettings
     //{
     //    NullValueHandling = NullValueHandling.Ignore
     //};
     if (msg.MsgType == "news")
     {
         var a =
             new
         {
             touser  = msg.ToUser,
             msgtype = msg.MsgType,
             news    = new { articles = msg.Text }
         };
         var result = JSON.ToJSON(a);//, settings
         return(result);
     }
     else
     {
         var a =
             new
         {
             text    = new { content = msg.Text },
             msgtype = msg.MsgType,
             touser  = msg.ToUser
         };
         var result = JSON.ToJSON(a);//, settings
         return(result);
     }
 }
Exemple #6
0
 public static string GetCertPwd(WeChatParam param = null)
 {
     if (param == null || string.IsNullOrWhiteSpace(param.WeChatPublic) || param.WeChatPublic == EnumHelper.WeChatPublic.Xcz.ToString())
     {
         return(WebConfigurationManager.AppSettings["WeChatCertPwd"]);
     }
     return(WebConfigurationManager.AppSettings["WeChatCertPwd_" + param.WeChatPublic]);
 }
Exemple #7
0
        /// <summary>
        /// 获取第三方平台AccessToken
        /// 传入component_verify_ticket
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static ComponentTokenResult GetOpenAccessToken(WeChatParam param)
        {
            var result = Open.GetComponentToken(new WeChatParam()
            {
                ComponentVerifyTicket = param.ComponentVerifyTicket
            });

            return(result);
        }
Exemple #8
0
        /// <summary>
        /// 取消当前使用的自定义菜单
        /// </summary>
        public static WeChatResult Delete(WeChatParam param)
        {
            var result = HttpHelper.Get <WeChatResult>(ApiList.MenuDeleteUrl, new HttpParam()
            {
                { "access_token", Token.GetAccessToken(param) }
            });

            return(result);
        }
        /// <summary>
        /// 传入OpenId,AccessToken
        /// </summary>
        public static UserInfoResult GetUserInfo(WeChatParam param)
        {
            var result = HttpHelper.Get <UserInfoResult>(ApiList.GetUserInfo, new
            {
                access_token = TokenHelper.GetAccessToken(),
                openid       = param.OpenId,
                lang         = "zh_CN"
            });

            return(result);
        }
Exemple #10
0
        /// <summary>
        /// 传入OpenId,AccessToken
        /// </summary>
        public static UserInfoModel GetUserInfo(WeChatParam param)
        {
            var result = HttpHelper.Get <UserInfoModel>(ApiList.GetUserInfo, new HttpParam()
            {
                { "access_token", Token.GetAccessToken(param) },
                { "openid", param.OpenId },
                { "lang", "zh_CN" }
            });

            return(result);
        }
Exemple #11
0
        /// <summary>
        /// 验证签名
        /// </summary>
        public bool Check(WeChatParam param = null)
        {
            var token = GetConfig.GetToken(param);
            var vs = new[] { timestamp, nonce, token }.OrderBy(s => s);
            var str  = string.Join("", vs);
            var copu = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");

            if (copu == null)
            {
                return(false);
            }
            return(copu.Equals(signature, StringComparison.CurrentCultureIgnoreCase));
        }
Exemple #12
0
        /// <summary>
        /// 传入Code
        /// </summary>
        public static Dictionary <string, string> GetOauth2AccessToken(WeChatParam param)
        {
            var param2 = new
            {
                appid      = WeChatConfig.GetAppId(),
                secret     = WeChatConfig.GetSecret(),
                code       = param.Code,
                grant_type = "authorization_code"
            };
            var dic = HttpHelper.Get <Dictionary <string, string> >(ApiList.GetOauth2AccessTokenUrl, param2);

            return(dic);
        }
Exemple #13
0
        /// <summary>
        /// 获取授权公众号的接口调用凭据(令牌)。传入:authorizer_appid(授权方appid)、authorizer_refresh_token(授权方的刷新令牌)、component_verify_ticket(微信后台推送的ticket,此ticket会定时推送)
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static AuthorizerTokenResult GetAuthorizerAccessToken(WeChatParam param)
        {
            if (string.IsNullOrWhiteSpace(param.AuthorizerAppid))
            {
                return(null);
            }
            var token = CacheHelper.Get("AuthorizerAccessToken" + param.AuthorizerAppid) as AuthorizerTokenResult;

            if (token != null && !string.IsNullOrWhiteSpace(token.AuthorizerAccessToken))
            {
                return(token);
            }
            var componentAccessToken = Open.GetComponentToken(new WeChatParam()
            {
                ComponentVerifyTicket = param.ComponentVerifyTicket
            });

            if (!componentAccessToken.IsSuccess)
            {
                return(new AuthorizerTokenResult()
                {
                    IsSuccess = false,
                    ErrMsg = componentAccessToken.ErrMsg
                });
            }
            var result = HttpHelper.Post <AuthorizerTokenResult>(new HttpParam()
            {
                Url       = ApiList.ApiAuthorizerToken,
                PostParam = new
                {
                    component_appid          = WeChatConfig.GetOpenAppId(),
                    authorizer_appid         = param.AuthorizerAppid,
                    authorizer_refresh_token = param.AuthorizerRefreshToken
                },
                GetParam = new
                {
                    component_access_token = componentAccessToken.ComponentAccessToken
                }
            });

            if (result.IsSuccess && !string.IsNullOrWhiteSpace(result.AuthorizerAccessToken))
            {
                CacheHelper.Set("AuthorizerAccessToken" + param.AuthorizerAppid, result,
                                result.ExpiresIn - 60);
            }
            else
            {
                LogHelper.Debug("GetAuthorizerAccessToken失败!" + result.ErrMsg, "微信_Fail_");
            }
            return(result);
        }
Exemple #14
0
        /// <summary>
        /// 发送客服消息。必传:ToUser、MsgType、Content。WeChatType。
        /// </summary>
        public static WeChatResult Send(WeChatParam param)
        {
            var aToken = "";

            if (!string.IsNullOrWhiteSpace(param.AccessToken))
            {
                aToken = param.AccessToken;
            }
            else
            {
                if (param.WeChatType == EnumHelper.WeChatType.Open)
                {
                    var bs = TokenHelper.GetAuthorizerAccessToken(param);
                    if (!bs.IsSuccess)
                    {
                        return(bs);
                    }
                    aToken = bs.AuthorizerAccessToken;
                }
                else
                {
                    var bs = TokenHelper.GetAccessToken();
                    if (!bs.IsSuccess)
                    {
                        return(bs);
                    }
                    aToken = bs.AccessToken;
                }
            }
            var result = HttpHelper.Post <WeChatResult>(new HttpParam()
            {
                Url       = ApiList.MessageCustomSendUrl,
                PostParam =
                    new
                {
                    touser  = param.ToUser,
                    msgtype = param.MsgType,
                    text    = new
                    {
                        content = param.Content
                    }
                },
                GetParam =
                    new
                {
                    access_token = aToken
                }
            });

            return(result);
        }
Exemple #15
0
        /// <summary>
        /// 查询菜单
        /// </summary>
        /// <returns></returns>
        public static Menu Get(WeChatParam param = null)
        {
            var oo   = new { menu = new Menu() };
            var json = HttpHelper.Get(ApiList.MenuGetUrl, new HttpParam()
            {
                { "access_token", Token.GetAccessToken(param) }
            });
            var or     = JsonConvert.DeserializeAnonymousType(json, oo);
            var result = or.menu;

            if (result == null)
            {
                var retTemp = JsonConvert.DeserializeObject <WeChatResult>(json);
                throw new MenuException(retTemp.ErrCode, retTemp.ErrMsg);
            }
            return(result);
        }
Exemple #16
0
        /// <summary>
        /// 接入微信
        /// </summary>
        /// <returns></returns>
        public static bool Join(IMsgCall call, WeChatParam param = null)
        {
            var sign = ParseJoinToken();

            if (sign.Check(param))
            {
                if (JoinToken.IsGetRequest())
                {
                    sign.Response();
                }
                else
                {
                    ReceiveMsg.Reg(call);
                }
                return(true);
            }
            return(false);
        }
Exemple #17
0
        /// <summary>
        /// 查询菜单。
        /// 取公众号菜单,不需要传入参数。若是开放平台,则需要传入AuthorizerAppid(授权方appid)、AuthorizerRefreshToken(授权方的刷新令牌)、ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)
        /// </summary>
        /// <returns></returns>
        public static MenuResult Get(WeChatParam param = null)
        {
            //var menuObj = new { menu = new MenuResult() };
            var httpParam = new HttpParam();
            var aToken    = "";

            if (param != null && param.WeChatType == EnumHelper.WeChatType.Open)
            {
                var bs = TokenHelper.GetAuthorizerAccessToken(param);
                if (!bs.IsSuccess)
                {
                    return(new MenuResult()
                    {
                        IsSuccess = false,
                        ErrMsg = bs.ErrMsg
                    });
                }
                aToken = bs.AuthorizerAccessToken;
            }
            else
            {
                var bs = TokenHelper.GetAccessToken();
                if (!bs.IsSuccess)
                {
                    return(new MenuResult()
                    {
                        IsSuccess = false,
                        ErrMsg = bs.ErrMsg
                    });
                }
                aToken = bs.AccessToken;
            }
            string json = HttpHelper.Get(ApiList.MenuGetUrl, new { access_token = aToken });
            //var or = JsonConvert.DeserializeAnonymousType(json, menuObj);
            var or     = JSON.ToObject <menuObj>(json);//, menuObj
            var result = or.menu;

            if (result == null)
            {
                var retTemp = JSON.ToObject <MenuResult>(json);
                return(retTemp);
            }
            return(result);
        }
Exemple #18
0
        /// <summary>
        /// 使用授权码换取公众号的接口调用凭据和授权信息
        /// <para>传入:AuthorizationCode(授权code)、ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        public static QueryAuthResult QueryAuth(WeChatParam param)
        {
            var result = CacheHelper.Get("QueryAuth") as QueryAuthResult;

            if (result == null || string.IsNullOrWhiteSpace(result.AuthorizationInfo.AuthorizerAccessToken))
            {
                var token = GetComponentToken(new WeChatParam()
                {
                    ComponentVerifyTicket = param.ComponentVerifyTicket
                });
                if (!token.IsSuccess)
                {
                    return(new QueryAuthResult()
                    {
                        IsSuccess = false,
                        ErrMsg = token.ErrMsg
                    });
                }
                result = HttpHelper.Post <QueryAuthResult>(new HttpParam()
                {
                    Url       = ApiList.ApiQueryAuth,
                    PostParam = new
                    {
                        component_appid    = WeChatConfig.GetOpenAppId(),
                        authorization_code = param.AuthorizationCode
                    },
                    GetParam = new
                    {
                        component_access_token = token.ComponentAccessToken
                    }
                });
                if (result.AuthorizationInfo != null)
                {
                    CacheHelper.Set("QueryAuth", result, result.AuthorizationInfo.ExpiresIn - 60);
                }
                else
                {
                    LogHelper.Debug("QueryAuth失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Exemple #19
0
        /// <summary>
        /// 获取预授权码.该API用于获取预授权码。预授权码用于公众号授权时的第三方平台方安全验证。
        /// <para>传入:ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        /// <returns>返回:pre_auth_code(预授权码)、expires_in(有效期,为20分钟)</returns>
        public static CreatePreauthcodeResult GetCreatePreAuthCode(WeChatParam param)
        {
            var result = CacheHelper.Get("PreAuthCode") as CreatePreauthcodeResult;

            if (result == null || string.IsNullOrWhiteSpace(result.PreAuthCode))
            {
                var token = GetComponentToken(new WeChatParam()
                {
                    ComponentVerifyTicket = param.ComponentVerifyTicket
                });
                if (!token.IsSuccess)
                {
                    return(new CreatePreauthcodeResult()
                    {
                        IsSuccess = false,
                        ErrMsg = token.ErrMsg
                    });
                }
                result = HttpHelper.Post <CreatePreauthcodeResult>(new HttpParam()
                {
                    Url       = ApiList.ApiCreatePreauthcode,
                    PostParam = new
                    {
                        component_appid = WeChatConfig.GetOpenAppId()
                    },
                    GetParam = new
                    {
                        component_access_token = token.ComponentAccessToken
                    }
                });
                if (!string.IsNullOrWhiteSpace(result.PreAuthCode))
                {
                    CacheHelper.Set("PreAuthCode", result, result.ExpiresIn);
                }
                else
                {
                    LogHelper.Debug("GetCreatePreAuthCode失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Exemple #20
0
        /// <summary>
        /// 获取第三方平台access_token。该API用于获取第三方平台令牌(component_access_token)
        /// <para>传入:ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        /// <returns>返回ComponentAccessToken(第三方平台access_token)</returns>
        public static ComponentTokenResult GetComponentToken(WeChatParam param)
        {
            var result = CacheHelper.Get("ComponentToken") as ComponentTokenResult;

            if (result == null || string.IsNullOrWhiteSpace(result.ComponentAccessToken))
            {
                result = HttpHelper.Post <ComponentTokenResult>(ApiList.ApiComponentToken, new
                {
                    component_appid         = WeChatConfig.GetOpenAppId(),
                    component_appsecret     = WeChatConfig.GetOpenAppSecret(),
                    component_verify_ticket = param.ComponentVerifyTicket
                });
                if (!string.IsNullOrWhiteSpace(result.ComponentAccessToken))
                {
                    CacheHelper.Set("ComponentToken", result, result.ExpiresIn - 60);
                }
                else
                {
                    LogHelper.Debug("GetComponentToken失败!" + result.ErrMsg, "微信_Fail_");
                }
            }
            return(result);
        }
Exemple #21
0
        /// <summary>
        /// 验证签名。默认公众号不需要参数。传入authorizer_appid(授权方appid)、authorizer_refresh_token(授权方的刷新令牌)则验证该公众号(用于微信开放平台)、component_verify_ticket(微信后台推送的ticket,此ticket会定时推送)
        /// </summary>
        public bool Check(WeChatParam param = null)
        {
            string token;

            if (param != null && !string.IsNullOrWhiteSpace(param.AuthorizerAppid))
            {
                if (string.IsNullOrWhiteSpace(param.AuthorizerRefreshToken))
                {
                    LogHelper.Debug("参数错误!authorizer_refresh_token必传!", "微信CallBack_");
                    return(false);
                }
                var bs = TokenHelper.GetAuthorizerAccessToken(new WeChatParam()
                {
                    AuthorizerAppid        = param.AuthorizerAppid,
                    AuthorizerRefreshToken = param.AuthorizerRefreshToken,
                    ComponentVerifyTicket  = param.ComponentVerifyTicket
                });
                if (!bs.IsSuccess)
                {
                    return(false);
                }
                token = bs.AuthorizerAccessToken;
            }
            else
            {
                token = WeChatConfig.GetToken();
            }
            var vs = new[] { timestamp, nonce, token }.OrderBy(s => s);
            var str  = string.Join("", vs);
            var copu = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");

            if (copu == null)
            {
                return(false);
            }
            return(copu.Equals(signature, StringComparison.CurrentCultureIgnoreCase));
        }
Exemple #22
0
        /// <summary>
        /// 创建菜单。传入Menu。若是开放平台,则需要传入AuthorizerAppid(授权方appid)、AuthorizerRefreshToken(授权方的刷新令牌)、ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)
        /// </summary>
        public static WeChatResult Save(WeChatParam param)
        {
            var token = "";

            if (param.WeChatType == EnumHelper.WeChatType.Open)
            {
                var bs = TokenHelper.GetAuthorizerAccessToken(param);
                if (!bs.IsSuccess)
                {
                    return(bs);
                }
                token = bs.AuthorizerAccessToken;
            }
            else
            {
                var bs = TokenHelper.GetAccessToken();
                if (!bs.IsSuccess)
                {
                    return(bs);
                }
                token = bs.AccessToken;
            }

            var r = HttpHelper.Post <WeChatResult>(new HttpParam()
            {
                Url       = ApiList.MenuCreateUrl,
                PostParam =
                    JSON.ToNiceJSON(param.Menu, new JSONParameters()
                {
                    SerializeNullValues = false,
                    UseEscapedUnicode   = false
                }),//, new JsonSerializerSettings{NullValueHandling = ullValueHandling.Ignore}
                GetParam = "access_token=" + token
            });

            return(r);
        }
Exemple #23
0
        /// <summary>
        /// 获取授权方的公众号帐号基本信息。该API用于获取授权方的公众号基本信息,包括头像、昵称、帐号类型、认证类型、微信号、原始ID和二维码图片URL。
        /// <para>传入:AuthorizerAppid(授权方appid)、ComponentVerifyTicket(微信后台推送的ticket,此ticket会定时推送)</para>
        /// </summary>
        /// <param name="param"></param>
        public static GetAuthorizerInfoResult GetAuthorizerInfo(WeChatParam param)
        {
            var token = GetComponentToken(new WeChatParam()
            {
                ComponentVerifyTicket = param.ComponentVerifyTicket
            });

            if (!token.IsSuccess)
            {
                return(new GetAuthorizerInfoResult()
                {
                    IsSuccess = false,
                    ErrMsg = token.ErrMsg
                });
            }
            var str = HttpHelper.Post(new HttpParam()
            {
                Url       = ApiList.ApiGetAuthorizerInfo,
                PostParam =
                    new
                {
                    component_appid  = WeChatConfig.GetOpenAppId(),
                    authorizer_appid = param.AuthorizerAppid
                },
                GetParam = new
                {
                    component_access_token = token.ComponentAccessToken
                }
            });
            var result = JSON.ToObject <GetAuthorizerInfoResult>(str);

            if (!result.IsSuccess)
            {
                LogHelper.Debug("GetAuthorizerInfo失败!" + result.ErrMsg, "微信_Fail_");
            }
            return(result);
        }
Exemple #24
0
        ///// <summary>
        /////
        ///// </summary>
        //public string CreateUrl { get; set; }
        ///// <summary>
        /////
        ///// </summary>
        //public string QueryUrl { get; set; }
        ///// <summary>
        /////
        ///// </summary>
        //public string DeleteUrl { get; set; }

        ///// <summary>
        ///// 获取默认的MenuHelper。
        ///// 此实例设置了默认Url并(在传递null时)读取缓存的access_token
        ///// </summary>
        ///// <returns></returns>
        //public static MenuHelper Create(string accessToken = null)
        //{
        //    var result = new MenuHelper
        //    {
        //        CreateUrl = ApiList.MenuCreateUrl,
        //        QueryUrl = ApiList.MenuGetUrl,
        //        DeleteUrl = ApiList.MenuDeleteUrl
        //    };
        //    return result;
        //}

        /// <summary>
        /// 创建菜单
        /// </summary>
        public static WeChatResult Save(Menu menu, WeChatParam param = null)
        {
            var r = HttpHelper.Post <WeChatResult>(ApiList.MenuCreateUrl, menu.ToString(), "access_token=" + Token.GetAccessToken(param));

            return(r);
        }
Exemple #25
0
        /// <summary>
        /// billDate格式 20141212
        /// </summary>
        /// <param name="context"></param>
        /// <param name="billDate"></param>
        /// <returns></returns>
        public static BaseResult DownloadBill(string billDate, WeChatParam param)
        {
            var packageReq = new RequestHandler();

            packageReq.SetKey(GetConfig.GetKey(param));
            packageReq.SetParameter("appid", GetConfig.GetAppid(param));
            packageReq.SetParameter("mch_id", GetConfig.GetMchId(param));
            packageReq.SetParameter("nonce_str", GetNoncestr());
            packageReq.SetParameter("bill_date", billDate);
            packageReq.SetParameter("bill_type", "ALL");
            packageReq.SetParameter("sign", packageReq.CreateMd5Sign());
            var reqXml     = packageReq.ParseXml();
            var httpClient = new HttpUtil();

            httpClient.SetCharset(HttpContext.Current.Request.ContentEncoding.BodyName);
            var result = httpClient.Send(reqXml, ApiList.DownloadBillUrl);

            try
            {
                var xe        = XElement.Parse(result, LoadOptions.SetLineInfo);
                var reResult1 = xe.GetElement("return_code") == null ? "" : xe.GetElement("return_code").Value;
                var reResult2 = xe.GetElement("return_msg") == null ? "" : xe.GetElement("return_msg").Value;
                return(new BaseResult()
                {
                    IsSuccess = false, Data = "", Message = reResult1 + "_" + reResult2
                });
            }
            catch (Exception)
            {
                var list   = new List <Bill>();
                var myList = result.Replace("\r\n", "|").Split('|').Skip(1).ToList <string>();
                myList.RemoveAt(myList.Count() - 1);
                myList.RemoveAt(myList.Count() - 1);
                myList.RemoveAt(myList.Count() - 1);
                string[] arr;
                foreach (var str in myList)
                {
                    arr = str.Replace("`", "").Split(',');
                    #region 赋值
                    list.Add(new Bill()
                    {
                        交易时间     = arr[0],
                        公众账号ID   = arr[1],
                        商户号      = arr[2],
                        子商户号     = arr[3],
                        设备号      = arr[4],
                        微信订单号    = arr[5],
                        商户订单号    = arr[6],
                        用户标识     = arr[7],
                        交易类型     = arr[8],
                        交易状态     = arr[9],
                        付款银行     = arr[10],
                        货币种类     = arr[11],
                        总金额      = arr[12],
                        企业红包金额   = arr[13],
                        微信退款单号   = arr[14],
                        商户退款单号   = arr[15],
                        退款金额     = arr[16],
                        企业红包退款金额 = arr[17],
                        退款类型     = arr[18],
                        退款状态     = arr[19],
                        商品名称     = arr[20],
                        商户数据包    = arr[21],
                        手续费      = arr[22],
                        费率       = arr[23]
                    });
                    #endregion
                }
                return(new BaseResult()
                {
                    IsSuccess = true, Data = list
                });
            }
        }
Exemple #26
0
        public static BaseResult Notify(WeChatParam param)
        {
            try
            {
                var res = new ResponseHandler();
                res.SetKey(GetConfig.GetKey(param));
                var error = "";
                //判断签名
                if (res.IsWXsign(out error))
                {
                    #region 参数
                    var returnCode = res.GetParameter("return_code");
                    //返回信息,如非空,为错误原因签名失败参数格式校验错误
                    var returnMsg = res.GetParameter("return_msg");
                    var appid     = res.GetParameter("appid");

                    //以下字段在 return_code 为 SUCCESS 的时候有返回--------------------------------
                    var mchId      = res.GetParameter("mch_id");
                    var deviceInfo = res.GetParameter("device_info");
                    var nonceStr   = res.GetParameter("nonce_str");
                    var resultCode = res.GetParameter("result_code");
                    var errCode    = res.GetParameter("err_code");
                    var errCodeDes = res.GetParameter("err_code_des");

                    //以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回---------------
                    var openid = res.GetParameter("openid");
                    //Y-关注,N-未关注,仅在公众账号类型支付有效
                    var isSubscribe = res.GetParameter("is_subscribe");
                    var tradeType   = res.GetParameter("trade_type");
                    //银行类型,采用字符串类型的银行标识
                    var bankType = res.GetParameter("bank_type");
                    var totalFee = res.GetParameter("total_fee");
                    //货币类型,符合 ISO 4217 标准的三位字母代码,默认人民币:CNY
                    var feeType = res.GetParameter("fee_type");
                    //微信支付订单号
                    var transactionId = res.GetParameter("transaction_id");
                    //商户系统的订单号,与请求一致。
                    var outTradeNo = res.GetParameter("out_trade_no");
                    var attach     = res.GetParameter("attach");
                    //格 式 为yyyyMMddhhmmss
                    var timeEnd = res.GetParameter("time_end");
                    #endregion
                    //支付成功
                    if (!outTradeNo.Equals("") && returnCode.Equals("SUCCESS") && resultCode.Equals("SUCCESS"))
                    {
                        //LogHelper.WriteLog("支付回调:", sbResult.ToString() + "notify > success \r\n",EnumService.LogType.Debug);
                        //在外面回写订单
                        return(new BaseResult()
                        {
                            IsSuccess = true,
                            Data = new Dictionary <string, string>
                            {
                                { "OrderNumber", outTradeNo },
                                { "WeChat", openid },
                            }
                        });
                    }
                    else
                    {
                        //LogHelper.WriteLog("支付回调:", sbResult.ToString() + "notify > total_fee= " + totalFee + " \r\n  err_code_des= " + errCodeDes + " \r\n  result_code= " + resultCode + " \r\n", EnumService.LogType.Exception);
                    }
                }
                else
                {
                    //LogHelper.WriteLog("支付回调:",sbResult.ToString() + "notify > isWXsign= false \r\n" + error, EnumService.LogType.Exception);
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog("支付回调:",sbResult.ToString() + "notify > ex=" + ex.Message + @ex.StackTrace + @ex.InnerException + " \r\n",  EnumService.LogType.Exception);
            }
            return(new BaseResult()
            {
                IsSuccess = false
            });
        }