Ejemplo n.º 1
0
 /// <summary>
 /// 必须传入Debug,Url,可选传入:WeChatPublic
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public static 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("'", "\"") + "';";
     }
 }
Ejemplo n.º 2
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];
 }
Ejemplo n.º 3
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;
 }
Ejemplo n.º 4
0
 public static string GetCertPwd(WeChatParam param)
 {
     if (param.WeChatPublic == EnumHelper.WeChatPublic.Xcz.ToString())
     {
         return WebConfigurationManager.AppSettings["WeChatCertPwd"];
     }
     else if (param.WeChatPublic == EnumHelper.WeChatPublic.XczJl.ToString())
     {
         return WebConfigurationManager.AppSettings["WeChatCertPwd_XczJl"];
     }
     return WebConfigurationManager.AppSettings["WeChatCertPwd"];
 }
Ejemplo n.º 5
0
 public static string GetKey(WeChatParam param)
 {
     if (param.WeChatPublic == EnumHelper.WeChatPublic.Xcz.ToString())
     {
         return WebConfigurationManager.AppSettings["PartnerKey"];
     }
     else if (param.WeChatPublic == EnumHelper.WeChatPublic.XczJl.ToString())
     {
         return WebConfigurationManager.AppSettings["PartnerKey_XczJl"];
     }
     return WebConfigurationManager.AppSettings["PartnerKey"];
 }
Ejemplo n.º 6
0
 /// <summary>
 /// 验证签名
 /// </summary>
 public bool Check(WeChatParam param)
 {
     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);
 }
Ejemplo n.º 7
0
 /// <summary>
 /// 查询菜单
 /// </summary>
 /// <returns></returns>
 public Menu Get(WeChatParam param)
 {
     var oo = new { menu = new Menu() };
     var json = HttpHelper.Get(QueryUrl, 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;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// 获取access_token。会缓存,过期后自动重新获取新的token。
        /// </summary>
        public static string GetAccessToken(WeChatParam param)
        {
            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;

        }
Ejemplo n.º 9
0
 /// <summary>
 /// billDate格式 20141212
 /// </summary>
 /// <param name="context"></param>
 /// <param name="billDate"></param>
 /// <returns></returns>
 public BaseResult DownloadBill(HttpContextBase context, string billDate,WeChatParam param)
 {
     var packageReq = new RequestHandler(context);
     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(context.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 };
     }
 }
Ejemplo n.º 10
0
        public BaseResult Notify(WeChatParam param,HttpContextBase context)
        {
            var sbResult = new StringBuilder();
            try
            {
                sbResult.Append("@参数:" + JsonConvert.SerializeObject(param) + "\r\n");
                sbResult.Append("@HttpContextLength:" + context.Request.InputStream.Length + "\r\n");
                sbResult.Append("@开始创建ResponseHandler实例\r\n");
                var res = new ResponseHandler(context);
                sbResult.Append("@创建ResponseHandler实例成功\r\n");
                res.SetKey(GetConfig.GetKey(param));
                sbResult.Append("@设置密钥成功\r\n");
                var error = "";
                //判断签名
                if (res.IsWXsign(out error))
                {
                    sbResult.Append("@判断签名成功\r\n");
                    #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
                    sbResult.Append("@取所有参数成功\r\n");
                    //支付成功
                    if (!outTradeNo.Equals("") && returnCode.Equals("SUCCESS") && resultCode.Equals("SUCCESS"))
                    {
                        sbResult.Append("@支付成功\r\n" + outTradeNo);
                        //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
                    {
                        sbResult.Append("@支付失败\r\n");
                        //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
                {
                    sbResult.Append("@判断签名失败\r\n");
                    //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 };
        }
Ejemplo n.º 11
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;
        }
Ejemplo n.º 12
0
 /// <summary>
 /// 取消当前使用的自定义菜单
 /// </summary>
 public WeChatResult Delete(WeChatParam param)
 {
     var result = HttpHelper.Get<WeChatResult>(DeleteUrl, new HttpParam() { { "access_token", Token.GetAccessToken(param) } });
     return result;
 }
Ejemplo n.º 13
0
 /// <summary>
 /// 创建菜单
 /// </summary>
 public WeChatResult CreateMenu(Menu menu, WeChatParam param)
 {
     var r = HttpHelper.Post<WeChatResult>(CreateUrl, menu.ToString(), "access_token=" + Token.GetAccessToken(param));
     return r;
 }
Ejemplo n.º 14
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;
        }
Ejemplo n.º 15
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;
 }