Example #1
0
        public string GetBalanceCode()
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment="sandbox";
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "51.0";
            encoder["METHOD"] =  "GetBalance";
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
        private string UrlConstructor(tbl_Orders order)
        {
            string   currencyCode = DomainService.GetSettingsValue(SettingsKey.secureTradingCurrencyCode, this.DomainID);
            NVPCodec encoder      = InitializeEncoder(order, currencyCode);

            return("https://payments.securetrading.net/process/payments/choice?" + encoder.Encode());
        }
        public string ECSetExpressCheckout_PayLaterCode(string returnURL,string cancelURL,string amount,string paymentType,string currencyCode)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment="sandbox";
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "51.0";
            encoder["METHOD"] =  "SetExpressCheckout";
            encoder["RETURNURL"] =  returnURL;
            encoder["CANCELURL"] =  cancelURL;
            encoder["AMT"] =  amount;
            encoder["PAYMENTACTION"] =  paymentType;
            encoder["CURRENCYCODE"] =  currencyCode;
            encoder["L_PROMOCODE0"] = "101";
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
    public bool DoCheckoutPayment(string finalPaymentAmount, string token, string PayerID, ref NVPCodec decoder, ref string retMsg)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
        }

        NVPCodec encoder = new NVPCodec();
        encoder["METHOD"] = "DoExpressCheckoutPayment";
        encoder["TOKEN"] = token;
        encoder["PAYERID"] = PayerID;
        encoder["PAYMENTREQUEST_0_AMT"] = finalPaymentAmount;
        encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD";
        encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall(pStrrequestforNvp);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();
        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            return true;
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                "Desc2=" + decoder["L_LONGMESSAGE0"];

            return false;
        }
    }
Example #5
0
        public PayPalResponse ECGetExpressCheckout(string token)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = getProfile();
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] = "84.0";
            encoder["METHOD"] = "GetExpressCheckoutDetails";

            // Add request-specific fields to the request.
            encoder["TOKEN"] = token; // Pass the token returned in SetExpressCheckout.

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp = caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            PayPalResponse response = new PayPalResponse {
                token = (decoder["TOKEN"] != null) ? decoder["TOKEN"] : "",
                acknowledgement = decoder["ACK"],
                first = decoder["FIRSTNAME"],
                last = decoder["LASTNAME"],
                email = decoder["EMAIL"],
                amount = decoder["PAYMENTREQUEST_0_AMT"],
                payerID = decoder["PAYERID"]
            };
            return response;
        }
    /// <summary>
    /// Call this method to complete payment.
    /// </summary>
    /// <param name="finalPaymentAmount"></param>
    /// <param name="token"></param>
    /// <param name="PayerID"></param>
    /// <param name="decoder"></param>
    /// <param name="retMsg"></param>
    /// <returns></returns>
    public bool DoCheckoutPayment(string finalPaymentAmount, string token, ref NVPCodec decoder)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
        }

        NVPCodec encoder = new NVPCodec();

        encoder[NVPProperties.Properties.METHOD]             = NVPProperties.Methods.ProcessPayment;
        encoder[NVPProperties.Properties.TOKEN]              = token;
        encoder[NVPProperties.Properties.PAYMENTREQUEST_AMT] = finalPaymentAmount;

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder[NVPProperties.Properties.ACK].ToLower();

        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Example #7
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (Request.QueryString["Code"].ToLower() == "Cancel".ToLower())
         {
             return;
         }
         else if (Request.QueryString["Code"].ToLower() == "Sucess".ToLower())
         {
             lblAppName.InnerHtml   = Session["AppName"].ToString();
             imgApp.Src             = Session["AppIcon"].ToString();
             lblValidationCode.Text = Session.SessionID;
             return;
         }
         else if (Request.QueryString["Code"].ToLower() == "Error".ToLower())
         {
             lblAppName.InnerHtml   = Session["AppIcon"].ToString();
             imgApp.Src             = Session["AppIcon"].ToString();
             lblValidationCode.Text = Session["errorresult"].ToString();
             return;
         }
         Session["AppName"] = Request.QueryString["AppName"].ToString();
         Session["AppIcon"] = Request.QueryString["AppIcon"].ToString();
         string url                   = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "";
         string cancelURL             = url + ResolveUrl("paypal.aspx") + "?Code=Cancel";
         string returnURL             = url + ResolveUrl("paypal.aspx") + "?Code=Sucess";
         ECSetExpressCheckout objset  = new ECSetExpressCheckout();
         NVPCodec             decoder = new NVPCodec();
         decoder = objset.ECSetExpressCheckoutCode(returnURL, Request.QueryString["AppName"].ToString(), System.Configuration.ConfigurationManager.AppSettings["AppCode"].ToString(), cancelURL, Request.QueryString["Price"].ToString(), "Sale", Request.QueryString["Currency"].ToString());
         string strAck = decoder["ACK"];
         if (strAck != null && (strAck == "Success" || strAck == "SuccessWithWarning"))
         {
             Session["TOKEN"] = decoder["TOKEN"];
             string host1 = "www." + ASPDotNetSamples.AspNet.Constants.ENVIRONMENT + ".paypal.com";
             //
             string ECURL = string.Empty;
             if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "T")
             {
                 ECURL = "https://" + host1 + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + decoder["TOKEN"];
             }
             else
             {
                 ECURL = "https://www.paypal.com/webscr?cmd=_express-checkout" + "&token=" + decoder["TOKEN"];
             }
             Response.Redirect(ECURL, false);
         }
         else
         {
             Session["errorresult"] = decoder;
             string pStrResQue = "API=" + ASPDotNetSamples.AspNet.Util.BuildResponse(decoder, "Set", "");
             Response.Redirect("paypal.aspx?Code=Error");
         }
     }
     catch (Exception ex)
     {
         Session["errorresult"] = "API=" + ex.Message;
         Response.Redirect("paypal.aspx?Code=Error");
     }
 }
        public string GetTransactionDetailsCode(string transactionID)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment="sandbox";
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "51.0";
            encoder["METHOD"] =  "GetTransactionDetails";

            // Add request-specific fields to the request.
            encoder["TRANSACTIONID"] =  transactionID;

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
Example #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Potvrda da je korisnik završio proces checkout
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCompleted"] = string.Empty;
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
                }

                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg             = "";
                string   token              = "";
                string   finalPaymentAmount = "";
                string   PayerID            = "";
                NVPCodec decoder            = new NVPCodec();

                token              = Session["token"].ToString();
                PayerID            = Session["payerId"].ToString();
                finalPaymentAmount = Session["payment_amt"].ToString();

                bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    // Retrieve PayPal confirmation value.
                    string paymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                    TransactionId.Text = paymentConfirmation;

                    ProductContext _db = new ProductContext();
                    // Get the current order id.
                    int currentOrderId = -1;
                    if (Session["currentOrderId"].ToString() != string.Empty)
                    {
                        currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                    }
                    Order myCurrentOrder;
                    if (currentOrderId >= 0)
                    {
                        // Get the order based on order id.
                        myCurrentOrder = _db.Orders.Single(o => o.OrderId == currentOrderId);
                        // Update the order to reflect payment has been completed.
                        myCurrentOrder.PaymentTransactionId = paymentConfirmation;
                        _db.SaveChanges();
                    }
                    // Clear shopping cart.
                    using (ProdavnicaIgracaka.Logic.ShoppingCartActions usersShoppingcart = new ProdavnicaIgracaka.Logic.ShoppingCartActions())
                    {
                        usersShoppingcart.EmptyCart();
                    }
                    // Clear order id.
                    Session["currentOrderid"] = string.Empty;
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
    public NVPCodec CancelAuthorization(string transactionID, string note)
    {
        NVPCallerServices caller = new NVPCallerServices();
        IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
        /*
         WARNING: Do not embed plaintext credentials in your application code.
         Doing so is insecure and against best practices.
         Your API credentials must be handled securely. Please consider
         encrypting them for use in any production environment, and ensure
         that only authorized individuals may view or modify them.
         */

        // Set up your API credentials, PayPal end point, API operation and version.
        caller.APIProfile = profile;

        NVPCodec encoder = new NVPCodec();
        encoder["VERSION"] = "51.0";
        encoder["METHOD"] = "DoVoid";

        // Add request-specific fields to the request.
        encoder["AUTHORIZATIONID"] = transactionID;
        encoder["NOTE"] = note;
        encoder["TRXTYPE"] = "V";

        // Execute the API operation and obtain the response.
        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = caller.Call(pStrrequestforNvp);

        NVPCodec decoder = new NVPCodec();
        return decoder;
    }
Example #11
0
        /// <summary>
        /// Refunds the payment from the payment provider. This is often used when you need to call external services to handle the refund process.
        /// </summary>
        /// <remarks>
        /// Docs at https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/RefundTransaction_API_Operation_NVP/
        /// </remarks>
        /// <param name="payment">The payment.</param>
        /// <param name="status">The status.</param>
        /// <returns></returns>
        protected override bool RefundPaymentInternal(Payment payment, out string status)
        {
            var caller = GetPayPalNVPCaller(payment.PaymentMethod);

            var postCodec = new NVPCodec();

            postCodec["VERSION"]       = "51.0";
            postCodec["METHOD"]        = "RefundTransaction";
            postCodec["TRANSACTIONID"] = payment.TransactionId;
            postCodec["REFUNDTYPE"]    = "Full";

            // Execute the API operation and obtain the response.
            string postString     = postCodec.Encode();
            string responseString = caller.Call(postString);

            var responseCodec = new NVPCodec();

            responseCodec.Decode(responseString);

            status = GetCodecStatus(responseCodec);
            bool callStatus = GetCallStatus(responseCodec);

            if (callStatus)
            {
                status = PaymentMessages.RefundSuccess + " >> " + status;
            }
            else
            {
                status = PaymentMessages.RefundFailed + " >> " + status;
            }

            return(callStatus);
        }
Example #12
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (Request.QueryString["Code"].ToLower() == "Cancel".ToLower())
         {
             return;
         }
         else if (Request.QueryString["Code"].ToLower() == "Sucess".ToLower())
         {
             lblAppName.InnerHtml = Session["AppName"].ToString();
             imgApp.Src = Session["AppIcon"].ToString();
             lblValidationCode.Text = Session.SessionID;
             return;
         }
         else if (Request.QueryString["Code"].ToLower() == "Error".ToLower())
         {
             lblAppName.InnerHtml = Session["AppIcon"].ToString();
             imgApp.Src = Session["AppIcon"].ToString();
             lblValidationCode.Text = Session["errorresult"].ToString();
             return;
         }
         Session["AppName"] = Request.QueryString["AppName"].ToString();
         Session["AppIcon"] = Request.QueryString["AppIcon"].ToString();
         string url = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "";
         string cancelURL = url + ResolveUrl("paypal.aspx") + "?Code=Cancel";
         string returnURL = url + ResolveUrl("paypal.aspx") + "?Code=Sucess";
         ECSetExpressCheckout objset = new ECSetExpressCheckout();
         NVPCodec decoder = new NVPCodec();
         decoder = objset.ECSetExpressCheckoutCode(returnURL, Request.QueryString["AppName"].ToString(), System.Configuration.ConfigurationManager.AppSettings["AppCode"].ToString(), cancelURL, Request.QueryString["Price"].ToString(), "Sale", Request.QueryString["Currency"].ToString());
         string strAck = decoder["ACK"];
         if (strAck != null && (strAck == "Success" || strAck == "SuccessWithWarning"))
         {
             Session["TOKEN"] = decoder["TOKEN"];
             string host1 = "www." + ASPDotNetSamples.AspNet.Constants.ENVIRONMENT + ".paypal.com";
             //
             string ECURL = string.Empty;
             if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "T")
             {
                 ECURL = "https://" + host1 + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + decoder["TOKEN"];
             }
             else
             {
                 ECURL = "https://www.paypal.com/webscr?cmd=_express-checkout" + "&token=" + decoder["TOKEN"];
             }
             Response.Redirect(ECURL, false);
         }
         else
         {
             Session["errorresult"] = decoder;
             string pStrResQue = "API=" + ASPDotNetSamples.AspNet.Util.BuildResponse(decoder, "Set", "");
             Response.Redirect("paypal.aspx?Code=Error");
         }
     }
     catch (Exception ex)
     {
         Session["errorresult"] = "API=" + ex.Message;
         Response.Redirect("paypal.aspx?Code=Error");
     }
 }
    public bool GetCheckoutDetails(string token, ref string PayerID, ref NVPCodec decoder, ref string retMsg)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
        }

        NVPCodec encoder = new NVPCodec();

        encoder["METHOD"] = "GetExpressCheckoutDetails";
        encoder["TOKEN"]  = token;

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();

        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            PayerID = decoder["PAYERID"];
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                     "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                     "Desc2=" + decoder["L_LONGMESSAGE0"];

            return(false);
        }
    }
