public void Pay(Payload payload, ClientIndentification client, Boolean goLive, string merchantAccount,
                        decimal amount, String currencyCode, Int32 orderID)
        {
            if (String.IsNullOrEmpty(merchantAccount))
            {
                throw new Exception("Please specify receiver email for paypal.");
            }

            GoLive = goLive;

            //The pay key is valid for 3 hours; the payment must be approved while the pay key is valid.
            //check order payment status, is there already has a payment record waiting buyer approve??
            var orderToken = Services.Current.DataConext.
                             Payment_Paypal_OrderTokens.Where(o => o.OrderID == orderID).OrderByDescending(o => o.Id).FirstOrDefault();

            if (orderToken != null && (DateTime.Now - orderToken.CreateTime).TotalHours <= 3) //waiting for approve
            {
                HttpContext.Current.Response.Redirect(RedirectURL + orderToken.PayKey);
                return;
            }

            Guid orderTrackToken = Guid.NewGuid();

            var objectWebRequest = (HttpWebRequest)WebRequest.Create(EndpointURL);

            objectWebRequest.Method      = "POST";
            objectWebRequest.ContentType = "application/x-www-form-urlencoded";

            objectWebRequest.Headers.Set("X-PAYPAL-SECURITY-USERID", this.Authentication.X_PAYPAL_SECURITY_USERID);
            objectWebRequest.Headers.Set("X-PAYPAL-SECURITY-PASSWORD", this.Authentication.X_PAYPAL_SECURITY_PASSWORD);
            objectWebRequest.Headers.Set("X-PAYPAL-SECURITY-SIGNATURE", this.Authentication.X_PAYPAL_SECURITY_SIGNATURE);

            objectWebRequest.Headers.Set("X-PAYPAL-REQUEST-DATA-FORMAT", payload.X_PAYPAL_REQUEST_DATA_FORMAT.ToString());
            objectWebRequest.Headers.Set("X-PAYPAL-RESPONSE-DATA-FORMAT", payload.X_PAYPAL_RESPONSE_DATA_FORMAT.ToString());
            objectWebRequest.Headers.Set("X-PAYPAL-APPLICATION-ID", client.X_PAYPAL_APPLICATION_ID);

            StringBuilder reqBuilder = new StringBuilder();

            reqBuilder.AppendFormat("actionType={0}", HttpUtility.UrlEncode("PAY"));
            reqBuilder.AppendFormat("&feesPlayer={0}", HttpUtility.UrlEncode("EACHRECEIVER"));

            String cancelUrl = retrieveUrl("PayPal_Cancel", new RouteValueDictionary(new { token = orderTrackToken.ToString("N") }));

            reqBuilder.AppendFormat("&cancelUrl={0}", HttpUtility.UrlEncode(cancelUrl));
            reqBuilder.AppendFormat("&clientDetails.ipAddress={0}", HttpUtility.UrlEncode(HttpContext.Current.Request.UserHostAddress));
            reqBuilder.AppendFormat("&clientDetails.partnerName={0}", HttpUtility.UrlEncode("Koobo Commerce"));

            String ipnUrl = retrieveUrl("PayPal_IPN", new RouteValueDictionary(new { token = orderTrackToken.ToString("N") }));

            reqBuilder.AppendFormat("&ipnNotificationUrl=" + HttpUtility.UrlEncode(ipnUrl));

            reqBuilder.AppendFormat("&trackingId={0}", orderTrackToken.ToString("N"));
            reqBuilder.AppendFormat("&currencyCode={0}", HttpUtility.UrlEncode(currencyCode));
            reqBuilder.AppendFormat("&receiverList.receiver(0).email={0}", HttpUtility.UrlEncode(merchantAccount));
            reqBuilder.AppendFormat("&receiverList.receiver(0).amount={0}", HttpUtility.UrlEncode(amount.ToString()));
            reqBuilder.Append("&requestEnvelope.errorLanguage=en_US");   //requestEnvelope.errorLanguage must be en_US
            reqBuilder.Append("&requestEnvelope.detailLevel=ReturnAll"); //ReturnAll – This value provides the maximum level of detail (default)

            String returnUrl = retrieveUrl("PayPal_Return", new RouteValueDictionary(new { token = orderTrackToken.ToString("N") }));

            reqBuilder.AppendFormat("&returnUrl={0}", HttpUtility.UrlEncode(returnUrl));

            //Create a byte array of the data we want to send
            var byteData = UTF8Encoding.UTF8.GetBytes(reqBuilder.ToString());

            //Set the content length in the request headers
            objectWebRequest.ContentLength = byteData.Length;

            //Write data
            Stream postStream = null;

            postStream = objectWebRequest.GetRequestStream();

            postStream.Write(byteData, 0, byteData.Length);

            //Sent request / get response from server
            HttpWebResponse response = (HttpWebResponse)objectWebRequest.GetResponse();

            //Get response stream into a reader
            StreamReader reader = new StreamReader(response.GetResponseStream());

            //Read received response into a string array
            var strResponse = reader.ReadToEnd();

            //Split
            var strSplited = strResponse.Split('&');

            //Output
            string strOutput = "";

            foreach (var s in strSplited)
            {
                if (string.IsNullOrWhiteSpace(s) == false && s.Length > 0)
                {
                    strOutput = strOutput + s + "<br />";
                }
            }

            //Output to HTML
            // ResultDump.Text = "<br /><b>Printing received response:</b><br />" & strOutput

            //----------------------------------------------------------------------
            //'Do check if sucess and assign redirect string value
            //'----------------------------------------------------------------------
            String strPayKey, strPaymentExecStatus;
            String strTmp = strSplited[1];

            strTmp = strTmp.Substring(21, 7);

            if (strTmp == "Success")
            {
                //Get PayKey
                strPayKey = strSplited[4];
                strPayKey = strPayKey.Substring(7, 20);

                //Get PaymentExecStatus
                strPaymentExecStatus = strSplited[5].Substring(18);

                //Save Payment statue
                var newOrderToken = new Payment_Paypal_OrderToken()
                {
                    OrderID         = orderID,
                    OrderTraceToken = orderTrackToken,
                    CreateTime      = DateTime.Now,
                    PayKey          = strPayKey,
                    ExecStatus      = (byte)(PaymentStatus)Enum.Parse(typeof(PaymentStatus), strPaymentExecStatus, true)
                };
                Services.Current.DataConext.Payment_Paypal_OrderTokens.InsertOnSubmit(newOrderToken);
                Services.Current.DataConext.SubmitChanges();

                //update order status
                //var host = new ServiceHost();
                //IOrder order = host
                //      .QueryOrders()
                //      .Where(i => i.Id == orderID)
                //      .FirstOrDefault();
                //if (order != null)
                //{
                //order.OrderStatus = OrderStatus.PaymentPending;
                //host.Put(order);
                // }

                HttpContext.Current.Response.Redirect(RedirectURL + strPayKey);

                //Print redirect URL to HTML page
                //RedirectUrl.Text = "<br /><b>Please redirect user to following URL:</b><br />" & strRedirectURL
            }
            else //error handler
            {
                var           errors     = ParseError(strOutput.Replace("<br />", "&"));
                StringBuilder msgBuilder = new StringBuilder();
                foreach (var item in errors)
                {
                    msgBuilder.Append(item.Message);
                    msgBuilder.Append(HttpUtility.UrlEncode("\r"));
                }
                throw new Exception(msgBuilder.ToString());
            }
        }
