public override TransactionInfo ProcessSubscription(ref SubscriptionInfo sub, GatewayInfo gateway, GatewayTypeInfo gatewayType, ICustomer customer, CreditCardInfo card, bool isTrial, bool testTransaction)
        {
            ProPayRequest request = null;
            ProPayResponse response = null;
            TransactionInfo transactionInfo = new TransactionInfo();

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;
            decimal amount = isTrial == true ? sub.TrialAmount : sub.Amount;

            request = new ProPayRequest(requestUrl, loginId, transactionKey, customer, card, amount, testTransaction);
            response = request.Process();


            sub.LastProcessedDate = DateTime.Now;

            transactionInfo.Id = Guid.NewGuid();
            transactionInfo.SubscriptionId = sub.Id;
            transactionInfo.GatewayId = sub.GatewayId;
            transactionInfo.CreateDate = DateTime.Now;
            transactionInfo.IsTrial = isTrial;
            transactionInfo.Type = TransactionType.Standard;
            transactionInfo.Amount = amount;
            transactionInfo.GatewayAmount = gateway.TransactionFee;
            transactionInfo.OrderId = sub.RefId;
            if (response == null)
            {
                sub.LastProcessingStatus = TransactionStatus.Error;
                transactionInfo.ResponseText = "";
                transactionInfo.Status = TransactionStatus.Error;
            }
            else if (response.Code == ProPayResponseCode.Success)
            {
                sub.LastProcessingStatus = TransactionStatus.Approved;
                if (isTrial)
                    sub.TrialOccurrencesDone += 1;
                else
                    sub.TotalOccurrencesDone += 1;
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Approved;
            }
            else
            {
                sub.LastProcessingStatus = TransactionStatus.Error;
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Error;
            }
            return transactionInfo;
        }
 public override TransactionInfo PreAuthorize(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, decimal amount, bool testTransaction)
 {
     throw new NotImplementedException();
 }
 public override void Refund(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, string refID, TransactionInfo transaction, bool testTransaction)
 {
     throw new NotImplementedException();
 }
        public void Orders_CreateKlarnaOrder()
        {
            // Arrange
            var url     = Settings.MultiSafePayUrl;
            var apiKey  = Settings.ApiKey;
            var client  = new MultiSafepayClient(apiKey, url);
            var orderId = Guid.NewGuid().ToString();

            var orderRequest = OrderRequest.CreateDirectKlarnaOrder(orderId, "product description", 1210, "EUR",
                                                                    new PaymentOptions("http://example.com/notify", "http://example.com/success", "http://example.com/failed"),
                                                                    GatewayInfo.Klarna(new DateTime(1970, 07, 10), "male", "+31 (0)20 8500 500", "*****@*****.**"),
                                                                    new ShoppingCart
            {
                Items = new[]
                {
                    new ShoppingCartItem("10001", "Test Product", 10.0, 1, "EUR")
                }
            },
                                                                    new CheckoutOptions()
            {
                TaxTables = new TaxTables()
                {
                    DefaultTaxTable = new TaxTable()
                    {
                        Name  = "Default",
                        Rules = new[] { new TaxRateRule()
                                        {
                                            Rate = 0.21
                                        } },
                        ShippingTaxed = false
                    }
                }
            },
                                                                    new Customer()
            {
                FirstName   = "Testperson-nl",
                LastName    = "Approved",
                HouseNumber = "1/XI",
                Address1    = "Neherkade",
                City        = "Gravenhage",
                Country     = "NL",
                PostCode    = "2521VA",
            },
                                                                    new DeliveryAddress()
            {
                FirstName   = "Testperson-nl",
                LastName    = "Approved",
                HouseNumber = "1/XI",
                Address1    = "Neherkade",
                City        = "Gravenhage",
                Country     = "NL",
                PostCode    = "2521VA",
            }
                                                                    );

            // Act
            var result = client.CreateOrder(orderRequest);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(orderRequest.OrderId, result.OrderId);
            Assert.IsTrue(result.PaymentUrl.StartsWith("http://example.com/success?transactionid=")); // redirect to success URL
        }
        public override TransactionInfo ProcessPayment(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, decimal amount, bool testTransaction)
        {
            ProPayRequest request = null;
            ProPayResponse response = null;
            TransactionInfo transactionInfo = new TransactionInfo();

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;

            request = new ProPayRequest(requestUrl, loginId, transactionKey, customer, card, amount, testTransaction);
            response = request.Process();



            transactionInfo.Id = Guid.NewGuid();
            transactionInfo.SubscriptionId = Guid.Empty;
            transactionInfo.GatewayId = gateway.Id;
            transactionInfo.CreateDate = DateTime.Now;
            //transactionInfo.IsTrial = ??;
            transactionInfo.Type = TransactionType.Standard;
            transactionInfo.Amount = amount;
            transactionInfo.GatewayAmount = gateway.TransactionFee;
            transactionInfo.OrderId = orderId;
            if (response == null)
            {
                transactionInfo.ResponseText = "";
                transactionInfo.Status = TransactionStatus.Error;
            }
            else if (response.Code == ProPayResponseCode.Success)
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Approved;
            }
            else
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Error;
            }
            return transactionInfo;
        }
