Exemple #1
0
        public bool CheckPayNotifySign(WxAppInfoConfig config, string xml)
        {
            var dic1 = WeiXinSdk.CommonUtil.ToDictionary(xml);

            if (dic1["sign"] == null)
            {
                return(false);
            }

            string wxSign = dic1["sign"].ToString();


            bool   isFlag = true;
            string buff   = "";

            foreach (KeyValuePair <string, object> pair in dic1)
            {
                if (pair.Value == null)
                {
                    isFlag = false;
                    break;
                }

                if (pair.Key != "sign" && pair.Value.ToString() != "")
                {
                    buff += pair.Key + "=" + pair.Value + "&";
                }
            }

            if (!isFlag)
            {
                return(false);
            }

            buff = buff.Trim('&');


            //在string后加入API KEY
            buff += "&key=" + config.PayKey;
            //MD5加密
            var md5 = MD5.Create();
            var bs  = md5.ComputeHash(Encoding.UTF8.GetBytes(buff));
            var sb  = new StringBuilder();

            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            //所有字符转为大写
            string mySign = sb.ToString().ToUpper();

            if (wxSign != mySign)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Exemple #2
0
        public UnifiedOrderResult UnifiedOrderByJsApi(WxAppInfoConfig config, string openId, string orderSn, decimal orderAmount, string goods_tag, string ip, string body, DateTime?time_expire = null)
        {
            var ret = new UnifiedOrderResult();

            TenpayUtil tenpayUtil = new TenpayUtil(config);

            UnifiedOrder unifiedOrder = new UnifiedOrder();

            unifiedOrder.openid           = openId;
            unifiedOrder.out_trade_no     = orderSn;                            //商户订单号
            unifiedOrder.spbill_create_ip = "192.168.1.1";                      //终端IP
            unifiedOrder.total_fee        = Convert.ToInt32(orderAmount * 100); //标价金额
            unifiedOrder.body             = body;                               //商品描述
            unifiedOrder.trade_type       = "JSAPI";
            if (time_expire != null)
            {
                unifiedOrder.time_expire = time_expire.Value.ToString("yyyyMMddHHmmss");
            }

            if (!string.IsNullOrEmpty(goods_tag))
            {
                unifiedOrder.goods_tag = goods_tag;
            }

            ret = tenpayUtil.UnifiedOrder(unifiedOrder);

            return(ret);
        }
Exemple #3
0
        public SortedDictionary <string, string> DoPost(WxAppInfoConfig config, ITenpayPostApi request, bool isUserCert = false)
        {
            string realServerUrl = GetServerUrl(this.serverUrl, request.ApiName);

            WebUtils webUtils = new WebUtils();

            _returnCoennt = webUtils.DoPost(config, realServerUrl, request.PostData, isUserCert);


            SortedDictionary <string, string> m_values = new SortedDictionary <string, string>();


            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(_returnCoennt);
            XmlNode     xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
            XmlNodeList nodes   = xmlNode.ChildNodes;

            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
            }


            return(m_values);
        }
Exemple #4
0
        public string OrderQuery(WxAppInfoConfig config, string orderSn)
        {
            CustomJsonResult result     = new CustomJsonResult();
            TenpayUtil       tenpayUtil = new TenpayUtil(config);
            string           xml        = tenpayUtil.OrderQuery(orderSn);

            return(xml);
        }