Example #2
0
        public void Pay(Payload payload, ClientIndentification client, Boolean goLive, string merchantAccount,
            decimal amount, String currencyCode, Int32 orderID)
        {
            if (String.IsNullOrEmpty(merchantAccount))
            {
                throw new Exception("Please specify receiver email for paypal.");
            }

            GoLive = goLive;

            //The pay key is valid for 3 hours; the payment must be approved while the pay key is valid.
            //check order payment status, is there already has a payment record waiting buyer approve??
            var orderToken = Services.Current.DataConext.
                    Payment_Paypal_OrderTokens.Where(o => o.OrderID == orderID).OrderByDescending(o => o.Id).FirstOrDefault();
            if (orderToken != null && (DateTime.Now - orderToken.CreateTime).TotalHours <= 3) //waiting for approve
            {
                HttpContext.Current.Response.Redirect(RedirectURL + orderToken.PayKey);
                return;
            }

            Guid orderTrackToken = Guid.NewGuid();

            var objectWebRequest = (HttpWebRequest)WebRequest.Create(EndpointURL);

            objectWebRequest.Method = "POST";
            objectWebRequest.ContentType = "application/x-www-form-urlencoded";

            objectWebRequest.Headers.Set("X-PAYPAL-SECURITY-USERID", this.Authentication.X_PAYPAL_SECURITY_USERID);
            objectWebRequest.Headers.Set("X-PAYPAL-SECURITY-PASSWORD", this.Authentication.X_PAYPAL_SECURITY_PASSWORD);
            objectWebRequest.Headers.Set("X-PAYPAL-SECURITY-SIGNATURE", this.Authentication.X_PAYPAL_SECURITY_SIGNATURE);

            objectWebRequest.Headers.Set("X-PAYPAL-REQUEST-DATA-FORMAT", payload.X_PAYPAL_REQUEST_DATA_FORMAT.ToString());
            objectWebRequest.Headers.Set("X-PAYPAL-RESPONSE-DATA-FORMAT", payload.X_PAYPAL_RESPONSE_DATA_FORMAT.ToString());
            objectWebRequest.Headers.Set("X-PAYPAL-APPLICATION-ID", client.X_PAYPAL_APPLICATION_ID);

            StringBuilder reqBuilder = new StringBuilder();
            reqBuilder.AppendFormat("actionType={0}", HttpUtility.UrlEncode("PAY"));
            reqBuilder.AppendFormat("&feesPlayer={0}", HttpUtility.UrlEncode("EACHRECEIVER"));

            String cancelUrl = retrieveUrl("PayPal_Cancel", new RouteValueDictionary(new { token = orderTrackToken.ToString("N") }));
            reqBuilder.AppendFormat("&cancelUrl={0}", HttpUtility.UrlEncode(cancelUrl));
            reqBuilder.AppendFormat("&clientDetails.ipAddress={0}", HttpUtility.UrlEncode(HttpContext.Current.Request.UserHostAddress));
            reqBuilder.AppendFormat("&clientDetails.partnerName={0}", HttpUtility.UrlEncode("Koobo Commerce"));

            String ipnUrl = retrieveUrl("PayPal_IPN", new RouteValueDictionary(new { token = orderTrackToken.ToString("N") }));
            reqBuilder.AppendFormat("&ipnNotificationUrl=" + HttpUtility.UrlEncode(ipnUrl));

            reqBuilder.AppendFormat("&trackingId={0}", orderTrackToken.ToString("N"));
            reqBuilder.AppendFormat("&currencyCode={0}", HttpUtility.UrlEncode(currencyCode));
            reqBuilder.AppendFormat("&receiverList.receiver(0).email={0}", HttpUtility.UrlEncode(merchantAccount));
            reqBuilder.AppendFormat("&receiverList.receiver(0).amount={0}", HttpUtility.UrlEncode(amount.ToString()));
            reqBuilder.Append("&requestEnvelope.errorLanguage=en_US");//requestEnvelope.errorLanguage must be en_US
            reqBuilder.Append("&requestEnvelope.detailLevel=ReturnAll"); //ReturnAll – This value provides the maximum level of detail (default)

            String returnUrl = retrieveUrl("PayPal_Return", new RouteValueDictionary(new { token = orderTrackToken.ToString("N") }));
            reqBuilder.AppendFormat("&returnUrl={0}", HttpUtility.UrlEncode(returnUrl));

            //Create a byte array of the data we want to send
            var byteData = UTF8Encoding.UTF8.GetBytes(reqBuilder.ToString());

            //Set the content length in the request headers
            objectWebRequest.ContentLength = byteData.Length;

            //Write data
            Stream postStream = null;

            postStream = objectWebRequest.GetRequestStream();

            postStream.Write(byteData, 0, byteData.Length);

            //Sent request / get response from server
            HttpWebResponse response = (HttpWebResponse)objectWebRequest.GetResponse();

            //Get response stream into a reader
            StreamReader reader = new StreamReader(response.GetResponseStream());

            //Read received response into a string array
            var strResponse = reader.ReadToEnd();

            //Split
            var strSplited = strResponse.Split('&');

            //Output
            string strOutput = "";

            foreach (var s in strSplited)
            {
                if (string.IsNullOrWhiteSpace(s) == false && s.Length > 0)
                {
                    strOutput = strOutput + s + "<br />";
                }
            }

            //Output to HTML
            // ResultDump.Text = "<br /><b>Printing received response:</b><br />" & strOutput

            //----------------------------------------------------------------------
            //'Do check if sucess and assign redirect string value
            //'----------------------------------------------------------------------
            String strPayKey, strPaymentExecStatus;
            String strTmp = strSplited[1];
            strTmp = strTmp.Substring(21, 7);

            if (strTmp == "Success")
            {
                //Get PayKey
                strPayKey = strSplited[4];
                strPayKey = strPayKey.Substring(7, 20);

                //Get PaymentExecStatus
                strPaymentExecStatus = strSplited[5].Substring(18);

                //Save Payment statue
                var newOrderToken = new Payment_Paypal_OrderToken()
                {
                    OrderID = orderID,
                    OrderTraceToken = orderTrackToken,
                    CreateTime = DateTime.Now,
                    PayKey = strPayKey,
                    ExecStatus = (byte)(PaymentStatus)Enum.Parse(typeof(PaymentStatus), strPaymentExecStatus, true)
                };
                Services.Current.DataConext.Payment_Paypal_OrderTokens.InsertOnSubmit(newOrderToken);
                Services.Current.DataConext.SubmitChanges();

                //update order status
                //var host = new ServiceHost();
                //IOrder order = host
                //      .QueryOrders()
                //      .Where(i => i.Id == orderID)
                //      .FirstOrDefault();
                //if (order != null)
                //{
                //order.OrderStatus = OrderStatus.PaymentPending;
                //host.Put(order);
                // }

                HttpContext.Current.Response.Redirect(RedirectURL + strPayKey);

                //Print redirect URL to HTML page
                //RedirectUrl.Text = "<br /><b>Please redirect user to following URL:</b><br />" & strRedirectURL
            }
            else //error handler
            {
                var errors = ParseError(strOutput.Replace("<br />", "&"));
                StringBuilder msgBuilder = new StringBuilder();
                foreach (var item in errors)
                {
                    msgBuilder.Append(item.Message);
                    msgBuilder.Append(HttpUtility.UrlEncode("\r"));
                }
                throw new Exception(msgBuilder.ToString());
            }
        }