Exemple #6
0
 public CodRequest(PayeeInfo payee, GatewayInfo gateway, TradeInfo trade)
 {
     this.orderId    = trade.OrderId;
     this.getGateway = gateway;
 }
        public void Order_CreateRedirectPayAfterDelivery_SetsRequiredProperties()
        {
            // Act
            var order = OrderRequest.CreateRedirectPayAfterDeliveryOrder("orderid", "description", 1000, "EUR",
                                                                         new PaymentOptions("notificationUrl", "successRedirectUrl", "cancelRedirectUrl"),
                                                                         GatewayInfo.PayAfterDelivery(new DateTime(1986, 08, 31), "NL39 RABO 0300 0652 64", "+31 (0)20 8500 500", "*****@*****.**", "referrer", "useragent"),
                                                                         new ShoppingCart
            {
                Items = new[]
                {
                    new ShoppingCartItem("Test Product", 10, 2, "EUR"),
                }
            },
                                                                         new CheckoutOptions()
            {
                TaxTables = new TaxTables()
                {
                    DefaultTaxTable = new TaxTable()
                    {
                        Name  = "Default",
                        Rules = new[] { new TaxRateRule()
                                        {
                                            Rate = 0.21
                                        } },
                        ShippingTaxed = false
                    }
                }
            },
                                                                         new Customer
            {
                FirstName   = "John",
                LastName    = "Doe",
                HouseNumber = "39",
                Address1    = "Kraanspoor",
                City        = "Amsterdam",
                Country     = "NL",
                PostCode    = "1033SC"
            });

            // Assert
            Assert.IsNotNull(order.Type);
            Assert.IsNotNull(order.GatewayId);
            Assert.IsNotNull(order.OrderId);
            Assert.IsNotNull(order.CurrencyCode);
            Assert.IsNotNull(order.AmountInCents);
            Assert.IsNotNull(order.Description);
            Assert.IsNotNull(order.GatewayInfo);
            Assert.IsNotNull(order.GatewayInfo.Birthday);
            Assert.IsNotNull(order.GatewayInfo.BankAccount);
            Assert.IsNotNull(order.GatewayInfo.Phone);
            Assert.IsNotNull(order.GatewayInfo.Email);
            Assert.IsNotNull(order.GatewayInfo.Referrer);
            Assert.IsNotNull(order.GatewayInfo.UserAgent);
            Assert.IsNotNull(order.PaymentOptions);
            Assert.IsNotNull(order.PaymentOptions.NotificationUrl);
            Assert.IsNotNull(order.PaymentOptions.SuccessRedirectUrl);
            Assert.IsNotNull(order.PaymentOptions.CancelRedirectUrl);
            Assert.IsNotNull(order.ShoppingCart);
            Assert.IsNotNull(order.ShoppingCart.Items);
            Assert.IsNotNull(order.ShoppingCart.Items[0]);
            Assert.IsNotNull(order.ShoppingCart.Items[0].Name);
            Assert.IsNotNull(order.ShoppingCart.Items[0].UnitPrice);
            Assert.IsNotNull(order.ShoppingCart.Items[0].Quantity);
            Assert.IsNotNull(order.Customer);
            Assert.IsNotNull(order.Customer.FirstName);
            Assert.IsNotNull(order.Customer.LastName);
            Assert.IsNotNull(order.Customer.Address1);
            Assert.IsNotNull(order.Customer.HouseNumber);
            Assert.IsNotNull(order.Customer.City);
            Assert.IsNotNull(order.Customer.Country);


            Assert.AreEqual(OrderType.Redirect, order.Type);
            Assert.AreEqual("PAYAFTER", order.GatewayId);
            Assert.AreEqual("orderid", order.OrderId);
            Assert.AreEqual("EUR", order.CurrencyCode);
            Assert.AreEqual(1000, order.AmountInCents);
            Assert.AreEqual("description", order.Description);
            Assert.AreEqual(new DateTime(1986, 8, 31), order.GatewayInfo.Birthday);
            Assert.AreEqual("NL39 RABO 0300 0652 64", order.GatewayInfo.BankAccount);
            Assert.AreEqual("+31 (0)20 8500 500", order.GatewayInfo.Phone);
            Assert.AreEqual("*****@*****.**", order.GatewayInfo.Email);
            Assert.AreEqual("referrer", order.GatewayInfo.Referrer);
            Assert.AreEqual("useragent", order.GatewayInfo.UserAgent);
            Assert.AreEqual("notificationUrl", order.PaymentOptions.NotificationUrl);
            Assert.AreEqual("successRedirectUrl", order.PaymentOptions.SuccessRedirectUrl);
            Assert.AreEqual("cancelRedirectUrl", order.PaymentOptions.CancelRedirectUrl);
            Assert.AreEqual("Test Product", order.ShoppingCart.Items[0].Name);
            Assert.AreEqual(10, order.ShoppingCart.Items[0].UnitPrice);
            Assert.AreEqual(2, order.ShoppingCart.Items[0].Quantity);
            Assert.AreEqual("John", order.Customer.FirstName);
            Assert.AreEqual("Doe", order.Customer.LastName);
            Assert.AreEqual("Kraanspoor", order.Customer.Address1);
            Assert.AreEqual("39", order.Customer.HouseNumber);
            Assert.AreEqual("Amsterdam", order.Customer.City);
            Assert.AreEqual("NL", order.Customer.Country);
        }