Exemple #5
0
        public CustomJsonResult <JsApiConfigParams> GetJsApiConfigParams(WxAppInfoConfig config, string url)
        {
            string jsApiTicket = GetJsApiTicket(config);

            JsApiConfigParams parms = new JsApiConfigParams(config.AppId, url, jsApiTicket);

            return(new CustomJsonResult <JsApiConfigParams>(ResultType.Success, ResultCode.Success, "", parms));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="config"></param>
        /// <param name="out_trade_no">商户内部的订单号</param>
        public TenpayOrderQueryApi(WxAppInfoConfig config, string out_trade_no)
        {
            SortedDictionary <string, object> sParams = new SortedDictionary <string, object>();

            sParams.Add("appid", config.AppId);                 //公众账号ID
            sParams.Add("mch_id", config.PayMchId);             //商户号
            sParams.Add("nonce_str", CommonUtil.GetNonceStr()); //随机字符串
            sParams.Add("out_trade_no", out_trade_no);          //微信订单号

            string sign = MakeSign(sParams, config.PayKey);

            sParams.Add("sign", sign);//签名

            _postData = GetXml(sParams);
        }
Exemple #7
0
        public TenpayUnifiedOrderApi(WxAppInfoConfig config, UnifiedOrder order)
        {
            SortedDictionary <string, object> sParams = new SortedDictionary <string, object>();

            sParams.Add("appid", config.AppId);                      //公众账号ID
            sParams.Add("mch_id", config.PayMchId);                  //商户号
            sParams.Add("nonce_str", CommonUtil.GetNonceStr());      //随机字符串
            sParams.Add("notify_url", config.PayResultNotifyUrl);    //通知地址
            sParams.Add("trade_type", order.trade_type);             //交易类型
            sParams.Add("spbill_create_ip", order.spbill_create_ip); //终端IP
            sParams.Add("out_trade_no", order.out_trade_no);         //商户订单号
            sParams.Add("total_fee", order.total_fee);               //标价金额
            sParams.Add("body", order.body);                         //商品描述
            sParams.Add("time_expire", order.time_expire);           //订单过期时间
            sParams.Add("attach", order.attach);                     //附加数据
            if (order.trade_type == "JSAPI")
            {
                sParams.Add("openid", order.openid);//用户标识
            }

            if (!string.IsNullOrEmpty(order.goods_tag))
            {
                sParams.Add("goods_tag", order.goods_tag);//商品优惠标识
            }

            if (order.trade_type == "MWEB")
            {
                sParams.Add("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://mobile.17fanju.com\",\"wap_name\": \"贩聚社团\"}}");//场景信息
            }
            //sParams.Add("device_info", "WEB");//设备号
            //sParams.Add("sign_type", "");//签名类型
            //sParams.Add("detail", "");商品详情
            //sParams.Add("attach", "");附加数据
            //sParams.Add("fee_type", "");//标价币种
            //sParams.Add("time_start", "");//交易起始时间
            //sParams.Add("time_expire", "");//交易结束时间
            //sParams.Add("goods_tag", "");//订单优惠标记
            //sParams.Add("product_id", "");//商品ID
            //sParams.Add("limit_pay", "");//指定支付方式
            //sParams.Add("openid", "openid");//用户标识
            //sParams.Add("scene_info", "");//场景信息
            string sign = MakeSign(sParams, config.PayKey);

            sParams.Add("sign", sign);//签名


            _postData = GetXml(sParams);
        }
Exemple #8
0
        public UserInfoModelByMinProramJsCode GetUserInfoByMinProramJsCode(WxAppInfoConfig config, string encryptedData, string iv, string code)
        {
            try
            {
                var    jsCode2Session = OAuthApi.GetWxApiJsCode2Session(config.AppId, config.AppSecret, code);
                string strData        = AES_decrypt(encryptedData, iv, jsCode2Session.session_key);
                LogUtil.Info("UserInfo:" + strData);
                var obj = JsonConvert.DeserializeObject <UserInfoModelByMinProramJsCode>(strData);

                return(obj);
            }
            catch
            {
                return(null);
            }
        }
Exemple #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="config"></param>
        /// <param name="out_trade_no">商户内部的订单号</param>
        public TenpayCouponQueryInfoApi(WxAppInfoConfig config, string coupon_id, string coupon_stock_id, string openid)
        {
            SortedDictionary <string, object> sParams = new SortedDictionary <string, object>();

            sParams.Add("appid", config.AppId);
            sParams.Add("coupon_id", coupon_id);
            sParams.Add("mch_id", config.PayMchId);
            sParams.Add("nonce_str", CommonUtil.GetNonceStr());
            sParams.Add("openid", openid);
            sParams.Add("stock_id", coupon_stock_id);
            string sign = MakeSign(sParams, config.PayKey);

            sParams.Add("sign", sign);

            _postData = GetXml(sParams);

            // _postData = "<xml><appid><![CDATA[wxc6e80f8c575cf3f5]]></appid><coupon_stock_id><![CDATA[3068001]]></coupon_stock_id><mch_id><![CDATA[1486589902]]></mch_id><nonce_str><![CDATA[bdb70cd1606a4669a15d5af965811f77]]></nonce_str><openid>otakHv8beYaLD9po9y6WjVe1fqt81</openid><openid_count>1</openid_count><partner_trade_no><![CDATA[202]]></partner_trade_no><sign><![CDATA[76C1EE9C00B953AC2655637D088F83ED]]></sign></xml>";
        }
Exemple #10
0
        public string GetApiAccessToken(WxAppInfoConfig config)
        {
            string wxAccessToken = System.Configuration.ConfigurationManager.AppSettings["custom:WxTestAccessToken"];

            if (wxAccessToken != null)
            {
                return(wxAccessToken);
            }

            string key = string.Format("Wx_AppId_{0}_AccessToken", config.AppId);

            var redis       = new RedisClient <string>();
            var accessToken = redis.KGetString(key);

            if (accessToken == null)
            {
                LogUtil.Info(string.Format("获取微信AccessToken,key:{0},已过期,重新获取", key));

                WxApi c = new WxApi();

                WxApiAccessToken apiAccessToken = new WxApiAccessToken("client_credential", config.AppId, config.AppSecret);

                var apiAccessTokenResult = c.DoGet(apiAccessToken);

                if (string.IsNullOrEmpty(apiAccessTokenResult.access_token))
                {
                    LogUtil.Info(string.Format("获取微信AccessToken,key:{0},已过期,Api重新获取失败", key));
                }
                else
                {
                    LogUtil.Info(string.Format("获取微信AccessToken,key:{0},value:{1},已过期,重新获取成功", key, apiAccessTokenResult.access_token));

                    accessToken = apiAccessTokenResult.access_token;

                    redis.KSet(key, accessToken, new TimeSpan(0, 30, 0));
                }
            }
            else
            {
                LogUtil.Info(string.Format("获取微信AccessToken,key:{0},value:{1}", key, accessToken));
            }

            return(accessToken);
        }
Exemple #11
0
        public UnifiedOrderResult UnifiedOrderByNative(WxAppInfoConfig config, string merchantId, string orderSn, decimal orderAmount, string goods_tag, string ip, string body, DateTime time_expire)
        {
            var ret = new UnifiedOrderResult();

            TenpayUtil tenpayUtil = new TenpayUtil(config);

            UnifiedOrder unifiedOrder = new UnifiedOrder();

            unifiedOrder.openid           = "";
            unifiedOrder.out_trade_no     = orderSn;                            //商户订单号
            unifiedOrder.spbill_create_ip = ip;                                 //终端IP
            unifiedOrder.total_fee        = Convert.ToInt32(orderAmount * 100); //标价金额
            unifiedOrder.body             = body;                               //商品描述
            unifiedOrder.trade_type       = "NATIVE";
            unifiedOrder.time_expire      = time_expire.ToString("yyyyMMddHHmmss");
            unifiedOrder.goods_tag        = goods_tag;
            unifiedOrder.attach           = "{\"merchantId\":\"" + merchantId + "\"}";
            ret = tenpayUtil.UnifiedOrder(unifiedOrder);

            return(ret);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="config"></param>
        /// <param name="out_trade_no">商户内部的订单号</param>
        public TenpayOrderPayReFundApi(WxAppInfoConfig config, string out_trade_no, string out_refund_no, string total_fee, string refund_fee, string refund_desc)
        {
            SortedDictionary <string, object> sParams = new SortedDictionary <string, object>();

            sParams.Add("appid", config.AppId);                 //公众账号ID
            sParams.Add("mch_id", config.PayMchId);             //商户号
            sParams.Add("nonce_str", CommonUtil.GetNonceStr()); //随机字符串
            sParams.Add("out_trade_no", out_trade_no);          //微信订单号



            sParams.Add("total_fee", int.Parse(total_fee));   //订单总金额
            sParams.Add("refund_fee", int.Parse(refund_fee)); //退款金额
            sParams.Add("out_refund_no", out_refund_no);      //随机生成商户退款单号
            sParams.Add("refund_desc", refund_desc);          //退款原因

            string sign = MakeSign(sParams, config.PayKey);

            sParams.Add("sign", sign);//签名

            _postData = GetXml(sParams);
        }
Exemple #13
0
        public string GetJsApiTicket(WxAppInfoConfig config)
        {
            string key = string.Format("Wx_AppId_{0}_JsApiTicket", config.AppId);

            var redis       = new RedisClient <string>();
            var jsApiTicket = redis.KGetString(key);

            if (jsApiTicket == null)
            {
                WxApi c = new WxApi();

                string access_token = GetApiAccessToken(config);

                var wxApiJsApiTicket = new WxApiJsApiTicket(access_token);

                var wxApiJsApiTicketResult = c.DoGet(wxApiJsApiTicket);
                if (string.IsNullOrEmpty(wxApiJsApiTicketResult.ticket))
                {
                    LogUtil.Info(string.Format("获取微信JsApiTicket,key:{0},已过期,Api重新获取失败", key));
                }
                else
                {
                    LogUtil.Info(string.Format("获取微信JsApiTicket,key:{0},value:{1},已过期,重新获取成功", key, wxApiJsApiTicketResult.ticket));

                    jsApiTicket = wxApiJsApiTicketResult.ticket;

                    redis.KSet(key, jsApiTicket, new TimeSpan(0, 30, 0));
                }
            }
            else
            {
                LogUtil.Info(string.Format("获取微信JsApiTicket,key:{0},value:{1}", key, jsApiTicket));
            }

            return(jsApiTicket);
        }
Exemple #14
0
        public CustomJsonResult LoginByMinProgram(RopOwnLoginByMinProgram rop)
        {
            var result = new CustomJsonResult();
            var ret    = new RetOwnLoginByMinProgram();

            var merch = CurrentDb.Merch.Where(m => m.Id == rop.MerchId && m.WxMpAppId == rop.AppId).FirstOrDefault();

            if (merch == null)
            {
                return(new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "商户信息认证失败"));
            }

            var wxAppInfoConfig = new WxAppInfoConfig();

            wxAppInfoConfig.AppId               = merch.WxMpAppId;
            wxAppInfoConfig.AppSecret           = merch.WxMpAppSecret;
            wxAppInfoConfig.PayMchId            = merch.WxPayMchId;
            wxAppInfoConfig.PayKey              = merch.WxPayKey;
            wxAppInfoConfig.PayResultNotifyUrl  = merch.WxPayResultNotifyUrl;
            wxAppInfoConfig.NotifyEventUrlToken = merch.WxPaNotifyEventUrlToken;


            var wxUserInfoByMinProram = SdkFactory.Wx.GetUserInfoByMinProramJsCode(wxAppInfoConfig, rop.EncryptedData, rop.Iv, rop.Code);

            if (wxUserInfoByMinProram == null)
            {
                return(new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "获取微信用户信息失败"));
            }

            var wxUserInfo = CurrentDb.WxUserInfo.Where(m => m.OpenId == wxUserInfoByMinProram.openId).FirstOrDefault();

            if (wxUserInfo == null)
            {
                string sysClientUserId = GuidUtil.New();

                var sysClientUser = new SysClientUser();

                sysClientUser.Id            = sysClientUserId;
                sysClientUser.UserName      = string.Format("wx{0}", Guid.NewGuid().ToString().Replace("-", ""));
                sysClientUser.PasswordHash  = PassWordHelper.HashPassword("888888");
                sysClientUser.SecurityStamp = Guid.NewGuid().ToString();
                sysClientUser.RegisterTime  = DateTime.Now;
                sysClientUser.Nickname      = wxUserInfoByMinProram.nickName;
                sysClientUser.Sex           = wxUserInfoByMinProram.gender;
                sysClientUser.Province      = wxUserInfoByMinProram.province;
                sysClientUser.City          = wxUserInfoByMinProram.city;
                sysClientUser.Country       = wxUserInfoByMinProram.country;
                sysClientUser.Avatar        = wxUserInfoByMinProram.avatarUrl;
                sysClientUser.IsVip         = false;
                sysClientUser.CreateTime    = DateTime.Now;
                sysClientUser.Creator       = sysClientUserId;
                sysClientUser.BelongSite    = Enumeration.BelongSite.Client;
                CurrentDb.SysClientUser.Add(sysClientUser);
                CurrentDb.SaveChanges();

                wxUserInfo              = new WxUserInfo();
                wxUserInfo.Id           = GuidUtil.New();
                wxUserInfo.MerchId      = rop.MerchId;
                wxUserInfo.AppId        = rop.AppId;
                wxUserInfo.ClientUserId = sysClientUser.Id;
                wxUserInfo.OpenId       = wxUserInfoByMinProram.openId;
                wxUserInfo.CreateTime   = DateTime.Now;
                wxUserInfo.Creator      = sysClientUserId;
                CurrentDb.WxUserInfo.Add(wxUserInfo);
                CurrentDb.SaveChanges();
            }
            else
            {
                var sysClientUser = CurrentDb.SysClientUser.Where(m => m.Id == wxUserInfo.ClientUserId).FirstOrDefault();
                if (sysClientUser != null)
                {
                    sysClientUser.Nickname = wxUserInfoByMinProram.nickName;
                    sysClientUser.Sex      = wxUserInfoByMinProram.gender;
                    sysClientUser.Province = wxUserInfoByMinProram.province;
                    sysClientUser.City     = wxUserInfoByMinProram.city;
                    sysClientUser.Country  = wxUserInfoByMinProram.country;
                    sysClientUser.Avatar   = wxUserInfoByMinProram.avatarUrl;
                }
                CurrentDb.SaveChanges();
            }

            var tokenInfo = new TokenInfo();

            ret.Token        = GuidUtil.New();
            tokenInfo.UserId = wxUserInfo.ClientUserId;

            SSOUtil.SetTokenInfo(ret.Token, tokenInfo, new TimeSpan(1, 0, 0));

            result = new CustomJsonResult(ResultType.Success, ResultCode.Success, "登录成功", ret);

            return(result);
        }