Example #14
0
    public bool DoCheckoutPayment(string finalPaymentAmount, string token, string
                                  PayerID, ref NVPCodec decoder, ref string retMsg)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
        }
        NVPCodec encoder = new NVPCodec();

        encoder["METHOD"]  = "DoExpressCheckoutPayment";
        encoder["TOKEN"]   = token;
        encoder["PAYERID"] = PayerID;
        encoder["PAYMENTREQUEST_0_AMT"]           = finalPaymentAmount;
        encoder["PAYMENTREQUEST_0_CURRENCYCODE"]  = "USD";
        encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);
        string strAck = decoder["ACK"].ToLower();

        if (strAck != null && (strAck == "success" || strAck ==
                               "successwithwarning"))
        {
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                     "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                     "Desc2=" + decoder["L_LONGMESSAGE0"];
            return(false);
        }
    }
Example #15
0
    private string buildCredentialsNVPString()
    {
        NVPCodec codec = new NVPCodec();

        if (!IsEmpty(APIUsername))
        {
            codec["USER"] = APIUsername;
        }

        if (!IsEmpty(APIPassword))
        {
            codec[PWD] = APIPassword;
        }

        if (!IsEmpty(APISignature))
        {
            codec[SIGNATURE] = APISignature;
        }

        if (!IsEmpty(Subject))
        {
            codec["SUBJECT"] = Subject;
        }

        codec["VERSION"] = "88.0";

        return(codec.Encode());
    }
Example #16
0
    /// <summary>
    /// ShortcutExpressCheckout: The method that calls SetExpressCheckout API
    /// </summary>
    /// <param name="amt"></param>
    /// <param ref name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool ShortcutExpressCheckout(string netamt, string vatamt, string grossamt, string currencycode, ref string token, ref string retMsg, ref NVPCodec retdecoder, ref string payerid)
    {
        string host = "www.paypal.com";

        if (bSandbox)
        {
            pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
            host         = "www.sandbox.paypal.com";
        }

        string returnURL = ConfigurationManager.AppSettings["ReturnURL"].ToString();
        string cancelURL = ConfigurationManager.AppSettings["CancelURL"].ToString();

        NVPCodec encoder = new NVPCodec();

        encoder["METHOD"]        = "SetExpressCheckout";
        encoder["RETURNURL"]     = returnURL;
        encoder["CANCELURL"]     = cancelURL;
        encoder["AMT"]           = grossamt;
        encoder["PAYMENTACTION"] = "Sale";
        encoder["CURRENCYCODE"]  = currencycode;
        encoder["L_NAME0"]       = "GSE-Mart.aero Advert Payment ";
        encoder["L_AMT0"]        = netamt;
        encoder["ITEMAMT"]       = netamt;
        encoder["TAXAMT"]        = vatamt;

        //// Jim. Try explicitly putting these in!
        //encoder["USER"] = APIUsername;
        //encoder["PWD"] = APIPassword;
        //encoder["SIGNATURE"] = APISignature;

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        NVPCodec decoder = new NVPCodec();

        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();

        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            token = decoder["TOKEN"];

            // useraction = commit makes the user commit to the transaction in PayPal
            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token + "&useraction=commit";

            retMsg = ECURL;
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                     "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                     "Desc2=" + decoder["L_LONGMESSAGE0"];

            return(false);
        }
    }
        public NVPCodec ECSetExpressCheckoutCode(string returnURL, string appName,string appCode, string cancelURL, string appAMT, string paymentType, string currencyCode)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "T")
            {
                profile.APIUsername = "******";
                profile.APIPassword = "******";
                profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
                profile.Environment = "sandbox";
            }
            else if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "L")
            {

                profile.APIUsername = "******";
                profile.APIPassword = "******";
                profile.APISignature = "AFcWxV21C7fd0v3bYYYRCpSSRl31Ab5GxWPc-1XSb8rJctwNCFHIYb84";
                profile.Environment = "live";
            }
            else
            {
                profile.APIUsername = "******";
                profile.APIPassword = "******";
                profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
                profile.Environment = "sandbox";
            }
            caller.APIProfile = profile;
            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "65.1";
            encoder["METHOD"] =  "SetExpressCheckout";
            // Add request-specific fields to the request.
            encoder["RETURNURL"] =  returnURL;
            encoder["CANCELURL"] =  cancelURL;
            encoder["AMT"] = appAMT;
            encoder["ITEMCATEGORY"] = "Digital";
            encoder["L_NAME0"] = appName;
            encoder["L_NUMBER0"] = appCode;
            encoder["L_AMT0"] = appAMT;
            encoder["L_QTY0"] ="1";
            encoder["PAYMENTACTION"] =  paymentType;
            encoder["CURRENCYCODE"] =  currencyCode;
            encoder["SOLUTIONTYPE"] = "Sole";
            // Execute the API operation and obtain the response.
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder;
        }
Example #18
0
 public bool ShortcutExpressCheckout(string amt, ref string token, ref string 
retMsg) 
 { if (bSandbox)
 { 
 pEndPointURL = pEndPointURL_SB; 
 host = host_SB; 
 } 
 
 string returnURL = "http://localhost:1234/Checkout/CheckoutReview.aspx"; 
 string cancelURL = "http://localhost:1234/Checkout/CheckoutCancel.aspx"; 
 
 NVPCodec encoder = new NVPCodec(); 
 encoder["METHOD"] = "SetExpressCheckout"; 
 encoder["RETURNURL"] = returnURL; 
 encoder["CANCELURL"] = cancelURL; 
 encoder["BRANDNAME"] = "Wingtip Toys Sample Application"; 
 encoder["PAYMENTREQUEST_0_AMT"] = amt; 
 encoder["PAYMENTREQUEST_0_ITEMAMT"] = amt; 
 encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale"; 
 encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD"; 
 
 // Get the Shopping Cart Products 
 using (ClassiqWheels.Logic.ShoppingCartActions myCartOrders = new
ClassiqWheels.Logic.ShoppingCartActions()) 
 { 
 List<CartItem> myOrderList = myCartOrders.GetCartItems(); 
 
 for (int i = 0; i < myOrderList.Count; i++) 
 { 
 encoder["L_PAYMENTREQUEST_0_NAME" + i] = 
myOrderList[i].Product.ProductName.ToString(); 
 encoder["L_PAYMENTREQUEST_0_AMT" + i] = 
myOrderList[i].Product.UnitPrice.ToString(); 
 encoder["L_PAYMENTREQUEST_0_QTY" + i] = 
myOrderList[i].Quantity.ToString(); 
 } 
 } 
string pStrrequestforNvp = encoder.Encode(); 
 string pStresponsenvp = HttpCall(pStrrequestforNvp); 
 
 NVPCodec decoder = new NVPCodec(); 
 decoder.Decode(pStresponsenvp); 
 
 string strAck = decoder["ACK"].ToLower(); 
 if (strAck != null && (strAck == "success" || strAck == 
"successwithwarning")) 
 { 
 token = decoder["TOKEN"];
     string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout"+"&token="+ token;
     retMsg = ECURL; 
 return true; 
     } 
 else 
 { 
 retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" + 
 "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" + 
 "Desc2=" + decoder["L_LONGMESSAGE0"]; 
 return false; 
 } 
Example #19
0
    public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
            host         = host_SB;
        }

        string returnURL = "http://localhost:2911/Checkout/CheckoutReview.aspx";
        string cancelURL = "http://localhost:2911/Checkout/CheckoutCancel.aspx";

        NVPCodec encoder = new NVPCodec();

        encoder["METHOD"]                         = "SetExpressCheckout";
        encoder["RETURNURL"]                      = returnURL;
        encoder["CANCELURL"]                      = cancelURL;
        encoder["BRANDNAME"]                      = "BoozeSoothe Sample Application";
        encoder["PAYMENTREQUEST_0_AMT"]           = amt;
        encoder["PAYMENTREQUEST_0_ITEMAMT"]       = amt;
        encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
        encoder["PAYMENTREQUEST_0_CURRENCYCODE"]  = "USD";

        // Get the Shopping Cart Products
        using (BoozeSoothe.Logic.ShoppingCartActions myCartOrders = new BoozeSoothe.Logic.ShoppingCartActions())
        {
            List <CartItem> myOrderList = myCartOrders.GetCartItems();

            for (int i = 0; i < myOrderList.Count; i++)
            {
                encoder["L_PAYMENTREQUEST_0_NAME" + i] = myOrderList[i].Product.ProductName.ToString();
                encoder["L_PAYMENTREQUEST_0_AMT" + i]  = myOrderList[i].Product.UnitPrice.ToString();
                encoder["L_PAYMENTREQUEST_0_QTY" + i]  = myOrderList[i].Quantity.ToString();
            }
        }

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        NVPCodec decoder = new NVPCodec();

        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();

        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            token = decoder["TOKEN"];
            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
            retMsg = ECURL;
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                     "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                     "Desc2=" + decoder["L_LONGMESSAGE0"];
            return(false);
        }
    }
Example #20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                System.Diagnostics.Debug.Write("Session[\"userCheckoutCompleted\"]" + Session["userCheckoutCompleted"]);
                // Verify user has completed the checkout process.
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCompleted"] = string.Empty;
                    Response.Redirect("~/Checkout/CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
                }

                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg             = "";
                string   token              = "";
                string   finalPaymentAmount = "";
                string   PayerID            = "";
                NVPCodec decoder            = new NVPCodec();

                token   = Session["token"].ToString();
                PayerID = Session["payerId"].ToString();

                finalPaymentAmount = Session["TotalPrice"].ToString();

                bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);

                Console.WriteLine(retMsg);
                Console.WriteLine(finalPaymentAmount);

                if (ret)
                {
                    // Retrieve PayPal confirmation value.
                    string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                    TransactionId.Text = PaymentConfirmation;
                    //  lblTransactionNo.Text= "Your Order No :-" + dtResult.Rows[0][0];
                    OrderNo.Text = Session["OrderNo"].ToString();
                    // Get the current order id.
                    int currentOrderId = -1;

                    if (Session["currentOrderId"] != null)
                    {
                        currentOrderId = Convert.ToInt32(Session["currentOrderId"]);
                        if (currentOrderId >= 0)
                        {
                            ConnectionClass.UpdateOrderDetails(currentOrderId, PaymentConfirmation);
                        }
                    }


                    // Clear order id.
                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    Response.Redirect("~/Checkout/CheckoutError.aspx?" + retMsg);
                }
            }
        }
