Exemplo n.º 1
0
 public static JSAPITicket GetJSAPITicket(WeChatPayConfig config,AccessToken oldToken,JSAPITicket oldTicket, out bool changed)
 {
     changed = false;
     JSAPITicket ticket = null;
     bool needGet = false;
     JSAPITicketRequest request = null;
     if(oldTicket==null)
     {
         needGet = true;
     }
     else
     {
         if(oldTicket.ExpiresTime<DateTime.Now)
         {
             needGet = true;
         }
     }
     if(needGet)
     {
         changed = true;
         bool tChanged = false;
         request = new JSAPITicketRequest(config);
         AccessToken token = WeChatPaymentWrapper.GetWeChatToken(config,oldToken,out tChanged);
         request.Access_Token = token;
         BaseResponse res = request.Execute();
         if(res!=null)
         {
             JSAPITicketResponse jsRes = (JSAPITicketResponse)res;
             ticket = jsRes.Ticket;
         }
     }
     return ticket;
 }
Exemplo n.º 2
0
        public static AccessToken GetWeChatToken(WeChatPayConfig config, AccessToken oldToken,out bool changed)
        {
            changed = false;
            AccessToken token = null;
            TokenRequest request = null;
            bool needGet = false;
            if (oldToken==null)
            {
                needGet = true;
            }
            else
            {
                if(oldToken.ExpiresTime<DateTime.Now)
                {
                    needGet = true;
                }
            }

            if(needGet)
            {
                request = new TokenRequest(config);
                BaseResponse res = request.Execute();
                if (res != null)
                {
                    changed = true;
                    AccessTokenResponse tokenRes = (AccessTokenResponse)res;
                    if (tokenRes.Access_Token != null)
                    {
                        token = tokenRes.Access_Token;
                        oldToken = token;
                    }
                }
            }
            return token;
        }