Exemple #15
0
        public CustomJsonResult JsApiPaymentPms(string operater, string clientUserId, RupOrderJsApiPaymentPms rup)
        {
            var result = new CustomJsonResult();

            var wxUserInfo = CurrentDb.WxUserInfo.Where(m => m.ClientUserId == clientUserId).FirstOrDefault();

            if (wxUserInfo == null)
            {
                return(new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "找不到该用户数据"));
            }

            var order = CurrentDb.Order.Where(m => m.Id == rup.OrderId).FirstOrDefault();

            if (order == null)
            {
                return(new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "找不到该订单数据"));
            }

            LogUtil.Info("MerchId:" + order.MerchId);
            LogUtil.Info("WxMpAppId:" + rup.AppId);
            var merch = CurrentDb.Merch.Where(m => m.Id == order.MerchId && m.WxMpAppId == rup.AppId).FirstOrDefault();

            if (merch == null)
            {
                return(new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "商户信息认证失败"));
            }

            var wxAppInfoConfig = new WxAppInfoConfig();

            wxAppInfoConfig.AppId               = merch.WxMpAppId;
            wxAppInfoConfig.AppSecret           = merch.WxMpAppSecret;
            wxAppInfoConfig.PayMchId            = merch.WxPayMchId;
            wxAppInfoConfig.PayKey              = merch.WxPayKey;
            wxAppInfoConfig.PayResultNotifyUrl  = merch.WxPayResultNotifyUrl;
            wxAppInfoConfig.NotifyEventUrlToken = merch.WxPaNotifyEventUrlToken;


            order.AppId         = merch.WxMpAppId;
            order.ClientUserId  = wxUserInfo.ClientUserId;
            order.PayExpireTime = DateTime.Now.AddMinutes(5);

            switch (rup.PayWay)
            {
            case PayWay.AliPay:
                order.PayWay = E_OrderPayWay.AliPay;
                break;

            case PayWay.Wechat:
                order.PayWay = E_OrderPayWay.Wechat;


                var ret_UnifiedOrder = SdkFactory.Wx.UnifiedOrderByJsApi(wxAppInfoConfig, wxUserInfo.OpenId, order.Sn, 0.01m, "", Lumos.CommonUtil.GetIP(), "自助商品", order.PayExpireTime.Value);

                if (string.IsNullOrEmpty(ret_UnifiedOrder.PrepayId))
                {
                    return(new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "支付二维码生成失败"));
                }
                order.PayPrepayId  = ret_UnifiedOrder.PrepayId;
                order.PayQrCodeUrl = ret_UnifiedOrder.CodeUrl;
                CurrentDb.SaveChanges();

                //Task4Factory.Global.Enter(TimerTaskType.CheckOrderPay, order.PayExpireTime.Value, order);

                var pms = SdkFactory.Wx.GetJsApiPayParams(wxAppInfoConfig, order.Id, order.Sn, ret_UnifiedOrder.PrepayId);

                result = new CustomJsonResult(ResultType.Success, ResultCode.Success, "操作成功", pms);
                break;
            }



            //JsApiPayParams parms = new JsApiPayParams("wxb01e0e16d57bd762", "37b016a9569e4f519702696e1274d63a", ret_UnifiedOrder.PrepayId, order.Id, order.Sn);

            //return new CustomJsonResult(ResultType.Success, ResultCode.Success, "", ret.Data);

            return(result);
        }
