A
download Checkout.ascx.cs
Language: C#
LOC: 475
Project Info
commercefinity - An open source eCommerce ...odule(commercefinity)
Server: Google
Type: svn
...runk\Commerce\PageControls\
   AddItemResult.ascx
   AddItemResult.ascx.cs
   Catalog.ascx
   Catalog.ascx.cs
   Checkout.ascx
   Checkout.ascx.cs
   MyOrders.ascx
   MyOrders.ascx.cs
   PPCheckout.ascx
   PPCheckout.ascx.cs
   Product.ascx
   Product.ascx.cs
   Receipt.ascx
   Receipt.ascx.cs
   ShoppingBasket.ascx
   ShoppingBasket.ascx.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Commerce.Common;
using Commerce.Providers;
using Commerce.PayPal;
using Telerik.Security;

public partial class Commerce_PageControls_Checkout : System.Web.UI.UserControl
{
    protected Order currentOrder = null;

    void ValidatePage()
    {
        //Page Validation
        //1) Need items in order to checkout
        try
        {
            TestCondition.IsTrue(currentOrder.Items.Count > 0, "There are not items in your cart");
        }
        catch
        {
            //send them to the basket page
            Response.Redirect("basket.aspx", false);
        }


        //2) Need to have this page under SSL!
        //Utility.TestForSSL();



    }
    protected void Page_Load(object sender, EventArgs e)
    {

        //show the panels according to payment settings
        pnlPPStandard.Visible = SiteConfig.UsePayPalPaymentsStandard;
        pnlExpressCheckout.Visible = SiteConfig.UsePayPalExpressCheckout;
        wizCheckout.Visible = SiteConfig.AcceptCreditCards;
        pnlNav.Visible = SiteConfig.AcceptCreditCards;

        //pull the order from the ViewState or DB as needed
        currentOrder = GetCurrentOrder();

        //make sure the page is valid
        ValidatePage();

        //turn the submit button off when they submit the order. This prevents double (or more) orders
        this.btnComplete.Attributes.Add("onclick", "this.value='Please wait...';this.disabled = true;" + Page.ClientScript.GetPostBackEventReference(this.btnComplete, ""));
        if (!Page.IsPostBack)
        {

            //check to see if they require a login
            if (SiteConfig.RequireLogin == "checkout")
            {
                if (!Page.User.Identity.IsAuthenticated)
                    Response.Redirect("~/login.aspx?ReturnUrl=checkout.aspx", true);
            }

            //Check to make sure the site accept's credit cards
            if (SiteConfig.AcceptCreditCards)
            {

                LoadShippingList();

                //default the addresses
                if (Profile.LastShippingAddress != null)
                    SetAddressEntry("addShipping", Profile.LastShippingAddress);
                if (Profile.LastBillingAddress != null)
                    SetAddressEntry("addBilling", Profile.LastBillingAddress);

                //this is the package info for UPS/USPS
                //PackageInfo package = LoadPackage();
                //BindShipping(package);


                //check the URL for a return from PayPal using Express Checkout
                if (Utility.GetParameter("token") != string.Empty)
                {
                    //get the info from PayPal about this buyer
                    //and populate the addresses,etc
                    ProcessExpressReturn(Utility.GetParameter("token"));

                    //load the final wizard screen
                    wizCheckout.MoveTo(wizCheckout.WizardSteps[2]);
                }
            }
            else
            {
                //it's PP Standard only
                //redirect to the PP Standard checkout page
                Response.Redirect("CheckoutPPStandard.aspx", true);

            }

        }
        SetOrderInfo();
    }