Exemple #8
0
 public abstract void VerifyNotify(int timeout, PayeeInfo payee, GatewayInfo gateway);
Exemple #9
0
        public override void VerifyNotify(int timeout, PayeeInfo payee, GatewayInfo gateway)
        {
            bool flag;

            try
            {
                flag = bool.Parse(this.GetResponse(this.CreateUrl(payee), timeout));
            }
            catch
            {
                flag = false;
            }

            foreach (string tmpParameter in Core.Globals.AlipayOtherParamKeys)
            {
                if (!string.IsNullOrEmpty(tmpParameter))
                {
                    this.parameters.Remove(tmpParameter);
                }
            }
            string[] strArray2 = Globals.BubbleSort(this.parameters.AllKeys);
            string   s         = "";

            for (int i = 0; i < strArray2.Length; i++)
            {
                if ((!string.IsNullOrEmpty(this.parameters[strArray2[i]]) && (strArray2[i] != "sign")) && (strArray2[i] != "sign_type"))
                {
                    if (i == (strArray2.Length - 1))
                    {
                        s = s + strArray2[i] + "=" + this.parameters[strArray2[i]];
                    }
                    else
                    {
                        s = s + strArray2[i] + "=" + this.parameters[strArray2[i]] + "&";
                    }
                }
            }
            s = s + payee.PrimaryKey;
            if (flag && this.parameters["sign"].Equals(Globals.GetMD5(s, this.input_charset)))
            {
                string str2 = this.parameters["trade_status"];
                if (str2 != null)
                {
                    if (!(str2 == "WAIT_SELLER_SEND_GOODS"))
                    {
                        if (!(str2 == "TRADE_FINISHED"))
                        {
                            return;
                        }
                    }
                    else
                    {
                        this.OnPaidToIntermediary();
                        return;
                    }
                    this.OnPaidToMerchant();
                }
            }
            else
            {
                this.OnNotifyVerifyFaild();
            }
        }