Exemple #16
0
 public TenpayUtil(WxAppInfoConfig config)
 {
     this._config = config;
 }
Exemple #17
0
 public string GetWebAuthorizeUrl(WxAppInfoConfig config, string returnUrl)
 {
     return(OAuthApi.GetAuthorizeUrl(config.AppId, config.Oauth2RedirectUrl + "?returnUrl=" + returnUrl));
 }
Exemple #18
0
 public WxApiSnsOauth2AccessTokenResult GetWebOauth2AccessToken(WxAppInfoConfig config, string code)
 {
     return(OAuthApi.GetWebOauth2AccessToken(config.AppId, config.AppSecret, code));
 }
Exemple #19
0
 public string UploadMultimediaImage(WxAppInfoConfig config, string imageUrl)
 {
     return(OAuthApi.UploadMultimediaImage(this.GetApiAccessToken(config), imageUrl));
 }
Exemple #20
0
 public string GetNotifyEventUrlToken(WxAppInfoConfig config)
 {
     return(config.NotifyEventUrlToken);
 }
Exemple #21
0
        public JsApiPayParams GetJsApiPayParams(WxAppInfoConfig config, string orderId, string orderSn, string prepayId)
        {
            JsApiPayParams parms = new JsApiPayParams(config.AppId, config.PayKey, prepayId, orderId, orderSn);

            return(parms);
        }
Exemple #22
0
 public WxApiUserInfoResult GetUserInfoByApiToken(WxAppInfoConfig config, string openId)
 {
     return(OAuthApi.GetUserInfoByApiToken(this.GetApiAccessToken(config), openId));
 }
Exemple #23
0
 public string CardCodeDecrypt(WxAppInfoConfig config, string encrypt_code)
 {
     return(OAuthApi.CardCodeDecrypt(this.GetApiAccessToken(config), encrypt_code));
 }