Example #21
0
    /// <summary>
    /// ShortcutExpressCheckout: The shortcut implementation of SetExpressCheckout
    /// </summary>
    /// <param name="amt"></param>
    /// <param ref name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
    {
        string host = "www.paypal.com";

        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
            host         = "www.sandbox.paypal.com";
        }

        string returnURL = "Shipping.aspx";
        string cancelURL = "Order.aspx";

        NVPCodec encoder = new NVPCodec();

        encoder["TENDER"] = "P";
        encoder["ACTION"] = "S";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else         /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }
        encoder["RETURNURL"] = returnURL;
        encoder["CANCELURL"] = cancelURL;
        encoder["AMT"]       = amt;
        encoder["CURRENCY"]  = "USD";

        // unique request ID
        System.Guid uid = System.Guid.NewGuid();

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp, uid.ToString());

        NVPCodec decoder = new NVPCodec();

        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();

        if (strAck != null && strAck == "0")
        {
            token = decoder["TOKEN"];

            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + "token=" + token;

            retMsg = ECURL;
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                     "Desc=" + decoder["RESPMSG"];

            return(false);
        }
    }
Example #22
0
    /// <summary>
    /// ShortcutExpressCheckout: The method that calls SetExpressCheckout API
    /// </summary>
    /// <param name="amt"></param>
    /// <param ref name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool ShortcutExpressCheckout(string amt, string itemName, string qty, string itemAmount, ref string token, ref string retMsg)
    {
        string host = "www.paypal.com";

        bool bSandbox = bool.Parse(ConfigurationManager.AppSettings["Sandbox"]);

        if (bSandbox)
        {
            pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
            host         = "www.sandbox.paypal.com";
        }

        string returnURL = ConfigurationManager.AppSettings["returnURL"];
        string cancelURL = ConfigurationManager.AppSettings["cancelURL"];
        string currency  = ConfigurationManager.AppSettings["currency"];

        NVPCodec encoder = new NVPCodec();

        encoder["METHOD"]    = "SetExpressCheckout";
        encoder["RETURNURL"] = returnURL;
        encoder["CANCELURL"] = cancelURL;
        encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = currency;

        encoder["PAYMENTREQUEST_0_AMT"]           = amt;
        encoder["PAYMENTREQUEST_0_ITEMAMT"]       = amt;
        encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";

        encoder["L_PAYMENTREQUEST_0_NAME0"] = itemName;
        encoder["L_PAYMENTREQUEST_0_QTY0"]  = qty;
        encoder["L_PAYMENTREQUEST_0_AMT0"]  = itemAmount;


        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        NVPCodec decoder = new NVPCodec();

        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();

        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            token = decoder["TOKEN"];

            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;

            retMsg = ECURL;
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                     "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                     "Desc2=" + decoder["L_LONGMESSAGE0"];

            return(false);
        }
    }
        public NVPCodec ECDoExpressCheckoutCode(string token, string payerID, string amount, string paymentType, string currencyCode)
        {
            NVPCallerServices caller  = new NVPCallerServices();
            IAPIProfile       profile = ProfileFactory.createSignatureAPIProfile();

            /*
             * WARNING: Do not embed plaintext credentials in your application code.
             * Doing so is insecure and against best practices.
             * Your API credentials must be handled securely. Please consider
             * encrypting them for use in any production environment, and ensure
             * that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "T")
            {
                profile.APIUsername  = "******";
                profile.APIPassword  = "******";
                profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
                profile.Environment  = "sandbox";
            }
            else if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "L")
            {
                profile.APIUsername  = "******";
                profile.APIPassword  = "******";
                profile.APISignature = "AFcWxV21C7fd0v3bYYYRCpSSRl31Ab5GxWPc-1XSb8rJctwNCFHIYb84";
                profile.Environment  = "live";
            }
            else
            {
                profile.APIUsername  = "******";
                profile.APIPassword  = "******";
                profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
                profile.Environment  = "sandbox";
            }
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();

            encoder["VERSION"] = "65.1";
            encoder["METHOD"]  = "DoExpressCheckoutPayment";

            // Add request-specific fields to the request.
            // Pass the token returned in SetExpressCheckout.
            encoder["TOKEN"]         = token;
            encoder["PAYERID"]       = payerID;
            encoder["AMT"]           = amount;
            encoder["PAYMENTACTION"] = paymentType;
            encoder["CURRENCYCODE"]  = currencyCode;

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp    = caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();

            decoder.Decode(pStresponsenvp);
            return(decoder);
        }
Example #24
0
 private WebSocket()
 {
     UrlEncoding  = Encoding.UTF8;
     UserAgent    = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727) SmokeTest/v1.0";
     MaxRedirects = 4;
     Cookies      = new NVPCodec();
     Headers      = new NVPCodec();
 }
Example #25
0
    /// <summary>
    /// ConfirmPayment: The method that calls DoExpressCheckoutPayment, invoked from the
    /// Billing Page EC placement
    /// </summary>
    /// <param name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool ConfirmPayment(string finalPaymentAmount, string token, string PayerId, ref NVPCodec decoder, ref string retMsg)
    {
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
        }

        NVPCodec encoder = new NVPCodec();

        encoder["TOKEN"]  = token;
        encoder["TENDER"] = "P";
        encoder["ACTION"] = "D";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else         /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }
        encoder["PAYERID"]  = PayerId;
        encoder["AMT"]      = finalPaymentAmount;
        encoder["CURRENCY"] = "USD";

        // unique request ID
        string unique_id;

        if (HttpContext.Current.Session["unique_id"] == null)
        {
            System.Guid uid = System.Guid.NewGuid();
            unique_id = uid.ToString();
            HttpContext.Current.Session["unique_id"] = unique_id;
        }
        else
        {
            unique_id = (string)HttpContext.Current.Session["unique_id"];
        }

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp, unique_id);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();

        if (strAck != null && strAck == "0")
        {
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                     "Desc=" + decoder["RESPMSG"];

            return(false);
        }
    }
Example #26
0
    /// <summary>
    /// DirectPayment: The method for credit card payment
    /// </summary>
    /// Note:
    ///	There are other optional inputs for credit card processing that are not presented here.
    ///		For a complete list of inputs available, please see the documentation here for US and UK:
    ///		http://www.paypal.com/en_US/pdf/PayflowPro_Guide.pdf
    ///		https://www.paypal.com/en_GB/pdf/PP_WebsitePaymentsPro_IntegrationGuide.pdf
    /// <param name="amt"></param>
    /// <param ref name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool DirectPayment(string paymentType, string paymentAmount, string creditCardType, string creditCardNumber, string expDate, string cvv2, string firstName, string lastName, string street, string city, string state, string zip, string countryCode, string currencyCode, string orderdescription, ref NVPCodec decoder, ref string retMsg)
    {
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
        }

        NVPCodec encoder = new NVPCodec();

        encoder["TENDER"] = "C";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else         /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }
        encoder["ACCT"]      = creditCardNumber;
        encoder["CVV2"]      = cvv2;
        encoder["EXPDATE"]   = expDate;
        encoder["ACCTTYPE"]  = creditCardType;
        encoder["AMT"]       = paymentAmount;
        encoder["CURRENCY"]  = currencyCode;
        encoder["FIRSTNAME"] = firstName;
        encoder["LASTNAME"]  = lastName;
        encoder["STREET"]    = street;
        encoder["CITY"]      = city;
        encoder["STATE"]     = state;
        encoder["ZIP"]       = zip;
        encoder["COUNTRY"]   = countryCode;
        // unique request ID
        System.Guid uid = System.Guid.NewGuid();
        encoder["INVNUM"]    = uid.ToString();
        encoder["ORDERDESC"] = orderdescription;
        encoder["VERBOSITY"] = "MEDIUM";

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp, uid.ToString());

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();

        if (strAck != null && strAck == "0")
        {
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                     "Desc=" + decoder["RESPMSG"];

            return(false);
        }
    }
        public Hashtable DoDirectPaymentCode()
        {
            NVPCallerServices caller  = new NVPCallerServices();
            IAPIProfile       profile = ProfileFactory.createSignatureAPIProfile();

            /*
             * WARNING: Do not embed plaintext credentials in your application code.
             * Doing so is insecure and against best practices.
             * Your API credentials must be handled securely. Please consider
             * encrypting them for use in any production environment, and ensure
             * that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername  = Constants.PayPal_Username;       //"sdk-three_api1.sdk.com";
            profile.APIPassword  = Constants.PayPal_Password;       //"QFZCWN5HZM8VBG7Q";
            profile.APISignature = Constants.PayPal_Signature;      //"AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment  = Constants.PayPal_PaymentAccount; //"live";// "sandbox";
            caller.APIProfile    = profile;

            NVPCodec encoder = new NVPCodec();

            encoder["VERSION"] = "51.0";
            encoder["METHOD"]  = "DoDirectPayment";

            // Add request-specific fields to the request.
            encoder["PAYMENTACTION"]  = "Sale"; //paymentAction;
            encoder["AMT"]            = fPaymentOrderTotal.ToString();
            encoder["CREDITCARDTYPE"] = (sCCType.Equals(CreditCardType.AmericanExpress)) ? "Amex" : sCCType.ToString();
            encoder["ACCT"]           = CCNumber;
            encoder["EXPDATE"]        = sCCExpDate;
            encoder["CVV2"]           = sCCVerificationCode;
            encoder["FIRSTNAME"]      = sCCOwnerFirstName;
            encoder["LASTNAME"]       = sCCOwnerLastName;
            encoder["STREET"]         = (sCCOwnerStreet2.Trim().Length > 0) ? string.Concat(sCCOwnerStreet1, ", ", sCCOwnerStreet2) : sCCOwnerStreet1;
            encoder["CITY"]           = sCCOwnerCityName;
            encoder["STATE"]          = sCCOwnerStateOrProvince;
            encoder["ZIP"]            = sCCOwnerPostalCode;
            encoder["COUNTRYCODE"]    = sCCOwnerCountryCode;
            encoder["CURRENCYCODE"]   = "USD";

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp    = caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();

            decoder.Decode(pStresponsenvp);

            Hashtable htResult = new Hashtable();

            foreach (string st in decoder.AllKeys)
            {
                htResult.Add(st, decoder[st]);
            }
            return(htResult);
        }
Example #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if ((string)Session["userCheckoutCompleted"] != "true")
                {
                    Session["userCheckoutCopleted"] = string.Empty;
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidate%20Checkout.");
                }

                NVPAPICaller payPalCaller = new NVPAPICaller();

                string   retMsg             = "";
                string   token              = "";
                string   finalPaymentAmount = "";
                string   PayerID            = "";
                NVPCodec decoder            = new NVPCodec();

                token              = Session["token"].ToString();
                PayerID            = Session["payerID"].ToString();
                finalPaymentAmount = (Convert.ToInt32(Session["payment_amt"]) * 100).ToString();

                bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                    TransactionId.Text = PaymentConfirmation;

                    ProductContext _db            = new ProductContext();
                    int            currentOrderId = -1;
                    if (Session["currentOrderID"].ToString() != string.Empty)
                    {
                        currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                    }
                    Order myCurrentOrder;
                    if (currentOrderId >= 0)
                    {
                        myCurrentOrder = _db.Orders.Single(
                            o => o.OrderId == currentOrderId);

                        myCurrentOrder.PaymentTransactionId = PaymentConfirmation;
                        _db.SaveChanges();
                    }

                    using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
                    {
                        usersShoppingCart.EmptyCart();
                    }

                    Session["currentOrderId"] = string.Empty;
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
Example #29
0
    public bool ShortcutExpressCheckout(string subTotal, string shippingIn, string amt, ref string token, ref string retMsg, Customer customerIn)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
            host         = host_SB;
        }

        string returnURL = "http://localhost:64352/Graded%20Unit1/CheckoutReview.aspx";
        string cancelURL = "http://localhost:64352/Graded%20Unit1/CheckoutCancel.aspx";

        NVPCodec encoder = new NVPCodec();

        encoder["METHOD"]                         = "SetExpressCheckout";
        encoder["RETURNURL"]                      = returnURL;
        encoder["CANCELURL"]                      = cancelURL;
        encoder["BRANDNAME"]                      = "LidiFlu Ltd";
        encoder["PAYMENTREQUEST_0_AMT"]           = amt;
        encoder["PAYMENTREQUEST_0_ITEMAMT"]       = subTotal;
        encoder["PAYMENTREQUEST_0_SHIPPINGAMT"]   = shippingIn;
        encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
        encoder["PAYMENTREQUEST_0_CURRENCYCODE"]  = "GBP";

        // Get the Shopping Cart Products


        for (int i = 0; i < customerIn.Orders[0].OrderLines.Count; i++)
        {
            encoder["L_PAYMENTREQUEST_0_NAME" + i] = customerIn.Orders[0].OrderLines[i].Product.ProdName.ToString();
            encoder["L_PAYMENTREQUEST_0_AMT" + i]  = customerIn.Orders[0].OrderLines[i].Product.ProdPrice.ToString();
            encoder["L_PAYMENTREQUEST_0_QTY" + i]  = customerIn.Orders[0].OrderLines[i].Quantity.ToString();
        }

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        NVPCodec decoder = new NVPCodec();

        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();

        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            token = decoder["TOKEN"];
            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
            retMsg = ECURL;
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                     "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                     "Desc2=" + decoder["L_LONGMESSAGE0"];
            return(false);
        }
    }
Example #30
0
        public string MassPayCode(string emailSubject, string receiverType, string currencyCode, string ReceiverEmail0, string amount0, string UniqueID0, string Note0, string ReceiverEmail1, string amount1, string UniqueID1, string Note1)
        {
            NVPCallerServices caller  = new NVPCallerServices();
            IAPIProfile       profile = ProfileFactory.createSignatureAPIProfile();

            /*
             * WARNING: Do not embed plaintext credentials in your application code.
             * Doing so is insecure and against best practices.
             * Your API credentials must be handled securely. Please consider
             * encrypting them for use in any production environment, and ensure
             * that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername  = "******";
            profile.APIPassword  = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment  = "sandbox";
            caller.APIProfile    = profile;

            NVPCodec encoder = new NVPCodec();

            encoder["VERSION"] = "51.0";
            encoder["METHOD"]  = "MassPay";

            // Add request-specific fields to the request.
            encoder["EMAILSUBJECT"] = emailSubject;
            encoder["RECEIVERTYPE"] = receiverType;
            encoder["CURRENCYCODE"] = currencyCode;

            if (ReceiverEmail0.Length > 0)
            {
                encoder["L_EMAIL0"]    = ReceiverEmail0;
                encoder["L_Amt0"]      = amount0;
                encoder["L_UNIQUEID0"] = UniqueID0;
                encoder["L_NOTE0"]     = Note0;
            }

            if (ReceiverEmail1.Length > 0)
            {
                encoder["L_EMAIL1"]    = ReceiverEmail1;
                encoder["L_Amt1"]      = amount1;
                encoder["L_UNIQUEID1"] = UniqueID1;
                encoder["L_NOTE1"]     = Note1;
            }



            // Execute the API operation and obtain the response.
            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp    = caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();

            decoder.Decode(pStresponsenvp);
            return(decoder["ACK"]);
        }
Example #31
0
    /// <summary>
    /// ConfirmPayment: The method that calls DoExpressCheckoutPayment, invoked from the 
    /// Billing Page EC placement
    /// </summary>
    /// <param name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool ConfirmPayment(string finalPaymentAmount, string token, string PayerId, ref NVPCodec decoder, ref string retMsg )
    {
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
        }

        NVPCodec encoder = new NVPCodec();

        encoder["TOKEN"] = token;
        encoder["TENDER"] = "P";
        encoder["ACTION"] = "D";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }
        encoder["PAYERID"] = PayerId;
        encoder["AMT"] = finalPaymentAmount;

        // unique request ID
        string unique_id;

        if (HttpContext.Current.Session["unique_id"] == null)
        {
            System.Guid uid = System.Guid.NewGuid();
            unique_id = uid.ToString();
            HttpContext.Current.Session["unique_id"] = unique_id;
        }
        else
        {
            unique_id = (string)HttpContext.Current.Session["unique_id"];
        }

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall(pStrrequestforNvp,unique_id);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();
        if (strAck != null && strAck == "0")
        {
            return true;
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                "Desc=" + decoder["RESPMSG"];

            return false;
        }
    }
Example #32
0
    public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
            host         = host_SB;
        }

        string returnURL = "http://localhost:51341/Checkout/CheckoutReview.aspx";
        string cancelURL = "http://localhost:51341/Checkout/CheckoutCancel.aspx";

        NVPCodec encoder = new NVPCodec();

        encoder["METHOD"]                         = "SetExpressCheckout";
        encoder["RETURNURL"]                      = returnURL;
        encoder["CANCELURL"]                      = cancelURL;
        encoder["BRANDNAME"]                      = "Go Events Ticket System";
        encoder["PAYMENTREQUEST_0_AMT"]           = amt;
        encoder["PAYMENTREQUEST_0_ITEMAMT"]       = amt;
        encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
        encoder["PAYMENTREQUEST_0_CURRENCYCODE"]  = "USD";

        List <CartItem> myOrderList = (List <CartItem>)Session["CartItems"];

        encoder["L_PAYMENTREQUEST_0_NAME"] = myOrderList[0].EventName.ToString();
        encoder["L_PAYMENTREQUEST_0_QTY"]  = myOrderList.Count.ToString();

        for (int i = 0; i < myOrderList.Count; i++)
        {
            encoder["L_PAYMENTREQUEST_0_AMT" + i] = myOrderList[i].Price.ToString();
        }

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp);

        NVPCodec decoder = new NVPCodec();

        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();

        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            token = decoder["TOKEN"];
            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
            retMsg = ECURL;
            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                     "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                     "Desc2=" + decoder["L_LONGMESSAGE0"];
            return(false);
        }
    }
Example #33
0
        private static string GetCodecStatus(NVPCodec codec)
        {
            var stringBuilder = new StringBuilder();

            foreach (string s in codec)
            {
                stringBuilder.AppendLine(string.Format("{0} => {1}", s, codec[s]));
            }
            return(stringBuilder.ToString());
        }
Example #34
0
        private NVPCodec InitializeEncoder(tbl_Orders order)
        {
            decimal totalItemsPrice = order.tbl_OrderContent.Sum(oc => oc.OC_TotalPrice) + order.DependentOrders.Sum(o => o.TotalAmount);

            string totalAmount         = Math.Round(order.TotalAmountToPay, 2).ToString().Replace(',', '.');
            string totalTaxAmount      = Math.Round(order.TotalTaxAmount, 2).ToString().Replace(',', '.');
            string totalItemsAmount    = order.O_IsCustomAmount ? order.TotalAmountToPay.ToString().Replace(',', '.') : Math.Round(totalItemsPrice, 2).ToString().Replace(',', '.');
            string totalShippingAmount = Math.Round(order.TotalDeliveryAmount, 2).ToString().Replace(',', '.');

            NVPCodec encoder = new NVPCodec();

            encoder[PayPalConsts.Version]          = "98.0";
            encoder[PayPalConsts.TotalAmount]      = totalAmount;
            encoder[PayPalConsts.DeliveryAmount]   = totalShippingAmount;
            encoder[PayPalConsts.ItemsTotalAmount] = totalItemsAmount;

            if (order.DiscountAmount != 0)
            {
                decimal discount = order.DiscountAmount > totalItemsPrice ? totalItemsPrice : order.DiscountAmount;
                encoder[PayPalConsts.DiscountAmount] = Math.Round(-Math.Abs(discount), 2).ToString().Replace(',', '.');
            }

            // if order items should be listed in order details displayed on PayPal account
            if (DomainService.GetSettingsValueAsBool(BL.SettingsKey.payPalSendOrderItems, this.DomainID) && !order.O_IsCustomAmount)
            {
                int i = 0;
                foreach (var oc in order.tbl_OrderContent)
                {
                    encoder[PayPalConsts.GetItemNumberKey(i)] = oc.tbl_Products == null?oc.tbl_ProductPrice.PR_ProductID.ToString() : oc.tbl_Products.P_ProductCode;

                    encoder[PayPalConsts.GetItemNameKey(i)]         = oc.OC_Title ?? "";
                    encoder[PayPalConsts.GetItemDescriptionKey(i)]  = oc.OC_Description ?? "";
                    encoder[PayPalConsts.GetItemQuantityKey(i)]     = oc.OC_Quantity.ToString();
                    encoder[PayPalConsts.GetItemsTotalAmountKey(i)] = Math.Round(oc.OC_TotalPrice / oc.OC_Quantity.GetValueOrDefault(1), 2).ToString().Replace(',', '.');

                    i++;
                }
                if (order.DependentOrders.Any())
                {
                    foreach (var donation in order.DependentOrders)
                    {
                        encoder[PayPalConsts.GetItemNumberKey(i)]       = donation.OrderID.ToString();
                        encoder[PayPalConsts.GetItemNameKey(i)]         = String.Format("Donation to order {0}", order.OrderID);
                        encoder[PayPalConsts.GetItemDescriptionKey(i)]  = "donation";
                        encoder[PayPalConsts.GetItemQuantityKey(i)]     = "1";
                        encoder[PayPalConsts.GetItemsTotalAmountKey(i)] = Math.Round(donation.TotalAmount, 2).ToString().Replace(',', '.');

                        i++;
                    }
                }
            }

            return(encoder);
        }
Example #35
0
    /// <summary>
    /// Populates a new CheckoutErrorModel object from the passed in return data from the gateway.
    /// </summary>
    /// <param name="decoder"></param>
    /// <returns></returns>
    public CheckoutErrorModel PopulateGatewayErrorModel(NVPCodec decoder)
    {
        var errorVM = new CheckoutErrorModel
        {
            ErrorCode    = decoder[NVPProperties.Properties.ERRORCODE],
            LongMessage  = decoder[NVPProperties.Properties.LONGMESSAGE],
            ShortMessage = decoder[NVPProperties.Properties.SHORTMESSAGE]
        };

        return(errorVM);
    }
Example #36
0
        public async Task Validate_TestStartCalled_ISmokeTestProviderRegistered_Returns_NvpCodecValues()
        {
            ISettingsProvider settingsProvider = new pm.DefaultSettingProvider(Directory.GetCurrentDirectory());

            TestHttpRequest httpRequest = new TestHttpRequest();

            httpRequest.Path = "/smokeTest/Start/";
            TestHttpResponse httpResponse = new TestHttpResponse();

            IPluginHelperService pluginHelperServices = _testPluginSmokeTest.GetRequiredService <IPluginHelperService>();
            IPluginTypesService  pluginTypesService   = _testPluginSmokeTest.GetRequiredService <IPluginTypesService>();
            IServiceCollection   serviceCollection    = new ServiceCollection() as IServiceCollection;
            NVPCodec             codecValues          = new NVPCodec();

            codecValues.Add("username", "admin");
            MockSmokeTestProvider smokeTestProvider = new MockSmokeTestProvider(codecValues);

            serviceCollection.AddSingleton <ISmokeTestProvider>(smokeTestProvider);

            TestHttpContext httpContext = new TestHttpContext(httpRequest, httpResponse,
                                                              serviceCollection.BuildServiceProvider());
            ILogger         logger             = new Logger();
            bool            nextDelegateCalled = false;
            RequestDelegate requestDelegate    = async(context) => { nextDelegateCalled = true; await Task.Delay(0); };

            using (WebSmokeTestMiddleware sut = new WebSmokeTestMiddleware(requestDelegate, pluginHelperServices,
                                                                           pluginTypesService, settingsProvider, logger))
            {
                List <WebSmokeTestItem> smokeTests = sut.SmokeTests;

                Assert.IsTrue(smokeTests.Count > 1);

                await sut.Invoke(httpContext);

                Assert.IsFalse(nextDelegateCalled);
                Assert.AreEqual(200, httpResponse.StatusCode);
                Assert.IsNull(httpResponse.ContentType);
                Assert.IsTrue(smokeTestProvider.StartCalled);

                byte[] data = new byte[httpResponse.Body.Length];
                httpResponse.Body.Position = 0;
                httpResponse.Body.Read(data, 0, data.Length);
                string test = Decrypt(Encoding.UTF8.GetString(data), EncryptionKey);

                Assert.IsFalse(String.IsNullOrEmpty(test));
                NVPCodec codec = new NVPCodec();
                codec.Decode(test);

                Assert.AreEqual(1, codec.AllKeys.Length);

                Assert.IsTrue(codec.AllKeys.Contains("username"));
                Assert.AreEqual("admin", codec["username"]);
            }
        }
Example #37
0
    /// <summary>
    /// GetShippingDetails: The method that calls GetExpressCheckoutDetails
    /// </summary>
    /// <param name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool GetShippingDetails(string token, ref string PayerId, ref string ShippingAddress, ref string retMsg)
    {
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
        }

        NVPCodec encoder = new NVPCodec();

        encoder["TOKEN"]  = token;
        encoder["TENDER"] = "P";
        encoder["ACTION"] = "G";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else         /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }

        // unique request ID
        System.Guid uid = System.Guid.NewGuid();

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp    = HttpCall(pStrrequestforNvp, uid.ToString());

        NVPCodec decoder = new NVPCodec();

        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();

        if (strAck != null && strAck == "0")
        {
            ShippingAddress  = "<table><tr>";
            ShippingAddress += "<td colspan='2'> Shipping Address</td></tr>";
            ShippingAddress += "<td> Street1 </td><td>" + decoder["SHIPTOSTREET"] + "</td></tr>";
            ShippingAddress += "<td> Street2 </td><td>" + decoder["SHIPTOSTREET2"] + "</td></tr>";
            ShippingAddress += "<td> City </td><td>" + decoder["SHIPTOCITY"] + "</td></tr>";
            ShippingAddress += "<td> State </td><td>" + decoder["SHIPTOSTATE"] + "</td></tr>";
            ShippingAddress += "<td> Zip </td><td>" + decoder["SHIPTOZIP"] + "</td>";
            ShippingAddress += "</tr>";

            return(true);
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                     "Desc=" + decoder["RESPMSG"];

            return(false);
        }
    }
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="nvp"></param>
        /// <returns></returns>
        private NVPCodec SendExpressCheckoutCommand(NVPCodec nvp)
        {
            NVPCallerServices service = InitializeServices();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            string   response    = service.Call(nvp.Encode());
            NVPCodec responsenvp = new NVPCodec();

            responsenvp.Decode(response);
            return(responsenvp);
        }
Example #39
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Verify user has completed the checkout process.
            if (Session["userCheckoutCompleted"] != "true")
            {
                Session["userCheckoutCompleted"] = "";
                Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
            }

            NVPAPICaller payPalCaller = new NVPAPICaller();

            string retMsg = "";
            string token = "";
            string finalPaymentAmount = "";
            string PayerID = "";
            NVPCodec decoder = new NVPCodec();

            token = Session["token"].ToString();
            PayerID = Session["payerId"].ToString();
            finalPaymentAmount = Session["payment_amt"].ToString();

            bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                // Retrieve PayPal confirmation value.
                string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                TransactionId.Text = PaymentConfirmation;

                // Get dataaccess context.
                DataAccess da = new DataAccess();
                Customer aCustomer = (Customer)Session["Customer"];
                aCustomer.Orders[0].OrderID = PaymentConfirmation;
                aCustomer = CartFunctions.setOrderId(aCustomer, PaymentConfirmation);
                // Add order to DB.

                da.addCustomer(aCustomer);
                da.addOrder(aCustomer);
                da.addOrderline(aCustomer);

                // Clear Order

                aCustomer = CartFunctions.clearOrder(aCustomer);

            }
            else
            {
                Response.Redirect("CheckoutError.aspx?" + retMsg);
            }
        }
    }
Example #40
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Verify user has completed the checkout process.
            if ((string)Session["userCheckoutCompleted"] != "true")
            {
                Session["userCheckoutCompleted"] = string.Empty;
                Response.Redirect(PrizeConstants.URL_CHECKOUT_ERROR + "?" + "Desc=Unvalidated%20Checkout.");
            }

            NVPAPICaller payPalCaller = new NVPAPICaller();
            payPalCaller.SetCredentials(PrizeConstants.WALLET_USER_NAME,
                                        PrizeConstants.WALLET_PASSWORD,
                                        PrizeConstants.WALLET_SIGNATURE);

            string   retMsg             = "";
            string   token              = "";
            string   finalPaymentAmount = "";
            string   PayerID            = "";
            NVPCodec decoder            = new NVPCodec();

            token              = Session["token"].ToString();
            PayerID            = Session["payerId"].ToString();
            finalPaymentAmount = Session["payment_amt"].ToString();

            bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                // Retrieve PayPal confirmation value.
                string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();

                TransactionId.Text = PaymentConfirmation;

                int currentOrderId = -1;
                if (Session["currentOrderId"] != string.Empty)
                {
                    currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
                }

                PrizeMemberPlanManager planManager = new PrizeMemberPlanManager();
                planManager.PayMemberPlans(currentOrderId, PaymentConfirmation);

                // Clear order id.
                Session["currentOrderId"] = string.Empty;
            }
            else
            {
                Response.Redirect(PrizeConstants.URL_CHECKOUT_ERROR + "?" + retMsg);
            }
        }
    }
Example #41
0
        public string MassPayCode(string emailSubject,string receiverType,string currencyCode,string ReceiverEmail0,string amount0,string UniqueID0,string Note0,string ReceiverEmail1,string amount1,string UniqueID1,string Note1)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment="sandbox";
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "51.0";
            encoder["METHOD"] =  "MassPay";

            // Add request-specific fields to the request.
            encoder["EMAILSUBJECT"] =  emailSubject;
            encoder["RECEIVERTYPE"] =  receiverType;
            encoder["CURRENCYCODE"]=currencyCode;

            if(ReceiverEmail0.Length>0)
            {
                encoder["L_EMAIL0"] =  ReceiverEmail0;
                encoder["L_Amt0"] =  amount0;
                encoder["L_UNIQUEID0"] =  UniqueID0;
                encoder["L_NOTE0"] =  Note0;
            }

            if(ReceiverEmail1.Length>0)
            {
                encoder["L_EMAIL1"] =  ReceiverEmail1;
                encoder["L_Amt1"] =  amount1;
                encoder["L_UNIQUEID1"] =  UniqueID1;
                encoder["L_NOTE1"] =  Note1;
            }

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
        public NVPCodec ECGetExpressCheckoutCode(string token)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "T")
            {
                profile.APIUsername = "******";
                profile.APIPassword = "******";
                profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
                profile.Environment = "sandbox";
            }
            else if (System.Configuration.ConfigurationManager.AppSettings["ENVIRONMENT"].ToString() == "L")
            {
                profile.APIUsername = "******";
                profile.APIPassword = "******";
                profile.APISignature = "AFcWxV21C7fd0v3bYYYRCpSSRl31Ab5GxWPc-1XSb8rJctwNCFHIYb84";
                profile.Environment = "live";
            }
            else
            {
                profile.APIUsername = "******";
                profile.APIPassword = "******";
                profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
                profile.Environment = "sandbox";
            }
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "65.1";
            encoder["METHOD"] =  "GetExpressCheckoutDetails";

            // Add request-specific fields to the request.
            encoder["TOKEN"] =  token; // Pass the token returned in SetExpressCheckout.

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder;
        }
Example #43
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Verify user has completed the checkout process.
            if (Session["userCheckoutCompleted"] != "true")
            {
                Session["userCheckoutCompleted"] = "";
                Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
            }

            NVPAPICaller payPalCaller = new NVPAPICaller();

            string   retMsg             = "";
            string   token              = "";
            string   finalPaymentAmount = "";
            string   PayerID            = "";
            NVPCodec decoder            = new NVPCodec();

            token              = Session["token"].ToString();
            PayerID            = Session["payerId"].ToString();
            finalPaymentAmount = Session["payment_amt"].ToString();

            bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                // Retrieve PayPal confirmation value.
                string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
                TransactionId.Text = PaymentConfirmation;

                // Get dataaccess context.
                DataAccess da        = new DataAccess();
                Customer   aCustomer = (Customer)Session["Customer"];
                aCustomer.Orders[0].OrderID = PaymentConfirmation;
                aCustomer = CartFunctions.setOrderId(aCustomer, PaymentConfirmation);
                // Add order to DB.

                da.addCustomer(aCustomer);
                da.addOrder(aCustomer);
                da.addOrderline(aCustomer);

                // Clear Order

                aCustomer = CartFunctions.clearOrder(aCustomer);
            }
            else
            {
                Response.Redirect("CheckoutError.aspx?" + retMsg);
            }
        }
    }
Example #44
0
        public string ECDoExpressCheckout(string token, string payerID, string amount, Cart cart)
        {
            Settings settings = new Settings();
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = getProfile();
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder.Add("VERSION","84.0");
            encoder.Add("METHOD","DoExpressCheckoutPayment");

            // Add request-specific fields to the request.
            encoder.Add("TOKEN",token);
            encoder.Add("PAYERID",payerID);
            encoder.Add("RETURNURL",getSiteURL() + "Payment/PayPalCheckout");
            encoder.Add("CANCELURL",getSiteURL() + "Payment");
            encoder.Add("PAYMENTREQUEST_0_AMT",amount);
            encoder.Add("PAYMENTREQUEST_0_PAYMENTACTION","Sale");
            encoder.Add("PAYMENTREQUEST_0_CURRENCYCODE","USD");
            encoder.Add("BRANDNAME",settings.Get("SiteName"));
            encoder.Add("LOGIN","Login");
            encoder.Add("HDRIMG",settings.Get("EmailLogo"));
            encoder.Add("CUSTOMERSERVICENUMBER",settings.Get("PhoneNumber"));
            encoder.Add("PAYMENTREQUEST_0_SHIPPINGAMT",cart.shipping_price.ToString());
            encoder.Add("PAYMENTREQUEST_0_DESC","Your " + settings.Get("SiteName") + " Order");
            encoder.Add("ALLOWNOTE","0");
            encoder.Add("NOSHIPPING","1");
            int count = 0;
            decimal total = 0;
            foreach (CartItem item in cart.CartItems) {
                encoder.Add("L_PAYMENTREQUEST_0_NUMBER" + count, item.partID.ToString());
                encoder.Add("L_PAYMENTREQUEST_0_NAME" + count, item.shortDesc);
                encoder.Add("L_PAYMENTREQUEST_0_AMT" + count, String.Format("{0:N2}", item.price));
                encoder.Add("L_PAYMENTREQUEST_0_QTY" + count, item.quantity.ToString());
                encoder.Add("L_PAYMENTREQUEST_0_ITEMCATEGORY" + count, "Physical");
                encoder.Add("L_PAYMENTREQUEST_0_ITEMURL" + count, settings.Get("SiteURL") + "part/" + item.partID);
                total += item.price * item.quantity;
                count++;
            }
            encoder.Add("PAYMENTREQUEST_0_TAXAMT", String.Format("{0:N2}", cart.tax));
            encoder.Add("PAYMENTREQUEST_0_ITEMAMT", String.Format("{0:N2}", total));
            // Execute the API operation and obtain the response.
            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp = caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
Example #45
0
        public string DoDirectPaymentCode(string paymentAction,string amount,string creditCardType,string creditCardNumber,string expdate_month,string cvv2Number,string firstName,string lastName,string address1,string city,string state,string zip,string countryCode,string currencyCode)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment="sandbox";
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "51.0";
            encoder["METHOD"] =  "DoDirectPayment";

            // Add request-specific fields to the request.
            encoder["PAYMENTACTION"] =  paymentAction;
            encoder["AMT"] =  amount;
            encoder["CREDITCARDTYPE"] =  creditCardType;
            encoder["ACCT"] =  creditCardNumber;
            encoder["EXPDATE"] =  expdate_month;
            encoder["CVV2"] =  cvv2Number;
            encoder["FIRSTNAME"] =  firstName;
            encoder["LASTNAME"] =  lastName;
            encoder["STREET"] =  address1;
            encoder["CITY"] =  city;
            encoder["STATE"] =  state;
            encoder["ZIP"] =  zip;
            encoder["COUNTRYCODE"] = countryCode;
            encoder["CURRENCYCODE"] =  currencyCode;

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
        public ICreditCardAuthorizationResponse VerifyCreditCardInfo(ICreditCardAuthorizationRequest request)
        {
            var caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();

            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AzbQABSL2jEPPHG.eDus2jfMT0xEAUITxvhhUWGmd3DHxaPXx6Zs1MPR";
            profile.Environment = "sandbox";
            caller.APIProfile = profile;

            var encoder = new NVPCodec();

            encoder["SIGNATURE"] = "AzbQABSL2jEPPHG.eDus2jfMT0xEAUITxvhhUWGmd3DHxaPXx6Zs1MPR";
            encoder["USER"] = "******";
            encoder["PWD"] = "1302977698";
            encoder["VERSION"] = "60.0";
            encoder["METHOD"] = "DoDirectPayment";

            // Add request-specific fields to the request.
            encoder["PAYMENTACTION"] = CreditCardPaymentActions.Authorization.ToString();
            encoder["AMT"] = "100";
            encoder["CREDITCARDTYPE"] = request.CreditCardInfo.Type.ToString();
            encoder["IPADDRESS"] = "192.168.0.1";
            encoder["ACCT"] = request.CreditCardInfo.CreditCardNumber;
            encoder["EXPDATE"] = request.CreditCardInfo.ExpirationDate.ToString("MMyyyy");
            encoder["CVV2"] = request.CreditCardInfo.Cvv2Number;
            encoder["FIRSTNAME"] = request.FirstName;
            encoder["LASTNAME"] = request.LastName;
            encoder["STREET"] = request.AddressInfo.Address1;
            encoder["CITY"] = request.AddressInfo.City;
            encoder["STATE"] = request.AddressInfo.State;
            encoder["ZIP"] = request.AddressInfo.ZipCode;
            encoder["COUNTRYCODE"] = request.AddressInfo.Country;
            encoder["CURRENCYCODE"] = "USD";

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp = caller.Call(pStrrequestforNvp);

            var decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return new CreditCardAuthorizationReponse(decoder["ACK"] == "Success");
        }
    /// <summary>
    /// This method is called first in order to perform the initial authorization for payment.
    /// </summary>
    /// <param name="amt"></param>
    /// <param name="token"></param>
    /// <param name="retMsg"></param>
    /// <returns></returns>
    public bool DoCheckoutAuth(OrderViewModel order, ref string token, ref NVPCodec decoder)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
        }

        NVPCodec encoder = new NVPCodec();
        encoder[NVPProperties.Properties.METHOD] = NVPProperties.Methods.AuthorizePayment;
        encoder[NVPProperties.Properties.BRANDNAME] = "Contoso Sports League";
        encoder[NVPProperties.Properties.PAYMENTREQUEST_AMT] = order.Total.ToString();
        encoder[NVPProperties.Properties.FIRSTNAME] = order.FirstName;
        encoder[NVPProperties.Properties.LASTNAME] = order.LastName;
        encoder[NVPProperties.Properties.ADDRESS] = order.Address;
        encoder[NVPProperties.Properties.CITY] = order.City;
        encoder[NVPProperties.Properties.STATE] = order.State;
        encoder[NVPProperties.Properties.POSTALCODE] = order.PostalCode;
        encoder[NVPProperties.Properties.NAME_ON_CREDIT_CARD] = order.NameOnCard;
        encoder[NVPProperties.Properties.CREDIT_CARD_TYPE] = order.CreditCardType;
        encoder[NVPProperties.Properties.CREDIT_CARD_NUMBER] = order.CreditCardNumber;
        encoder[NVPProperties.Properties.CREDIT_CARD_EXPDATE] = order.ExpirationDate;
        encoder[NVPProperties.Properties.CCV2] = order.CCV;

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall(pStrrequestforNvp);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder[NVPProperties.Properties.ACK].ToLower();
        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
        public string SetCustomerBillingAgreementCode(string returnURL,string cancelURL,string billingDesc)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */

            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment="sandbox";
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "51.0";
            encoder["METHOD"] =  "SetCustomerBillingAgreement";

            // Add request-specific fields to the request.
            encoder["RETURNURL"] =  returnURL;
            encoder["CANCELURL"] =  cancelURL;
            encoder["BILLINGTYPE"] =  "RecurringPayments";
            encoder["BILLINGAGREEMENTDESCRIPTION"] =  billingDesc;

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
        public string CreateRecurringPaymentsProfileCode(string token,string amount,string profileDate, string billingPeriod, string billingFrequency)
        {
            NVPCallerServices caller = new NVPCallerServices();
            IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
            /*
             WARNING: Do not embed plaintext credentials in your application code.
             Doing so is insecure and against best practices.
             Your API credentials must be handled securely. Please consider
             encrypting them for use in any production environment, and ensure
             that only authorized individuals may view or modify them.
             */
            // Set up your API credentials, PayPal end point, API operation and version.
            profile.APIUsername = "******";
            profile.APIPassword = "******";
            profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
            profile.Environment="sandbox";
            caller.APIProfile = profile;

            NVPCodec encoder = new NVPCodec();
            encoder["VERSION"] =  "51.0";

            // Add request-specific fields to the request.
            encoder["METHOD"] =  "CreateRecurringPaymentsProfile";
            encoder["TOKEN"] =  token;
            encoder["AMT"] =  amount;
            encoder["PROFILESTARTDATE"] =  profileDate;	//Date format from server expects Ex: 2006-9-6T0:0:0
            encoder["BILLINGPERIOD"] =  billingPeriod;
            encoder["BILLINGFREQUENCY"] =  billingFrequency;

            // Execute the API operation and obtain the response.
            string pStrrequestforNvp= encoder.Encode();
            string pStresponsenvp=caller.Call(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);
            return decoder["ACK"];
        }
    public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
    {
        if (bSandbox)
            {
                pEndPointURL = pEndPointURL_SB;
                host = host_SB;
            }

            string returnURL = "http://ethiohilecomvctoysapp2017.apphb.com/Checkout/CheckoutReview";
            string cancelURL = "http://ethiohilecomvctoysapp2017.apphb.com/Checkout/CheckoutCancel";

            NVPCodec encoder = new NVPCodec();
            encoder["METHOD"] = "SetExpressCheckout";
            encoder["RETURNURL"] = returnURL;
            encoder["CANCELURL"] = cancelURL;
            encoder["BRANDNAME"] = "HiLEco MVC Toys Sample Application 2015";
            encoder["PAYMENTREQUEST_0_AMT"] = amt;
            encoder["PAYMENTREQUEST_0_ITEMAMT"] = amt;
            encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
            encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD";

            // Get the Shopping Cart Products
            CartApplicationService cartApplicationService = new CartApplicationService();

            var Cart = ShoppingCartActions.GetCart();
            // string CartID = Cart.GetCartId(this.HttpContext);
            string CartID = "";
            CartID = Cart.ShoppingCartId;

            CartViewModel cartViewModel = new CartViewModel();
            cartViewModel=cartApplicationService.GetCarts(CartID);
            int i = 0;
            foreach (var item in cartViewModel.Carts)
            {
                if (item.CartID != "")
                {

                    encoder["L_PAYMENTREQUEST_0_NAME" + i] = item.ProductName.ToString();
                    encoder["L_PAYMENTREQUEST_0_AMT" + i] = item.UnitPrice.ToString();
                    encoder["L_PAYMENTREQUEST_0_QTY" + i] = item.Quantity.ToString();

                }
                i++;
            }
            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp = HttpCall(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);

            string strAck = decoder["ACK"].ToLower();
            if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
            {
                token = decoder["TOKEN"];
                string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
                retMsg = ECURL;
                return true;
            }
            else
            {
                retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                    "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                    "Desc2=" + decoder["L_LONGMESSAGE0"];
                return false;
            }
    }
Example #51
0
    /// <summary>
    /// GetShippingDetails: The method that calls GetExpressCheckoutDetails
    /// </summary>
    /// <param name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool GetShippingDetails(string token, ref string PayerId, ref string ShippingAddress, ref string retMsg)
    {
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
        }

        NVPCodec encoder = new NVPCodec();
        encoder["TOKEN"] = token;
        encoder["TENDER"] = "P";
        encoder["ACTION"] = "G";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }

        // unique request ID
        System.Guid uid = System.Guid.NewGuid();

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall( pStrrequestforNvp,uid.ToString() );

        NVPCodec decoder = new NVPCodec();
        decoder.Decode( pStresponsenvp );

        string strAck = decoder["RESULT"].ToLower();
        if (strAck != null && strAck == "0")
        {
            ShippingAddress = "<table><tr>";
            ShippingAddress += "<td colspan='2'> Shipping Address</td></tr>";
            ShippingAddress += "<td> Street1 </td><td>" + decoder["SHIPTOSTREET"] + "</td></tr>";
            ShippingAddress += "<td> Street2 </td><td>" + decoder["SHIPTOSTREET2"] + "</td></tr>";
            ShippingAddress += "<td> City </td><td>" + decoder["SHIPTOCITY"] + "</td></tr>";
            ShippingAddress += "<td> State </td><td>" + decoder["SHIPTOSTATE"] + "</td></tr>";
            ShippingAddress += "<td> Zip </td><td>" + decoder["SHIPTOZIP"] + "</td>";
            ShippingAddress += "</tr>";

            return true;
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                "Desc=" + decoder["RESPMSG"];

            return false;
        }
    }
    private string buildCredentialsNVPString()
    {
        NVPCodec codec = new NVPCodec();

        if (!IsEmpty(APIUsername))
            codec["USER"] = APIUsername;

        if (!IsEmpty(APIPassword))
            codec[PWD] = APIPassword;

        if (!IsEmpty(APISignature))
            codec[SIGNATURE] = APISignature;

        if (!IsEmpty(Subject))
            codec["SUBJECT"] = Subject;

        codec["VERSION"] = "88.0";

        return codec.Encode();
    }
    public bool GetCheckoutDetails(string token, ref string PayerID, ref NVPCodec decoder, ref string retMsg)
    {
        if (bSandbox)
        {
            pEndPointURL = pEndPointURL_SB;
        }

        NVPCodec encoder = new NVPCodec();
        encoder["METHOD"] = "GetExpressCheckoutDetails";
        encoder["TOKEN"] = token;

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall(pStrrequestforNvp);

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["ACK"].ToLower();
        if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
        {
            PayerID = decoder["PAYERID"];
            return true;
        }
        else
        {
            retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                "Desc2=" + decoder["L_LONGMESSAGE0"];

            return false;
        }
    }