    Order GetCurrentOrder()
    {
        Order result = null;
        if (ViewState["CurrentOrder"] != null)
        {
            result = (Order)ViewState["CurrentOrder"];
        }
        else
        {
            result = OrderController.GetCurrentOrder();
        }
        return result;
    }
    void SetOrderInfo()
    {

        RadioButtonList radShipChoices = (RadioButtonList)wizCheckout.FindControl("radShipChoices");
        if (radShipChoices != null)
        {
            currentOrder.ShippingAmount = Profile.CurrentOrderShipping;
            currentOrder.ShippingMethod = Profile.CurrentOrderShippingMethod;
        }
        //these are set by the wizard in steps 1 & 2
        currentOrder.ShippingAddress = addShipping.SelectedAddress;
        currentOrder.BillingAddress = addBilling.SelectedAddress;

        //put them to HTML string for display to our admins
        currentOrder.ShipToAddress = addShipping.SelectedAddress.ToHtmlString();
        currentOrder.BillToAddress = addBilling.SelectedAddress.ToHtmlString();

        //need a phone for shipping address
        currentOrder.ShipPhone = addShipping.SelectedAddress.Phone;

        //see if this is an ExpressCheckout order
        //if it is, then we need to put the Checkout Tokens into the Billing Address
        if (ViewState["ppToken"] != null && ViewState["ppID"] != null)
        {
            currentOrder.BillingAddress.PayPalPayerID = ViewState["ppID"].ToString();
            currentOrder.BillingAddress.PayPalToken = ViewState["ppToken"].ToString();

        }



        if (radShipChoices.Items.Count > 0)
        {
            currentOrder.ShippingAmount = decimal.Parse(radShipChoices.SelectedValue);
            currentOrder.ShippingMethod = radShipChoices.SelectedItem.Text;
        }
        //tax is stored in the Profile for this order
        currentOrder.TaxAmount = Profile.CurrentOrderTax;

        //pull the CC info from the PaymentBox
        currentOrder.CreditCardNumber = PaymentBox1.CCNumber;
        currentOrder.CreditCardExpireMonth = PaymentBox1.ExpirationMonth;
        currentOrder.CreditCardExpireYear = PaymentBox1.ExpirationYear;
        currentOrder.CreditCardSecurityNumber = PaymentBox1.SecurityCode;
        currentOrder.CreditCardType = PaymentBox1.CCType;

        if (currentOrder.BillingAddress != null)
        {
            currentOrder.FirstName = currentOrder.BillingAddress.FirstName;
            currentOrder.LastName = currentOrder.BillingAddress.LastName;
            currentOrder.Email = currentOrder.BillingAddress.Email;
        }

        //check to see if there's been a coupon applied
        //if there has, un-enable the coupons
        //change this as your business dicates
        if (!string.IsNullOrEmpty(currentOrder.CouponCodes))
        {
            couponMessage.Text = currentOrder.CouponCodes + " has already been applied to this order. You must empty your basket to remove the coupon.";
            couponCode.Enabled = false;
            applyCoupon.Enabled = false;
        }

        //put the order in the ViewState to spare our DB
        ViewState["CurrentOrder"] = currentOrder;
    }


    #region Addressing
    void SetAddressEntry(string controlName, Address address)
    {
        AddressEntry addBox = (AddressEntry)wizCheckout.FindControl(controlName);
        if (addBox != null)
            addBox.SelectedAddress = address;

    }
    Address GetAddressEntry(string controlName)
    {
        Address add = null;
        AddressEntry addBox = (AddressEntry)wizCheckout.FindControl(controlName);
        if (addBox != null)
            add = addBox.SelectedAddress;
        return add;

    }
    void SaveAddresses()
    {
        //pull the addresses and save them to the DB for the user
        Address billAddress = addBilling.SelectedAddress;
        billAddress.UserName = Utility.GetUserName();
        OrderController.SaveAddress(billAddress);

        //if the billing/shipping are different, save that as well
        Address shipAddress = addShipping.SelectedAddress;
        if (!shipAddress.Equals(billAddress))
        {
            shipAddress.UserName = Utility.GetUserName();
            OrderController.SaveAddress(shipAddress);
        }
    }
    #endregion

    #region Shipping Bits
    PackageInfo LoadPackage()
    {

        //Create shipping package
        PackageInfo package = new PackageInfo();
        package.FromZip = SiteConfig.ShipFromZip;
        package.FromCountryCode = SiteConfig.ShipFromCountryCode;
        package.ToZip = Profile.LastShippingAddress.Zip; ;
        package.ToCountryCode = Profile.LastShippingAddress.Country;
        package.Weight = currentOrder.GetItemsWeight();
        package.Width = Convert.ToInt16(currentOrder.GetTotalWidth());
        package.Height = Convert.ToInt16(currentOrder.GetTotalHeight());
        package.Length = Convert.ToInt16(currentOrder.GetMaxLength());
        package.DimensionUnit = SiteConfig.DimensionUnit;
        package.PackagingBuffer = SiteConfig.ShipPackagingBuffer;
        //Create Dictionary args for future expansion options
        package.Args = new Dictionary<string, string>();
        return package;

    }