Exemplo n.º 3
0
 static PersistentValueManager()
 {
     KMLogger.GetLogger().Info(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config\\WeChatPayConfig.xml"));
     KMLogger.GetLogger().Info(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config\\WeChatAccessToken.xml"));
     KMLogger.GetLogger().Info(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config\\WeChatJSAPITicket.xml"));
     config = XMLUtil.DeserializeXML<WeChatPayConfig>(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config\\WeChatPayConfig.xml"));
     WeChatAccessToken = XMLUtil.DeserializeXML<AccessToken>(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config\\WeChatAccessToken.xml"));
     WeChatJsApiTicket= XMLUtil.DeserializeXML<JSAPITicket>(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Config\\WeChatJSAPITicket.xml"));
 }
Exemplo n.º 4
0
 public BaseRequest(WeChatPayConfig config)
 {
     logger = WeChatLogger.GetLogger();
     this.appid = config.APPID;
     this.secret = config.Secret;
     this.shop_secret = config.ShopSecret;
     this.mch_id = config.ShopID;
     this.signType = config.SignType.ToLower();
     this.nonce_str = Guid.NewGuid().ToString().Replace("-","");
     if(nonce_str.Length>32)
     {
         nonce_str = nonce_str.Substring(0,32);
     }
     ConfigVerification();
 }
Exemplo n.º 5
0
 public static AccessToken GetAccessToken(WeChatPayConfig config, string code)
 {
     if(string.IsNullOrEmpty(code))
     {
         throw new Exception("Authentication code must be provided");
     }
     AccessToken token = null;
     AuthAccessTokenRequest authRequest = new AuthAccessTokenRequest(config);
     authRequest.code = code;
     BaseResponse res = authRequest.Execute();
     if(res!=null)
     {
         token = ((AccessTokenResponse)res).Access_Token;
     }
     return token;
 }
Exemplo n.º 6
0
 public static WeChatUserInfo GetUserInfo(WeChatPayConfig config, AccessToken token)
 {
     if (token == null || string.IsNullOrEmpty(token.Access_Token) || string.IsNullOrEmpty(token.OpenId))
     {
         throw new Exception("Access token and open id must be provided");
     }
     UserInfoRequest userInfoRequest = new UserInfoRequest(config);
     userInfoRequest.AccessToken = token.Access_Token;
     userInfoRequest.OpenId = token.OpenId;
     BaseResponse res = userInfoRequest.Execute();
     UserInfoResponse response = null;
     if (res != null)
     {
         response = (UserInfoResponse)res;
     }
     return response.UserInfo;
 }
Exemplo n.º 7
0
        public static AccessToken GetAccessToken(WeChatPayConfig config, string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new Exception("Authentication code must be provided");
            }
            AccessToken            token       = null;
            AuthAccessTokenRequest authRequest = new AuthAccessTokenRequest(config);

            authRequest.code = code;
            BaseResponse res = authRequest.Execute();

            if (res != null)
            {
                token = ((AccessTokenResponse)res).Access_Token;
            }
            return(token);
        }
Exemplo n.º 8
0
 public static string GetPrepayId(WeChatPayConfig config,string openId,string out_trade_no,string body,string clientIp,int totalFee, TradeType type)
 {
     string prepayId = string.Empty;
     BaseResponse response = null;
     PreOrderRequest request = new PreOrderRequest(config);
     request.out_trade_no = out_trade_no;
     request.spbill_create_ip = clientIp;
     request.total_fee = totalFee;
     request.trade_type = type;
     request.body = body;
     request.detail = "";
     request.openid = openId;
     response = request.Execute();
     if(response!=null)
     {
         prepayId = ((PreOrderResponse)response).prepay_id;
     }
     return prepayId;
 }
Exemplo n.º 9
0
        public static WeChatUserInfo GetUserInfo(WeChatPayConfig config, AccessToken token)
        {
            if (token == null || string.IsNullOrEmpty(token.Access_Token) || string.IsNullOrEmpty(token.OpenId))
            {
                throw new Exception("Access token and open id must be provided");
            }
            UserInfoRequest userInfoRequest = new UserInfoRequest(config);

            userInfoRequest.AccessToken = token.Access_Token;
            userInfoRequest.OpenId      = token.OpenId;
            BaseResponse     res      = userInfoRequest.Execute();
            UserInfoResponse response = null;

            if (res != null)
            {
                response = (UserInfoResponse)res;
            }
            return(response.UserInfo);
        }
Exemplo n.º 10
0
        public string GetJsApiPaySign(WeChatPayConfig config, SortedDictionary<string,string> param)
        {
            string sign = null;

            return sign;
        }
Exemplo n.º 11
0
 public PreOrderRequest(WeChatPayConfig config) : base(config)
 {
     this.notify_url = config.NotifyUrl;
     this.url        = config.CreateOrderUrl;
 }
Exemplo n.º 12
0
 public PayOrderQueryRequest(WeChatPayConfig config) : base(config)
 {
     //this.url = "https://api.mch.weixin.qq.com/pay/orderquery";
     this.url = config.PaymentQueryUrl;
 }
Exemplo n.º 13
0
 public JSAPITicketRequest(WeChatPayConfig config) : base(config)
 {
     this.url = config.GetJsTicketUrl;
 }
Exemplo n.º 14
0
 public AuthAccessTokenRequest(WeChatPayConfig config) : base(config)
 {
     logger.Info("AuthAccessTokenRequest............................");
     this.url = config.GetAccessTokenUrl;
 }
Exemplo n.º 15
0
        public static string PostHttpRequest(string url, NameValueCollection col, RequestType type, string contentType, bool needCret = false, WeChatPayConfig config = null)
        {
            WeChatLogger.GetLogger().Info("PostHttpRequest.........");
            string       output = null;
            StreamReader rs     = null;

            try
            {
                if (needCret && config == null)
                {
                    throw new Exception("Please provides wechatpayconfig instance when need cert");
                }
                string json_str = string.Empty;
                var    client   = new HttpClient();
                if (needCret)
                {
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    WebRequestHandler handler = new WebRequestHandler();
                    System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                    X509Certificate cer = new X509Certificate(config.CertFilePath, config.ShopID);
                    WeChatLogger.GetLogger().Info("cert path:" + config.CertFilePath);
                    handler.ClientCertificates.Add(cer);
                    client = new HttpClient(handler);
                }

                if (!string.IsNullOrEmpty(contentType))
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                }
                WeChatLogger.GetLogger().Info("url:" + url);
                if (type == RequestType.POST)
                {
                    HttpContent content  = null;
                    var         postData = new List <KeyValuePair <string, string> >();
                    if (col != null && col.Count > 0)
                    {
                        IEnumerator myEnumerator = col.GetEnumerator();
                        if (contentType != null && contentType.ToLower() == "text/xml")
                        {
                            WeChatLogger.GetLogger().Info("post xml data...");
                            StringBuilder cBuilder = new StringBuilder();
                            cBuilder.Append("<xml>");
                            foreach (String s in col.AllKeys)
                            {
                                cBuilder.Append("<" + s + ">");
                                cBuilder.Append(col[s]);
                                cBuilder.Append("</" + s + ">");
                            }
                            cBuilder.Append("</xml>");
                            WeChatLogger.GetLogger().Info(cBuilder.ToString());
                            content = new StringContent(cBuilder.ToString());
                        }
                        else
                        {
                            foreach (String s in col.AllKeys)
                            {
                                if (s != null && col[s] != null)
                                {
                                    postData.Add(new KeyValuePair <string, string>(s, col[s]));
                                }
                            }

                            content = new FormUrlEncodedContent(postData);
                        }
                    }

                    var response = client.PostAsync(url, content).Result;

                    if (!response.IsSuccessStatusCode)
                    {
                        return(null);
                    }

                    Stream res = response.Content.ReadAsStreamAsync().Result;
                    //res = response.Content.ReadAsStreamAsync().Result;
                    if (contentType != "multipart/form-data")
                    {
                        rs     = new StreamReader(res);
                        output = rs.ReadToEnd();
                    }
                }
                else if (type == RequestType.GET)
                {
                    StringBuilder urlParms = new StringBuilder();
                    if (col != null)
                    {
                        IEnumerator myEnumerator = col.GetEnumerator();
                        int         count        = 1;
                        foreach (String s in col.AllKeys)
                        {
                            urlParms.Append(s);
                            urlParms.Append("=");
                            urlParms.Append(col[s]);
                            if (count < (col.Count))
                            {
                                urlParms.Append("&");
                            }

                            count++;
                        }
                    }
                    string getUrl = url;
                    if (!string.IsNullOrEmpty(urlParms.ToString()))
                    {
                        getUrl += "?" + urlParms.ToString();
                    }
                    var response = client.GetAsync(getUrl).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Stream res = response.Content.ReadAsStreamAsync().Result;
                        rs     = new StreamReader(res);
                        output = rs.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                WeChatLogger.GetLogger().Error(ex);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                if (rs != null)
                {
                    rs.Close();
                }
            }
            WeChatLogger.GetLogger().Info("Post request done.");
            return(output);
        }
Exemplo n.º 16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data">Data could be xml string, or json xml string, or could be key value pairs string</param>
        /// <param name="contentType"></param>
        /// <param name="type"></param>
        /// <param name="needCret"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static string PostHttpRequest(string url, string data, string contentType, RequestType type, bool needCret = false, WeChatPayConfig config = null)
        {
            WeChatLogger.GetLogger().Info("PostHttpRequest.........");
            string       output = null;
            StreamReader rs     = null;

            try
            {
                if (needCret && config == null)
                {
                    throw new Exception("Please provides wechatpayconfig instance when need cert");
                }
                string json_str = string.Empty;
                var    client   = new HttpClient();
                if (needCret)
                {
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    WebRequestHandler handler = new WebRequestHandler();
                    System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                    X509Certificate cer = new X509Certificate(config.CertFilePath, config.ShopID);
                    WeChatLogger.GetLogger().Info("cert path:" + config.CertFilePath);
                    handler.ClientCertificates.Add(cer);
                    client = new HttpClient(handler);
                }
                if (!string.IsNullOrEmpty(contentType))
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                }

                WeChatLogger.GetLogger().Info("url:" + url);
                if (type == RequestType.POST)
                {
                    HttpContent content = null;
                    content = new StringContent(data);
                    if (!string.IsNullOrEmpty(data))
                    {
                        WeChatLogger.GetLogger().Info("data:" + data);
                    }
                    var response = client.PostAsync(url, content).Result;
                    if (!response.IsSuccessStatusCode)
                    {
                        return(null);
                    }
                    Stream res = response.Content.ReadAsStreamAsync().Result;
                    //res = response.Content.ReadAsStreamAsync().Result;
                    if (contentType != "multipart/form-data")
                    {
                        rs     = new StreamReader(res);
                        output = rs.ReadToEnd();
                    }
                }
                else if (type == RequestType.GET)
                {
                    string getUrl = url;
                    if (!string.IsNullOrEmpty(data))
                    {
                        getUrl += "?" + data;
                    }
                    var response = client.GetAsync(getUrl).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Stream res = response.Content.ReadAsStreamAsync().Result;
                        rs     = new StreamReader(res);
                        output = rs.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                WeChatLogger.GetLogger().Error(ex);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                if (rs != null)
                {
                    rs.Close();
                }
            }
            WeChatLogger.GetLogger().Info("Post request done.");
            return(output);
        }
 public RefundNotificationMessage(WeChatPayConfig _config, AccessToken token) : base(_config, token)
 {
     template_id = "4xUtbva04CAlG-IjLg4ag_VIm51I7NGGjFJj7Qs_9Ak";
 }
Exemplo n.º 18
0
 public UserInfoRequest(WeChatPayConfig config) : base(config)
 {
     logger.Info(this.GetType().FullName);
     this.url = config.GetUserInfoUrl;
 }
Exemplo n.º 19
0
 public MiniAppMessageBase(WeChatPayConfig _config, AccessToken token) : base(_config, token)
 {
     this.apiUrl = config.MiniAppTemplateMessageUrl;
 }
Exemplo n.º 20
0
 public AuthAccessTokenRequest(WeChatPayConfig config)
     : base(config)
 {
     logger.Info("AuthAccessTokenRequest............................");
     this.url = config.GetAccessTokenUrl;
 }
Exemplo n.º 21
0
 public PayOrderQueryRequest(WeChatPayConfig config)
     : base(config)
 {
     //this.url = "https://api.mch.weixin.qq.com/pay/orderquery";
     this.url = config.PaymentQueryUrl;
 }
 public OrderStatusChangeMsg(WeChatPayConfig _config, AccessToken token) : base(_config, token)
 {
     template_id = "RsP_3nVu7U1HLF1I01rTdIjFk8HAFJbuJSt4Jsbcs3k";
 }
Exemplo n.º 23
0
 public TokenRequest(WeChatPayConfig config) : base(config)
 {
     this.url = config.GetTokenUrl;
 }
Exemplo n.º 24
0
 public JSAPITicketRequest(WeChatPayConfig config)
     : base(config)
 {
     this.url = config.GetJsTicketUrl;
 }
Exemplo n.º 25
0
 public UserInfoRequest(WeChatPayConfig config)
     : base(config)
 {
     logger.Info(this.GetType().FullName);
     this.url = config.GetUserInfoUrl;
 }
 public CropCalculateMessage(WeChatPayConfig _config, AccessToken token) : base(_config, token)
 {
     template_id = "vKkNNORiSJ7jg1WusrJiZZ3iAKyvqc93C6WZ49kS9hQ";
 }
Exemplo n.º 27
0
 public PreOrderRequest(WeChatPayConfig config)
     : base(config)
 {
     this.notify_url = config.NotifyUrl;
     this.url = config.CreateOrderUrl;
 }
 public NormalNotificationMessage(WeChatPayConfig _config, AccessToken token) : base(_config, token)
 {
     template_id = "RsP_3nVu7U1HLF1I01rTdIjFk8HAFJbuJSt4Jsbcs3k";
 }
Exemplo n.º 29
0
 public TokenRequest(WeChatPayConfig config)
     : base(config)
 {
     this.url = config.GetTokenUrl;
 }
Exemplo n.º 30
0
        public HttpResponseMessage WeChatPayBack()
        {
            var    resp      = new HttpResponseMessage(HttpStatusCode.OK);
            string returnXML = null;

            logger.Info("PaymentController.WeChatPayBack is being called by Wechat payment notify service.........................");
            Stream stream = Request.InputStream;

            if (stream != null)
            {
                StreamReader rs = null;
                try
                {
                    rs = new StreamReader(stream);
                    string result = rs.ReadToEnd();
                    if (!string.IsNullOrEmpty(result))
                    {
                        logger.Info("Below is the data posted by wechat payment service");
                        logger.Info(result);
                        string paraValues = WeChatPaymentWrapper.ParsePaymentNotifySignParas(result);
                        logger.Info(string.Format("{0} needs to be signed", paraValues));
                        BaseResponse          baseresponse = WeChatPaymentWrapper.ParsePaymentNotify(result);
                        PaymentNotifyResponse response     = null;
                        if (baseresponse != null)
                        {
                            response = (PaymentNotifyResponse)baseresponse;
                        }
                        logger.Info(string.Format("Signature sent by wechat is {0}", response.sign));
                        WeChatPayConfig config = PersistentValueManager.config;
                        paraValues += "&key=" + config.ShopSecret;
                        string sign = UrlSignUtil.GetMD5(paraValues).ToUpper();
                        logger.Info(string.Format("Signature caculated by localsystem is {0}", sign));
                        if (sign != response.sign)
                        {
                            logger.Error("Two signatures are different, the request was not sent by wechat payment system.");
                            returnXML    = "<xml><return_code>FAIL</return_code><return_msg>签名不正确</return_msg></xml>";
                            resp.Content = new StringContent(returnXML, System.Text.Encoding.UTF8, "text/plain");
                        }
                        logger.Info("Sign verification passed");
                        OrderManagement   orderMgr = new OrderManagement(0);
                        PaymentManagement payMgr   = new PaymentManagement(0);
                        int paymentId = 0;
                        int.TryParse(response.out_trade_no, out paymentId);
                        if (paymentId > 0)
                        {
                            logger.Info("Going to process payment id" + paymentId);
                            ChargeResult cResult = null;
                            try
                            {
                                BPaymentHistory        payment  = null;
                                int                    total    = 0;
                                List <BPaymentHistory> payments = payMgr.FindUnProcessedOnLinePayments(paymentId, 0, 0, out total);
                                if (payments != null && payments.Count == 1)
                                {
                                    payment = payments[0];
                                    if (payment.PayType == 0)//直冲用户支付
                                    {
                                        logger.Info("OpenId:" + response.openid);
                                        logger.Info("OpenTradeNo:" + response.transaction_id);
                                        cResult = orderMgr.ProcessOrderAfterPaid(paymentId, response.transaction_id, response.openid);
                                        logger.Info(cResult.Status.ToString());
                                        logger.Info(cResult.Message);
                                        if (cResult.Status == ChargeStatus.SUCCEED)
                                        {
                                            logger.Info("The payment status has been successfully synced to local system.");
                                            returnXML    = "<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>";
                                            resp.Content = new StringContent(returnXML, System.Text.Encoding.UTF8, "text/plain");
                                            return(resp);
                                        }
                                        else
                                        {
                                            logger.Error(cResult.Message);
                                            returnXML    = "<xml><return_code>FAIL</return_code><return_msg>unexpected error</return_msg></xml>";
                                            resp.Content = new StringContent(returnXML, System.Text.Encoding.UTF8, "text/plain");
                                            return(resp);
                                        }
                                    }
                                }
                                else
                                {
                                    logger.Warn("Didn't find payment by id:" + paymentId);
                                    returnXML    = "<xml><return_code>FAIL</return_code><return_msg>out_trade_no is wrong</return_msg></xml>";
                                    resp.Content = new StringContent(returnXML, System.Text.Encoding.UTF8, "text/plain");
                                }
                            }
                            catch (KMBitException e)
                            {
                                returnXML    = "<xml><return_code>FAIL</return_code><return_msg>unexpected error</return_msg></xml>";
                                resp.Content = new StringContent(returnXML, System.Text.Encoding.UTF8, "text/plain");
                                logger.Error(e);
                            }
                            catch (Exception ex)
                            {
                                returnXML    = "<xml><return_code>FAIL</return_code><return_msg>unexpected error</return_msg></xml>";
                                resp.Content = new StringContent(returnXML, System.Text.Encoding.UTF8, "text/plain");
                                logger.Fatal(ex);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }
            }
            logger.Info("Done...................");
            return(resp);
        }