Example #54
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                NVPAPICaller payPalCaller = new NVPAPICaller();

                string retMsg = "";
                string token = "";
                string PayerID = "";
                NVPCodec decoder = new NVPCodec();
                token = Session["token"].ToString();

                bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
                if (ret)
                {
                    Session["payerId"] = PayerID;

                    var myOrder = new Order();
                    myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                    myOrder.Username = User.Identity.Name;
                    myOrder.FirstName = decoder["FIRSTNAME"].ToString();
                    myOrder.LastName = decoder["LASTNAME"].ToString();
                    myOrder.Address = decoder["SHIPTOSTREET"].ToString();
                    myOrder.City = decoder["SHIPTOCITY"].ToString();
                    myOrder.State = decoder["SHIPTOSTATE"].ToString();
                    myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
                    myOrder.Country = decoder["SHIPTOCOUNTRYCODE"].ToString();
                    myOrder.Email = decoder["EMAIL"].ToString();
                    myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());

                    // Verify total payment amount as set on CheckoutStart.aspx.
                    try
                    {
                        decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                        decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                        if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                        {
                            Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                        }
                    }
                    catch (Exception)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }

                    // Get DB context.
                    DataContext _db = new DataContext();

                    // Add order to DB.
                    _db.Orders.Add(myOrder);
                    _db.SaveChanges();

                    // Get the shopping cart items and process them.
                    using (talker.logic.ShoppingCartActions usersShoppingCart = new talker.logic.ShoppingCartActions())
                    {
                        List<CartItem> myOrderList = usersShoppingCart.GetCartItems();

                        // Add OrderDetail information to the DB for each product purchased.
                        for (int i = 0; i < myOrderList.Count; i++)
                        {
                            // Create a new OrderDetail object.
                            var myOrderDetail = new OrderDetail();
                            myOrderDetail.OrderId = myOrder.OrderId;
                            myOrderDetail.Username = User.Identity.Name;
                            myOrderDetail.ProductId = myOrderList[i].DiscussionId;
                            myOrderDetail.Quantity = 1;
                            myOrderDetail.UnitPrice = myOrderList[i].Discussion.TransactionAmount;

                            // Add OrderDetail to DB.
                            _db.OrderDetails.Add(myOrderDetail);
                            _db.SaveChanges();
                        }

                        // Set OrderId.
                        Session["currentOrderId"] = myOrder.OrderId;

                        // Display Order information.
                        List<Order> orderList = new List<Order>();
                        orderList.Add(myOrder);
                        ShipInfo.DataSource = orderList;
                        ShipInfo.DataBind();

                        // Display OrderDetails.
                        OrderItemList.DataSource = myOrderList;
                        OrderItemList.DataBind();
                    }
                }
                else
                {
                    Response.Redirect("CheckoutError.aspx?" + retMsg);
                }
            }
        }
        public ActionResult PaymentInfo()
        {
            var model = new PaymentSagePayServerModel();

            //First validate if this is the response of failed transaction (Status INVALID)
            var StatusDetail = Request.QueryString["StatusDetail"];

            if (StatusDetail != null)
            {
                model.Warnings.Add(StatusDetail);
                return View("Nop.Plugin.Payments.SagePayServer.Views.PaymentSagePayServer.PaymentInfo", model);
            }

            var webClient = new WebClient();

            var data = new NVPCodec();

            data.Add("VPSProtocol", SagePayHelper.GetProtocol());
            data.Add("TxType", _sagePayServerPaymentSettings.TransactType);
            data.Add("Vendor", _sagePayServerPaymentSettings.VendorName.ToLower());

            var orderGuid = Guid.NewGuid();

            data.Add("VendorTxCode", orderGuid.ToString());

            if (!String.IsNullOrWhiteSpace(_sagePayServerPaymentSettings.PartnerID))
                data.Add("ReferrerID", _sagePayServerPaymentSettings.PartnerID);

            var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            
            decimal? shoppingCartTotalBase = _orderTotalCalculationService.GetShoppingCartTotal(cart);

            var OrderTotal = shoppingCartTotalBase.GetValueOrDefault();

            data.Add("Amount", OrderTotal.ToString("F2", CultureInfo.InvariantCulture));

            if (_workContext.WorkingCurrency != null)
                data.Add("Currency", _workContext.WorkingCurrency.CurrencyCode);
            else if (_workContext.CurrentCustomer.CurrencyId.HasValue && _workContext.CurrentCustomer.Currency != null)
                data.Add("Currency", _workContext.CurrentCustomer.Currency.CurrencyCode);
            else
                data.Add("Currency", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);                        

            data.Add("Description", "DescriptionText");

            // The Notification URL is the page to which Server calls back when a transaction completes

            var notificationUrl = _sagePayServerPaymentSettings.NotificationFullyQualifiedDomainName;

            data.Add("NotificationURL", notificationUrl + "Plugins/PaymentSagePayServer/NotificationPage");

            // Billing Details
            data.Add("BillingSurname", _workContext.CurrentCustomer.BillingAddress.LastName);
            data.Add("BillingFirstnames", _workContext.CurrentCustomer.BillingAddress.FirstName);
            data.Add("BillingAddress1", _workContext.CurrentCustomer.BillingAddress.Address1);

            if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.BillingAddress.Address2))
                data.Add("BillingAddress2", _workContext.CurrentCustomer.BillingAddress.Address2);

            data.Add("BillingCity", _workContext.CurrentCustomer.BillingAddress.City);
            data.Add("BillingPostCode", _workContext.CurrentCustomer.BillingAddress.ZipPostalCode);
            data.Add("BillingCountry", _workContext.CurrentCustomer.BillingAddress.Country.TwoLetterIsoCode); //TODO: Verify if it is ISO 3166-1 country code

            if (_workContext.CurrentCustomer.BillingAddress.StateProvince != null)
                data.Add("BillingState", _workContext.CurrentCustomer.BillingAddress.StateProvince.Abbreviation);

            if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.BillingAddress.PhoneNumber))
                data.Add("BillingPhone", _workContext.CurrentCustomer.BillingAddress.PhoneNumber);


            // Delivery Details
            if (_workContext.CurrentCustomer.ShippingAddress != null)
            {
                data.Add("DeliverySurname", _workContext.CurrentCustomer.ShippingAddress.LastName);
                data.Add("DeliveryFirstnames", _workContext.CurrentCustomer.ShippingAddress.FirstName);
                data.Add("DeliveryAddress1", _workContext.CurrentCustomer.ShippingAddress.Address1);

                if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.ShippingAddress.Address2))
                    data.Add("DeliveryAddress2", _workContext.CurrentCustomer.ShippingAddress.Address2);

                data.Add("DeliveryCity", _workContext.CurrentCustomer.ShippingAddress.City);
                data.Add("DeliveryPostCode", _workContext.CurrentCustomer.ShippingAddress.ZipPostalCode);

                if (_workContext.CurrentCustomer.ShippingAddress.Country != null)
                {
                    data.Add("DeliveryCountry", _workContext.CurrentCustomer.ShippingAddress.Country.TwoLetterIsoCode);
                }

                if (_workContext.CurrentCustomer.ShippingAddress.StateProvince != null)
                    data.Add("DeliveryState", _workContext.CurrentCustomer.ShippingAddress.StateProvince.Abbreviation);

                if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.ShippingAddress.PhoneNumber))
                    data.Add("DeliveryPhone", _workContext.CurrentCustomer.ShippingAddress.PhoneNumber);

            }
            else {
                //Thanks to 'nomisit' for pointing this out. http://www.nopcommerce.com/p/258/sagepay-server-integration-iframe-and-redirect-methods.aspx
                data.Add("DeliverySurname", "");
                data.Add("DeliveryFirstnames", "");
                data.Add("DeliveryAddress1", "");
                data.Add("DeliveryAddress2", "");
                data.Add("DeliveryCity", "");
                data.Add("DeliveryPostCode", "");
                data.Add("DeliveryCountry", "");
                data.Add("DeliveryState", "");
                data.Add("DeliveryPhone", "");
            }

            data.Add("CustomerEMail", _workContext.CurrentCustomer.Email);

            //var strBasket = String.Empty;
            //strBasket = cart.Count + ":";

            //for (int i = 0; i < cart.Count; i++)
            //{
            //    ShoppingCartItem item = cart[i];
            //    strBasket += item.ProductVariant.FullProductName) + ":" +
            //                    item.Quantity + ":" + item.ProductVariant.Price + ":" +
            //                    item.ProductVariant.TaxCategoryId;
            //};

            //data.Add("Basket", strBasket);

            data.Add("AllowGiftAid", "0");

            // Allow fine control over AVS/CV2 checks and rules by changing this value. 0 is Default
            if (_sagePayServerPaymentSettings.TransactType != "AUTHENTICATE") data.Add("ApplyAVSCV2", "0");

            // Allow fine control over 3D-Secure checks and rules by changing this value. 0 is Default
            data.Add("Apply3DSecure", "0");

            if (String.Compare(_sagePayServerPaymentSettings.Profile, "LOW", true) == 0)
            {
                data.Add("Profile", "LOW"); //simpler payment page version.
            }

            var postURL = SagePayHelper.GetSageSystemUrl(_sagePayServerPaymentSettings.ConnectTo, "purchase");

            string strResponse = string.Empty;

            try
            {

                Byte[] responseData = webClient.UploadValues(postURL, data);

                strResponse = Encoding.ASCII.GetString(responseData);


            }
            catch (WebException ex)
            {

                return Content(String.Format(
                    @"Your server was unable to register this transaction with Sage Pay.
                    Check that you do not have a firewall restricting the POST and 
                    that your server can correctly resolve the address {0}. <br/>
                    The Status Number is: {1}<br/>
                    The Description given is: {2}", postURL, ex.Status, ex.Message));

            }

            if (string.IsNullOrWhiteSpace(strResponse))
                return Content(String.Format(
                    @"Your server was unable to register this transaction with Sage Pay.
                    Check that you do not have a firewall restricting the POST and 
                    that your server can correctly resolve the address {0}.", postURL));

            var strStatus = SagePayHelper.FindField("Status", strResponse);
            var strStatusDetail = SagePayHelper.FindField("StatusDetail", strResponse);

            switch (strStatus)
            {
                case "OK":

                    var strVPSTxId = SagePayHelper.FindField("VPSTxId", strResponse);
                    var strSecurityKey = SagePayHelper.FindField("SecurityKey", strResponse);
                    var strNextURL = SagePayHelper.FindField("NextURL", strResponse);

                    var transx = new SagePayServerTransaction()
                    {
                        CreatedOnUtc = DateTime.UtcNow,
                        VPSTxId = strVPSTxId,
                        SecurityKey = strSecurityKey,
                        NotificationResponse = strResponse,
                        VendorTxCode = orderGuid.ToString()
                    };

                    //Store this record in DB
                    _sagePayServerTransactionService.InsertSagePayServerTransaction(transx);
                   
                    
                    ViewBag.UseOnePageCheckout = UseOnePageCheckout();

                    if (_sagePayServerPaymentSettings.Profile == SagePayServerPaymentSettings.ProfileValues.LOW || ViewBag.UseOnePageCheckout)
                    {//Iframe
                        model.FrameURL = strNextURL;

                        return View("Nop.Plugin.Payments.SagePayServer.Views.PaymentSagePayServer.PaymentInfo", model);
                    }
                    else {
                        HttpContext.Response.Redirect(strNextURL);
                        HttpContext.Response.End();

                        return null;
                    }


                case "MALFORMED":
                    return Content(string.Format("Error ({0}: {1}) <br/> {2}", strStatus, strStatusDetail, data.Encode()));

                case "INVALID":
                    return Content(string.Format("Error ({0}: {1}) <br/> {2}", strStatus, strStatusDetail, data.Encode()));

                default:
                    return Content(string.Format("Error ({0}: {1})", strStatus, strStatusDetail));

            }

        }
Example #56
0
    protected void Page_Load(object sender, EventArgs e)
    {
        double subTotal = 0;
        double total = 0;
        double shipping = 00;

        if (!IsPostBack)
        {
            NVPAPICaller payPalCaller = new NVPAPICaller();

            string retMsg = "";
            string token = "";
            string PayerID = "";
            string foreName = "";
            string surName = "";
            string email = "";
            string address = "";
            string postcode = "";
            string town = "";

            NVPCodec decoder = new NVPCodec();
            token = Session["token"].ToString();

            bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
            if (ret)
            {

                //get user information from papal
                Session["payerId"] = PayerID;

                foreName = decoder["FIRSTNAME"].ToString();
                surName = decoder["LASTNAME"].ToString();
                address = decoder["SHIPTOSTREET"].ToString();
                town = decoder["SHIPTOCITY"].ToString();
                postcode = decoder["SHIPTOZIP"].ToString();
                email = decoder["EMAIL"].ToString();

                //display user information
                lblFore.Text = foreName;
                lblSur.Text = surName;
                lblCity.Text = town;
                lblEmail.Text = email;
                lblPostCode.Text = postcode;
                lblAddress.Text = address;

                //set customer object with information from paypal
                Customer aCustomer = (Customer)Session["Customer"];
                aCustomer.CityAddress = town;
                aCustomer.Email = email;
                aCustomer.FName = foreName;
                aCustomer.SName = surName;
                aCustomer.StreetAddress = address;
                aCustomer.PostCode = postcode;

                // Verify total payment amount as set on CheckoutStart.aspx.
                try
                {
                    decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                    decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                    shipping = Convert.ToDouble(decoder["SHIPPINGAMT"].ToString());
                    if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                    {
                        Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                    }
                }
                catch (Exception)
                {
                    Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
                }

                // Display Order information.

                var query = from goods in aCustomer.Orders[0].OrderLines
                            select new
                            {
                                Name = goods.Product.ProdName,
                                Description = goods.Product.ProdDescription,
                                Price = goods.Product.ProdPrice,
                                Qty = goods.Quantity,
                                Total = "£" + Convert.ToString(goods.Quantity * goods.Product.ProdPrice),
                                ProdImage = goods.Product.ProdImage
                            };

                GridView1.DataSource = query;
                GridView1.DataBind();

                subTotal = CartFunctions.getSubTotal(aCustomer);

                cellSub.Text = "£" + Convert.ToString(subTotal);
                total = subTotal + shipping;
                cellTotal.Text = "£" + total;
                cellShipping.Text = shipping.ToString();

            }
            else
            {
                Response.Redirect("CheckoutError.aspx?" + retMsg);
            }
        }
    }
Example #57
0
    /// <summary>
    /// DirectPayment: The method for credit card payment
    /// </summary>
    /// Note:
    ///	There are other optional inputs for credit card processing that are not presented here.
    ///		For a complete list of inputs available, please see the documentation here for US and UK:
    ///		https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_PayflowPro_Guide.pdf
    ///		https://cms.paypal.com/cms_content/GB/en_GB/files/developer/PP_WebsitePaymentsPro_IntegrationGuide_UK.pdf
    /// <param name="amt"></param>
    /// <param ref name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool DirectPayment(string paymentType, string paymentAmount, string creditCardType, string creditCardNumber, string expDate, string cvv2, string firstName, string lastName, string street, string city, string state, string zip, string countryCode, string currencyCode, string orderdescription, ref NVPCodec decoder, ref string retMsg)
    {
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
        }

        NVPCodec encoder = new NVPCodec();
        encoder["TENDER"] = "C";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }
        encoder["ACCT"]				= creditCardNumber;
        encoder["CVV2"]				= cvv2;
        encoder["EXPDATE"]			= expDate;
        encoder["ACCTTYPE"]			= creditCardType;
        encoder["AMT"]				= paymentAmount;
        encoder["CURRENCY"]			= currencyCode;
        encoder["FIRSTNAME"]		= firstName;
        encoder["LASTNAME"]			= lastName;
        encoder["STREET"]			= street;
        encoder["CITY"]				= city;
        encoder["STATE"]			= state;
        encoder["ZIP"]				= zip;
        encoder["COUNTRY"]			= countryCode;
        // unique request ID
        System.Guid uid = System.Guid.NewGuid();
        encoder["INVNUM"]			= uid.ToString();
        encoder["ORDERDESC"]		= orderdescription;
        encoder["VERBOSITY"]		= "MEDIUM";

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall(pStrrequestforNvp,uid.ToString());

        decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();
        if (strAck != null && strAck == "0")
        {
            return true;
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                "Desc=" + decoder["RESPMSG"];

            return false;
        }
    }
Example #58
0
    /// <summary>
    /// MarkExpressCheckout: The method that calls SetExpressCheckout, invoked from the 
    /// Billing Page EC placement
    /// </summary>
    /// <param name="amt"></param>
    /// <param ref name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool MarkExpressCheckout(string amt, 
                        string shipToName, string shipToStreet, string shipToStreet2,
                        string shipToCity, string shipToState, string shipToZip, 
                        string shipToCountryCode, ref string token, ref string retMsg)
    {
        string host = "www.paypal.com";
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
            host = "www.sandbox.paypal.com";
        }

        string returnURL = "http://www.careerjudge.com/FJAHome.aspx";
        string cancelURL = "https://www.novasoftindia.com";

        NVPCodec encoder = new NVPCodec();
        encoder["TENDER"] = "P";
        encoder["ACTION"] = "S";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }
        encoder["RETURNURL"] = returnURL;
        encoder["CANCELURL"] = cancelURL;
        encoder["AMT"] = amt;
        encoder["CURRENCY"]  = "USD";

        //Optional Shipping Address entered on the merchant site
        encoder["SHIPTOSTREET"]     = shipToStreet;
        encoder["SHIPTOSTREET2"]    = shipToStreet2;
        encoder["SHIPTOCITY"]       = shipToCity;
        encoder["SHIPTOSTATE"]      = shipToState;
        encoder["SHIPTOZIP"]        = shipToZip;
        encoder["SHIPTOCOUNTRY"]	= shipToCountryCode;
        encoder["ADDROVERRIDE"]		= "1";

        // unique request ID
        System.Guid uid = System.Guid.NewGuid();

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall(pStrrequestforNvp,uid.ToString());

        NVPCodec decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();
        if (strAck != null && strAck == "0")
        {
            token = decoder["TOKEN"];

            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + "token=" + token;

            retMsg = ECURL;
            return true;
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                "Desc=" + decoder["RESPMSG"];

            return false;
        }
    }