    void BindShipping(PackageInfo package)
    {
        //IDataReader rdr = Commerce.Providers.ShippingService.GetShippingChoices(package);

        Commerce.Providers.DeliveryOptionCollection options = Commerce.Providers.FulfillmentService.GetOptions(package);
        radShipChoices.DataSource = options;
        radShipChoices.DataTextField = "Service";
        radShipChoices.DataValueField = "Rate";
        radShipChoices.DataBind();
        radShipChoices.SelectedIndex = 0;

        //localize it using the C formatter for local currency
        decimal dRate = 0;
        foreach (ListItem l in radShipChoices.Items)
        {
            dRate = decimal.Parse(l.Value);
            l.Text += ": " + dRate.ToString("C");

        }

        //set the Profile Shipping Bits
        Profile.CurrentOrderShipping = decimal.Parse(radShipChoices.SelectedValue);
        Profile.CurrentOrderShippingMethod = radShipChoices.SelectedItem.Text;
    }

    void LoadShippingList()
    {
        DataList dtAddresses = (DataList)wizCheckout.FindControl("dtAddresses");
        if (dtAddresses != null)
        {
            dtAddresses.DataSource = OrderController.GetUserAddresses();
            dtAddresses.DataBind();

        }
    }

    protected decimal GetSelectedShipping()
    {
        decimal dOut = 0;
        decimal.TryParse(radShipChoices.SelectedValue, out dOut);
        return dOut;
    }
    protected string GetShippingAddress()
    {
        return addShipping.SelectedAddress.ToHtmlString();
    }
    protected string GetBillingAddress()
    {
        return addBilling.SelectedAddress.ToHtmlString();
    }
    protected string GetShippingZip()
    {
        string zip = "";
        Address add = GetAddressEntry("addShipping");
        if (add != null)
            zip = add.Zip;

        return zip;
    }

    void EnsurePanelsHidden()
    {
        //bit of a hack here - an atlas workaround
        //the visible property of the PayPal checkout thingers isn't honored
        //if we're here, they shouldn't be showing
        pnlExpressCheckout.Visible = false;
        pnlPPStandard.Visible = false;
        pnlNav.Visible = false;

    }
    protected void radShipChoices_SelectedIndexChanged(object sender, EventArgs e)
    {
        //reset the order items
        //the change to the shipping amount happens on page load
        //in SetOrderInfo()
        lblOrderItems.Text = currentOrder.ItemsToString(true);

        EnsurePanelsHidden();
    }
    #endregion

    #region Checkout
    protected void btnComplete_Click(object sender, EventArgs e)
    {

        EnsurePanelsHidden();

        //set the final order info
        SetOrderInfo();

        //saving down the addresses is a convenience, if it bombs
        //swallow the exception and let it go.
        try
        {
            SaveAddresses();
        }
        catch
        {

        }

        //if there is a token in the querystring
        //this is a return from PayPal, and is therefore
        //an express checkout
        string transactionID = "";
        if (Request.QueryString["token"] != null)
        {
            transactionID = RunExpressCheckout();

        }
        else
        {
            transactionID = RunCharge();
        }

        //if an error occurred, the transactionId will be null or empty. 
        if (!String.IsNullOrEmpty(transactionID))
        {
            radShipChoices.Enabled = false;
            pnlCoupons.Visible = false;
            pnlComplete.Visible = false;
            pnlFinalHeadNav.Visible = false;
            pnlReceipt.Visible = true;
        }
    }

    string RunExpressCheckout()
    {

        //InitOrder();

        //this is the PayPal response holder
        string orderID = "";

        string sToken = Utility.GetParameter("token");

        //run the Final Express Checkout
        try
        {
            Transaction trans = OrderController.TransactOrder(currentOrder, TransactionType.PayPalPayment);
            orderID = currentOrder.OrderGUID;
        }
        catch (Exception x)
        {
            ResultMessage1.ShowFail(x.Message);
        }

        return orderID;
    }