Exemple #10
0
        /// <summary>
        /// This method returns a GatewayInfo object
        /// </summary>
        public static GatewayInfo GetGatewayInfo(string gatewayFilePath, List <string> methodNames)
        {
            // initial value
            GatewayInfo gatewayInfo = new GatewayInfo();

            // locals
            List <GatewayMethodInfo> methodInformation = new List <GatewayMethodInfo>();
            int  index                   = -1;
            bool methodRegionOn          = false;
            GatewayMethodInfo methodInfo = null;

            // Set the MethodInformation
            gatewayInfo.MethodInformation = methodInformation;

            // if the gatewayFilePath exists
            if ((TextHelper.Exists(gatewayFilePath)) && (File.Exists(gatewayFilePath)) && (ListHelper.HasOneOrMoreItems(methodNames)))
            {
                // Get the fileText
                string fileText = File.ReadAllText(gatewayFilePath);

                // If the fileText string exists
                if (TextHelper.Exists(fileText))
                {
                    // Parse the lines
                    List <TextLine> lines = WordParser.GetTextLines(fileText);

                    // If the lines collection exists and has one or more items
                    if (ListHelper.HasOneOrMoreItems(lines))
                    {
                        // set the lines
                        gatewayInfo.TextLines = lines;

                        // Iterate the collection of string objects
                        foreach (string methodName in methodNames)
                        {
                            // reset
                            methodRegionOn = false;
                            index          = -1;

                            // Iterate the collection of TextLine objects
                            foreach (TextLine line in lines)
                            {
                                // Increment the value for index
                                index++;

                                // Create a codeLine
                                CodeLine codeLine = new CodeLine(line.Text);

                                // if the TextLine exists
                                if (codeLine.HasTextLine)
                                {
                                    // Get the words for this line
                                    codeLine.TextLine.Words = WordParser.GetWords(line.Text);
                                }

                                // if the value for methodRegionOn is true
                                if (methodRegionOn)
                                {
                                    // if this is the
                                    if ((codeLine.IsEndRegion) && (NullHelper.Exists(methodInfo)))
                                    {
                                        // turn this off
                                        methodRegionOn = false;

                                        // Set the methodInfo
                                        methodInfo.EndIndex = index;

                                        // break out of the loop
                                        break;
                                    }
                                }
                                else
                                {
                                    // if this is a Region
                                    if (codeLine.IsRegion)
                                    {
                                        // if this is the method being sought
                                        if (methodName == codeLine.RegionName)
                                        {
                                            // set to true
                                            methodRegionOn = true;

                                            // Create a new instance of a 'MethodInfo' object.
                                            methodInfo = new GatewayMethodInfo();

                                            // Set the methodName
                                            methodInfo.Name = methodName;

                                            // Set the startIndex
                                            methodInfo.StartIndex = index;

                                            // Add this item
                                            methodInformation.Add(methodInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // return value
            return(gatewayInfo);
        }
        private async void Main_Load(object sender, EventArgs e)
        {
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                try
                {
                    lblVersion.Text = $"App Version: {ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(4)}";
                }
                catch { }
            }
            else
            {
                lblVersion.Text = $"App Version: {Application.ProductVersion}";
            }
            //preload colors combobox
            cmbColors.DisplayMember = "ColorName";
            //cmbColors.SelectedValueChanged += (s, ev) => cmbColors.SelectedText = s.ToString();
            cmbColors.ValueMember = "ColorId";
            //cmbColors.SelectedValueChanged += (s, ev) => cmbColors.SelectedText = s.ToString();
            foreach (FieldInfo p in typeof(TradfriColors).GetFields())
            {
                object v = p.GetValue(null); // static classes cannot be instanced, so use null...
                cmbColors.Items.Add(new { ColorName = p.Name, ColorId = v });
            }

            // prepare/load settings
            userData = loadUserData();

            if (string.IsNullOrWhiteSpace(Properties.Settings.Default.appSecret))
            {
                using (EnterGatewayPSK form = new EnterGatewayPSK(Properties.Settings.Default.gatewayName, Properties.Settings.Default.appName, Properties.Settings.Default.gatewayIp))
                {
                    DialogResult result = form.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        tradfriController = new TradfriController(form.GatewayName, form.IP);
                        // generating appSecret on gateway - appSecret is connected with the appName so you must use a combination
                        // Gateway generates one appSecret key per applicationName
                        TradfriAuth appSecret = tradfriController.GenerateAppSecret(form.AppSecret, Properties.Settings.Default.appName);
                        // saving programatically appSecret.PSK value to settings
                        Properties.Settings.Default.appSecret   = appSecret.PSK;
                        Properties.Settings.Default.gatewayName = form.GatewayName;
                        Properties.Settings.Default.gatewayIp   = form.IP;
                        Properties.Settings.Default.Save();
                    }
                    else if (result == DialogResult.Yes)
                    {
                        tradfriController = new TradfriController(form.GatewayName, form.IP);
                        // saving programatically appSecret.PSK value to settings
                        Properties.Settings.Default.appSecret   = form.AppSecret;
                        Properties.Settings.Default.gatewayName = form.GatewayName;
                        Properties.Settings.Default.gatewayIp   = form.IP;
                        Properties.Settings.Default.Save();
                    }
                    else
                    {
                        MessageBox.Show("You haven't entered your Gateway PSK so applicationSecret can't be generated on gateway." + Environment.NewLine +
                                        "You can also enter it manually into app.config if you have one for your app already.",
                                        "Error acquiring appSecret",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        this.Close();
                    }
                }
            }
            // initialize controller based on settings
            else
            {
                tradfriController = new TradfriController(Properties.Settings.Default.gatewayName, Properties.Settings.Default.gatewayIp);
            }

            // connection to gateway
            tradfriController.ConnectAppKey(Properties.Settings.Default.appSecret, Properties.Settings.Default.appName);
            GatewayInfo g = await tradfriController.GatewayController.GetGatewayInfo();

            lblGatewayVersion.Text += g.Firmware;
            lblGateway.Text        += Properties.Settings.Default.gatewayIp;

            List <TradfriDevice> devices = new List <TradfriDevice>(await tradfriController.GatewayController.GetDeviceObjects()).OrderBy(x => x.DeviceType.ToString()).ToList();
            List <TradfriDevice> lights  = devices.Where(i => i.DeviceType.Equals(DeviceType.Light)).ToList();
            List <TradfriGroup>  groups  = new List <TradfriGroup>(await tradfriController.GatewayController.GetGroupObjects()).OrderBy(x => x.Name).ToList();

            // set datasource for dgv
            dgvDevices.DataSource          = devices;
            dgvDevices.AutoGenerateColumns = true;

            // set datasource for dgv
            dgvGroups.DataSource          = groups;
            dgvGroups.AutoGenerateColumns = true;

            // temporary disable autosave on rowSelectionChange
            loadingSelectedRows = true;
            // clear default selection
            dgvDevices.ClearSelection();
            //reselect rows from settings
            if (userData.SelectedDevices.Count > 0 && devices.Count > 0)
            {
                foreach (DataGridViewRow row in dgvDevices.Rows)
                {
                    if (userData.SelectedDevices.Any(x => x == (long)row.Cells["ID"].Value))
                    {
                        row.Selected = true;
                    }
                }
            }
            // re-enable autosave on rowSelectionChange
            loadingSelectedRows = false;

            if (lights.Count > 0)
            {
                // acquire first and last lights from grid
                TradfriDevice firstLight = lights.FirstOrDefault();
                TradfriDevice lastLight  = lights.LastOrDefault();
                // function handler for observe events
                void ObserveLightEvent(TradfriDevice x)
                {
                    TradfriDevice eventDevice = devices.Where(d => d.ID.Equals(x.ID)).SingleOrDefault();

                    eventDevice = x;
                    if (dgvDevices.SelectedRows.Count > 0)
                    {
                        foreach (object item in dgvDevices.SelectedRows)
                        {
                            if (((TradfriDevice)((DataGridViewRow)item).DataBoundItem).ID.Equals(eventDevice.ID))
                            {
                                this.Invoke((MethodInvoker) delegate
                                {
                                    Debug.WriteLine($"{DateTime.Now} - triggered: {x.DeviceType}, {x.Name}, {x.LightControl[0].State}, {x.LightControl[0].Dimmer}");
                                    lbxLog.Items.Add($"{DateTime.Now} - triggered: {x.DeviceType}, {x.Name}, {x.LightControl[0].State}, {x.LightControl[0].Dimmer}");
                                    lbxLog.SelectedIndex = lbxLog.Items.Count - 1;
                                    trbBrightness.Value  = Convert.ToInt16(eventDevice.LightControl[0].Dimmer * (double)10 / 254);
                                });
                            }
                        }
                    }
                };

                ObserveLightDelegate lightDelegate = new ObserveLightDelegate(ObserveLightEvent);
                // observe first light from grid
                tradfriController.DeviceController.ObserveDevice(firstLight, x => lightDelegate(x));
                // observe last light from grid if the bulbs are different
                if (firstLight.ID != lastLight.ID)
                {
                    tradfriController.DeviceController.ObserveDevice(lastLight, x => lightDelegate(x));
                }
            }
        }
Exemple #12
0
    /// <summary>
    /// Refund button clicked
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Refund_Click(object sender, EventArgs e)
    {
        //retrieve order
        ZNode.Libraries.Admin.OrderAdmin orderAdmin = new ZNode.Libraries.Admin.OrderAdmin();
        Order order = orderAdmin.GetOrderByOrderID(OrderID);
        ZNode.Libraries.Framework.Business.ZNodeEncryption enc = new ZNode.Libraries.Framework.Business.ZNodeEncryption();

        //get payment settings
        int paymentSettingID = (int)order.PaymentSettingID;
        PaymentSettingService pss = new PaymentSettingService();
        PaymentSetting ps = pss.GetByPaymentSettingID(paymentSettingID);

        //set gateway info
        GatewayInfo gi = new GatewayInfo();
        gi.GatewayLoginID = enc.DecryptData(ps.GatewayUsername);
        gi.GatewayPassword = enc.DecryptData(ps.GatewayPassword);
        gi.TransactionKey = enc.DecryptData(ps.TransactionKey);
        gi.Vendor = ps.Vendor;
        gi.Partner = ps.Partner;
        //gi.CurrencyCode = CurrencyCode;
        gi.TestMode = ps.TestMode;
        gi.gateway = (GatewayType)ps.GatewayTypeID ;

        string creditCardExp = Convert.ToString(order.CardExp);
        if (creditCardExp == null)
        {
            creditCardExp = "";
        }

        //set credit card
        CreditCard cc = new CreditCard();
        cc.Amount = Decimal.Parse(txtAmount.Text);
        cc.CardNumber = txtCardNumber.Text.Trim();
        cc.CreditCardExp = creditCardExp;
        cc.OrderID = order.OrderID;
        cc.TransactionID = order.CardTransactionID;

        GatewayResponse resp = new GatewayResponse();

        if ((GatewayType)ps.GatewayTypeID == GatewayType.AUTHORIZE)
        {
            GatewayAuthorize auth = new GatewayAuthorize();
            resp = auth.RefundPayment(gi, cc);
        }
        else if ((GatewayType)ps.GatewayTypeID == GatewayType.VERISIGN)
        {
            GatewayPayFlowPro pp = new GatewayPayFlowPro();
            resp = pp.RefundPayment(gi, cc);
        }
        else if ((GatewayType)ps.GatewayTypeID == GatewayType.PAYMENTECH)
        {
            GatewayOrbital pmt = new GatewayOrbital();
            resp = pmt.ReversePayment(gi, cc);
        }
        else if ((GatewayType)ps.GatewayTypeID == GatewayType.IPCOMMERCE)
        {
            GatewayIPCommerce ipc = new GatewayIPCommerce();
            resp = ipc.RefundPayment(gi, cc);
        }
        else if ((GatewayType)ps.GatewayTypeID == GatewayType.NOVA)
        {
            GatewayNova nova = new GatewayNova();
            cc.CreditCardExp = lstMonth.SelectedValue + "/" + lstYear.SelectedValue;
            cc.CardSecurityCode = txtSecurityCode.Text.Trim();
            gi.TransactionType = "CCCredit";
            resp = nova.RefundPayment(gi, cc);
        }
        else
        {
            lblError.Text = "Error: Credit card refunds and not supported for your gateway.";
            return;
        }

        if (resp.IsSuccess)
        {
            //update order status
            order.OrderStateID = 30; //returned status
            order.PaymentStatusID = 3; //refund status

            OrderService os = new OrderService();
            os.Update(order);

            pnlEdit.Visible = false;
            pnlConfirm.Visible = true;
        }
        else
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("Could not complete request. The following response was returned by the gateway: ");
            sb.Append(resp.ResponseText);
            lblError.Text = sb.ToString();
        }
    }
Exemple #13
0
    /// <summary>
    /// Refund button clicked
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Capture_Click(object sender, EventArgs e)
    {
        //retrieve order
        ZNode.Libraries.Admin.OrderAdmin orderAdmin = new ZNode.Libraries.Admin.OrderAdmin();
        Order order = orderAdmin.GetOrderByOrderID(OrderID);
        ZNode.Libraries.Framework.Business.ZNodeEncryption enc = new ZNode.Libraries.Framework.Business.ZNodeEncryption();

        //get payment settings
        int paymentSettingID = (int)order.PaymentSettingID;
        PaymentSettingService pss = new PaymentSettingService();
        PaymentSetting ps = pss.GetByPaymentSettingID(paymentSettingID);

        //set gateway info
        GatewayInfo gi = new GatewayInfo();
        gi.GatewayLoginID = enc.DecryptData(ps.GatewayUsername);
        gi.GatewayPassword = enc.DecryptData(ps.GatewayPassword);
        gi.TransactionKey = enc.DecryptData(ps.TransactionKey);
        gi.Vendor = ps.Vendor;
        gi.Partner = ps.Partner;
        gi.TestMode = ps.TestMode;
        gi.gateway = (GatewayType)ps.GatewayTypeID ;

        string creditCardExp = Convert.ToString(order.CardExp);
        if (creditCardExp == null)
        {
            creditCardExp = "";
        }

        //set credit card
        CreditCard cc = new CreditCard();
        cc.CreditCardExp = creditCardExp;
        cc.OrderID = order.OrderID;
        cc.TransactionID = order.CardTransactionID;

        GatewayResponse resp = new GatewayResponse();

        if ((GatewayType)ps.GatewayTypeID == GatewayType.AUTHORIZE)
        {
            GatewayAuthorize auth = new GatewayAuthorize();
            resp = auth.CapturePayment(gi, cc);
        }
        else if ((GatewayType)ps.GatewayTypeID == GatewayType.VERISIGN)
        {
            GatewayPayFlowPro pp = new GatewayPayFlowPro();
            resp = pp.CapturePayment(gi, cc);
        }
        else if ((GatewayType)ps.GatewayTypeID == GatewayType.PAYMENTECH)
        {
            GatewayOrbital pmt = new GatewayOrbital();
            resp = pmt.CapturePayment(gi, cc);
        }
        else
        {
            lblError.Text = "Error: Credit card payment capture is not supported for your gateway.";

        }

        if (resp.IsSuccess)
        {
            //update order status
            order.PaymentStatusID = 1; //refund status

            OrderService os = new OrderService();
            os.Update(order);

            pnlEdit.Visible = false;
            pnlConfirm.Visible = true;
        }
        else
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("Could not complete request. The following response was returned by the gateway: ");
            sb.Append(resp.ResponseText);
            lblError.Text = sb.ToString();
        }
    }
        public virtual void ProcessRequest(HttpContext context)
        {
            //Safe
            if (!VerifySendPayment(context))
            {
                return;
            }

            //订单ID字符串
            string orderIdStr = string.Empty;

            //获取全部订单ID
            string[] orderIds = OrderProcessor.GetQueryString4OrderIds(context.Request, out orderIdStr);

            //订单ID NULL ERROR返回首页
            if (orderIds == null || orderIds.Length < 1)
            {
                //Add ErrorLog..
                HttpContext.Current.Response.Redirect("~/");
                return;
            }

            //合并支付 订单支付信息以第一份订单为主
            T orderInfo = Option.GetOrderInfo(orderIds[0]);

            if (orderInfo == null)
            {
                return;
            }

            //计算订单支付金额
            decimal totalMoney = this.GetOrderTotalMoney(orderIds, orderInfo);

            if (totalMoney < 0)
            {
                return;
            }

            if (orderInfo.PaymentStatus != PaymentStatus.NotYet)
            {
                //订单已支付
                context.Response.Write(
                    HttpContext.GetGlobalResourceObject("Resources", "IDS_ErrorMessage_SentPayment").ToString());
                return;
            }

            PaymentModeInfo paymentMode = GetPaymentMode(orderInfo);

            if (paymentMode == null || string.IsNullOrWhiteSpace(paymentMode.Gateway))
            {
                //订单历史的支付方式不存在
                context.Response.Write(
                    HttpContext.GetGlobalResourceObject("Resources", "IDS_ErrorMessage_NoPayment").ToString());
                return;
            }

            string getwayName = paymentMode.Gateway.ToLower();

            //获取支付网关
            GatewayProvider provider =
                PayConfiguration.GetConfig().Providers[getwayName] as GatewayProvider;

            if (provider == null)
            {
                return;
            }

            //支付网关
            GatewayInfo gatewayInfo = this.GetGateway(getwayName);

            //交易信息
            TradeInfo tradeInfo = this.GetTrade(orderIdStr, totalMoney, orderInfo);

            #region 测试模式
            //DONE: 测试模式埋点
            if (Globals.IsPaymentTestMode && !Globals.ExcludeGateway.Contains(getwayName.ToLower()))
            {
                System.Text.StringBuilder url = new System.Text.StringBuilder(gatewayInfo.ReturnUrl);
                url.AppendFormat("&out_trade_no={0}", tradeInfo.OrderId);
                url.AppendFormat("&total_fee={0}", tradeInfo.TotalMoney);
                url.AppendFormat("&sign={0}", Globals.GetMd5(System.Text.Encoding.UTF8, url.ToString()));
                HttpContext.Current.Response.Redirect(
                    gatewayInfo.ReturnUrl.Contains("?")
                        ? url.ToString()
                        : url.ToString().Replace("&out_trade_no", "?out_trade_no"), true);
                return;
            }
            #endregion

            #region 发送支付请求
            //发送支付请求
            PaymentRequest paymentRequest = PaymentRequest.Instance(
                provider.RequestType,
                this.GetPayee(paymentMode),
                gatewayInfo,
                tradeInfo
                );
            if (paymentRequest == null)
            {
                return;
            }
            paymentRequest.SendRequest();
            #endregion
        }
        public override void Refund(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, string refID, TransactionInfo transaction,
            bool testTransaction)
        {
            ANetRequest request = null;
            ANetResponse response = null;

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;

            request = new ANetRequest(requestUrl, loginId, transactionKey, customer, card, refID, transaction, testTransaction, transaction.Amount);
           
            response = request.ProcessRefund();

            if (response.Code == ANetResponseCode.Approved)
            {
                transaction.Status = TransactionStatus.Refunded;
            }
        }
        public override TransactionInfo PreAuthorize(GatewayInfo gateway, GatewayTypeInfo gatewayType, Guid orderId, ICustomer customer, CreditCardInfo card, decimal amount, bool testTransaction)
        {
            ANetRequest request = null;
            ANetResponse response = null;
            TransactionInfo transactionInfo = new TransactionInfo();

            string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl;
            string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId;
            string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey;

            request = new ANetRequest(requestUrl, loginId, transactionKey, customer, card, amount, testTransaction);
            response = request.ProcessAuthOnly();

            transactionInfo.Id = Guid.NewGuid();
            //transactionInfo.CustomerName = System.Web.Security.Membership.GetUser(customer.ID).UserName;
            transactionInfo.SubscriptionId = Guid.Empty;
            transactionInfo.GatewayId = gateway.Id;
            transactionInfo.CreateDate = DateTime.Now;
            //transactionInfo.IsTrial = ??;
            transactionInfo.Type = TransactionType.Standard;
            transactionInfo.Amount = amount;
            transactionInfo.GatewayAmount = gateway.TransactionFee;
            transactionInfo.OrderId = orderId;
            if (response == null)
            {
                transactionInfo.ResponseText = "";
                transactionInfo.Status = TransactionStatus.Error;
            }
            else if (response.Code == ANetResponseCode.Approved)
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Approved;
            }
            else
            {
                transactionInfo.ResponseText = response.ResponseText;
                transactionInfo.Status = TransactionStatus.Error;
            }
            return transactionInfo;
        }