Example #59
0
    /// <summary>
    /// Credentials added to the NVP string
    /// </summary>
    /// <param name="profile"></param>
    /// <returns></returns>
    private string buildCredentialsNVPString()
    {
        NVPCodec codec = new NVPCodec();

        if (!IsEmpty(APIUser))
            codec["USER"] = APIUser;

        if (!IsEmpty(APIPassword))
            codec[PWD] = APIPassword;

        if (!IsEmpty(APIVendor))
            codec[VENDOR] = APIVendor;

        if (!IsEmpty(APIPartner))
            codec[PARTNER] = APIPartner;

        return codec.Encode();
    }
Example #60
0
    /// <summary>
    /// ShortcutExpressCheckout: The shortcut implementation of SetExpressCheckout
    /// </summary>
    /// <param name="amt"></param>
    /// <param ref name="token"></param>
    /// <param ref name="retMsg"></param>
    /// <returns></returns>
    public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
    {
        string host = "www.paypal.com";
        if (Env == "pilot")
        {
            pendpointurl = "https://pilot-payflowpro.paypal.com";
            host = "www.sandbox.paypal.com";
        }

        string returnURL = "http://www.careerjudge.com/FJAHome.aspx";
        string cancelURL = "https://www.novasoftindia.com";

        NVPCodec encoder = new NVPCodec();

        encoder["TENDER"] = "P";
        encoder["ACTION"] = "S";
        if ("Authorization" == "Sale")
        {
            encoder["TRXTYPE"] = "A";
        }
        else /* sale */
        {
            encoder["TRXTYPE"] = "S";
        }
        encoder["RETURNURL"] = returnURL;
        encoder["CANCELURL"] = cancelURL;
        encoder["AMT"] = amt;
        encoder["CURRENCY"] = "USD";

        // unique request ID
        System.Guid uid = System.Guid.NewGuid();

        string pStrrequestforNvp = encoder.Encode();
        string pStresponsenvp = HttpCall(pStrrequestforNvp,uid.ToString());

        NVPCodec decoder = new NVPCodec();
        decoder.Decode(pStresponsenvp);

        string strAck = decoder["RESULT"].ToLower();
        if (strAck != null && strAck == "0")
        {
            token = decoder["TOKEN"];

            string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + "token=" + token;

            retMsg = ECURL;
            return true;
        }
        else
        {
            retMsg = "ErrorCode=" + strAck + "&" +
                "Desc=" + decoder["RESPMSG"];

            return false;
        }
    }