    string RunCharge()
    {
        string sOut = "";

        try
        {

            Transaction trans = OrderController.TransactOrder(currentOrder, TransactionType.CreditCardPayment);
            //the orderID is set during the TransactOrder process
            sOut = currentOrder.OrderGUID;

        }
        catch (Exception x)
        {
            ResultMessage1.ShowFail(x.Message);
        }

        return sOut;
    }

    #endregion

    protected string GetPaymentInfo()
    {
        //this can be one of two things
        //Express Checkout payment
        //or credit card.
        string result = "";
        if (Utility.GetParameter("token") != string.Empty)
        {
            result = "PayPal Express Checkout Payment";
        }
        else
        {
            result = "Credit Card Payment: " + Enum.GetName(typeof(CreditCardType), PaymentBox1.CCType) + "<br>" +
                Utility.MaskCreditCard(PaymentBox1.CCNumber);
        }
        return result;
    }

    #region Express Checkout Bits

    void ProcessExpressReturn(string sToken)
    {

        //get the wrapper
        APIWrapper wrapper = GetPPWrapper();

        //they have come back from the PayPal site and have a token, so use this token to go get their info
        //and populate the shipping etc.
        Commerce.Common.Address payer = wrapper.GetExpressCheckout(sToken);


        //set this address as the BillTo/ShipTo for this order
        Profile.LastShippingAddress = payer;
        Profile.LastBillingAddress = payer;

        //set it as well in the billing/shippig controls
        addBilling.SelectedAddress = payer;
        addShipping.SelectedAddress = payer;

        //save this address for this user
        OrderController.SaveAddress(payer);

        //set the token in the ViewState 
        ViewState.Add("ppToken", payer.PayPalToken);
        ViewState.Add("ppID", payer.PayPalPayerID);

        //need to run the tax calc now that we have an address
        Profile.CurrentOrderTax = OrderController.CalculateTax(payer.Zip, currentOrder.CalculateSubTotal());


        //save down the order to the ViewState so that it can be picked up when Running the Charge
        SetOrderInfo();


    }
    APIWrapper GetPPWrapper()
    {
        string certPath = Server.MapPath("~/App_Data/" + SiteConfig.PayPalAPICertificate);
        APIWrapper wrapper = new Commerce.PayPal.APIWrapper(
            SiteConfig.PayPalAPIAccountName, SiteConfig.PayPalAPIAccountPassword,
            certPath, SiteConfig.PayPalAPICertificationPassword, SiteConfig.CurrencyCode);
        return wrapper;
    }
    protected void imgPayPal_Click(object sender, ImageClickEventArgs e)
    {
        SetExpressOrder();
    }
    void SetExpressOrder()
    {
        //use the API to get the SetCheckout response.
        //Then, redirect to PayPal
        int currencyDecimals = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits;
        //get the wrapper
        APIWrapper wrapper = GetPPWrapper();

        string sEmail = "";
        if (Profile.LastShippingAddress != null)
        {
            if (Profile.LastShippingAddress.Email != string.Empty)
            {
                sEmail = Profile.LastShippingAddress.Email;
            }
            else
            {
                sEmail = "nobody@nowhere.com";
            }
        }

        //send them back here for all occassions
        string successURL = Utility.GetSiteRoot() + "/checkout.aspx";
        string failURL = Utility.GetSiteRoot() + "/checkout.aspx";


        if (currentOrder.Items.Count > 0)
        {

            string ppToken = wrapper.SetExpressCheckout(sEmail, currentOrder.CalculateSubTotal(), successURL,
                failURL);
            if (ppToken.ToLower().Contains("error"))
            {
                lblPPErr.Text = "PayPal has returned an error message: " + ppToken;
            }
            else
            {
                string sUrl = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ppToken;

                if (SiteConfig.UsePPProSandbox)
                {
                    sUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ppToken;
                }

                try
                {
                    Response.Redirect(sUrl, false);
                }
                catch (Exception x)
                {
                    ResultMessage1.ShowFail(x.Message);
                }
            }

        }
        else
        {
            Response.Redirect("basket.aspx", false);
        }

    }

    #endregion

    #region Coupons
    protected void applyCoupon_Click(object sender, EventArgs e)
    {
        //Get the coupon.  
        try
        {
            Commerce.Promotions.Coupon selectedCoupon = Commerce.Promotions.Coupon.GetCoupon(couponCode.Text);
            //we have the coupon .. validate the order.  
            Commerce.Promotions.CouponValidationResponse valid =
                selectedCoupon.ValidateCouponForOrder(currentOrder);
            if (valid.IsValid)
            {
                //apply the coupon to the order 
                selectedCoupon.ApplyCouponToOrder(currentOrder);
                couponMessage.Text = "Coupon code " + selectedCoupon.CouponCode + " was applied to your order!";
                currentOrder.CouponCodes = selectedCoupon.CouponCode;

                //add a note to the order that the coupon was applied
                OrderController.AddNote("Applied coupon " + selectedCoupon.CouponCode + " to order during checkout", currentOrder);

                //re-display the order
                lblOrderItems.Text = currentOrder.ItemsToString(true);

            }
            else
            {
                couponMessage.Text = "The selected coupon could not be applied to your order.  " + valid.ValidationMessage;
            }
        }
        catch (ArgumentException ex)
        {
            couponMessage.Text = "The code you entered could not be found or verified.";


        }
        couponMessage.Visible = true;
        EnsurePanelsHidden();
    }

    #endregion

    #region Wizard Event Handlers


    protected void btnBack_Click(object sender, EventArgs e)
    {
        //move to the second step

        wizCheckout.MoveTo(wizCheckout.WizardSteps[1]);
    }
    protected void Step_Changed(object sender, EventArgs e)
    {

        pnlComplete.Visible = false;
        pnlNav.Visible = true;
        pnlExpressCheckout.Visible = false;
        pnlPPStandard.Visible = false;


        if (wizCheckout.ActiveStepIndex == 0)
        {
            //********************* SHIPPING PAGE ***************************
            btnPrev.Visible = false;
            btnNext.Text = "Billing >>";

            if (SiteConfig.UsePayPalExpressCheckout)
                pnlExpressCheckout.Visible = true;
            if (SiteConfig.UsePayPalPaymentsStandard)
                pnlPPStandard.Visible = true;


        }
        if (wizCheckout.ActiveStepIndex == 1)
        {
            //********************* BILLING PAGE ***************************
            btnPrev.Visible = true;
            btnPrev.Text = "<< Shipping";
            btnNext.Text = "Finalize >>";

            //default the billing address to the shipping address
            //if they haven't filled it out yet
            if (addBilling.SelectedAddress.FirstName.Trim() == string.Empty)
                addBilling.SelectedAddress = addShipping.SelectedAddress;

            //save down the billing address to the Profile
            Profile.LastShippingAddress = addShipping.SelectedAddress;

            //we have the shipping address so we can now calculate tax
            decimal dTax = OrderController.CalculateTax(Profile.LastShippingAddress.Zip, currentOrder.CalculateSubTotal());
            Profile.CurrentOrderTax = dTax;

        }
        else if (wizCheckout.ActiveStepIndex == 2)
        {
            //********************* FINAL PAGE ***************************
            PackageInfo package = LoadPackage();
            if (currentOrder.ShippingAddress != null && currentOrder.BillingAddress != null)
            {
                BindShipping(package);
            }
            SetOrderInfo();
            pnlNav.Visible = false;
            lblShipTo.Text = GetShippingAddress();
            lblBillTo.Text = GetBillingAddress();
            lblPaySummary.Text = GetPaymentInfo();
            lblOrderItems.Text = currentOrder.ItemsToString(true);
            //save down the shipping address
            Profile.LastBillingAddress = addBilling.SelectedAddress;
            pnlComplete.Visible = true;
            //

        }



    }
    protected void imgShip_Click(object sender, ImageClickEventArgs e)
    {
        wizCheckout.ActiveStepIndex = 0;
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        wizCheckout.ActiveStepIndex = 0;

    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        wizCheckout.ActiveStepIndex = 1;

    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        //this button advances the wizard
        wizCheckout.ActiveStepIndex = wizCheckout.ActiveStepIndex + 1;


    }
    protected void btnPrev_Click(object sender, EventArgs e)
    {
        wizCheckout.ActiveStepIndex = wizCheckout.ActiveStepIndex - 1;

    }
    #endregion

}

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us