"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Checkout and Payment with PayPal

by Erik Reitan

Download Wingtip Toys Sample Project (C#) or Download E-book (PDF)

This tutorial series will teach you the basics of building an ASP.NET Web Forms application using ASP.NET 4.5 and Microsoft Visual Studio Express 2013 for Web. A Visual Studio 2013 project with C# source code is available to accompany this tutorial series.

This tutorial describes how to modify the Wingtip Toys sample application to include user authorization, registration, and payment using PayPal. Only users who are logged in will have authorization to purchase products. The ASP.NET 4.5 Web Forms project template’s built-in user registration functionality already includes much of what you need. You will add PayPal Express Checkout functionality. In this tutorial you be using the PayPal developer testing environment, so no actual funds will be transferred. At the end of the tutorial, you will test the application by selecting products to add to the shopping cart, clicking the checkout button, and transferring data to the PayPal testing web site. On the PayPal testing web site, you will confirm your shipping and payment information and then return to the local Wingtip Toys sample application to confirm and complete the purchase.

There are several experienced third-party payment processors that specialize in online shopping that address scalability and security. ASP.NET developers should consider the advantages of utilizing a third party payment solution before implementing a shopping and purchasing solution.

[!NOTE]

The Wingtip Toys sample application was designed to shown specific ASP.NET concepts and features available to ASP.NET web developers. This sample application was not optimized for all possible circumstances in regard to scalability and security.

What you’ll learn:

Adding Order Tracking

In this tutorial, you’ll create two new classes to track data from the order a user has created. The classes will track data regarding shipping information, purchase total, and payment confirmation.

Add the Order and OrderDetail Model Classes

Earlier in this tutorial series, you defined the schema for categories, products, and shopping cart items by creating the Category, Product, and CartItem classes in the Models folder. Now you will add two new classes to define the schema for the product order and the details of the order.

  1. In the Models folder, add a new class named Order.cs.
    The new class file is displayed in the editor.
  2. Replace the default code with the following:

    [!code-csharpMain]
       1:  using System.ComponentModel.DataAnnotations;
       2:  using System.Collections.Generic;
       3:  using System.ComponentModel;
       4:   
       5:  namespace WingtipToys.Models
       6:  {
       7:    public class Order
       8:    {
       9:      public int OrderId { get; set; }
      10:   
      11:      public System.DateTime OrderDate { get; set; }
      12:   
      13:      public string Username { get; set; }
      14:   
      15:      [Required(ErrorMessage = "First Name is required")]
      16:      [DisplayName("First Name")]
      17:      [StringLength(160)]
      18:      public string FirstName { get; set; }
      19:   
      20:      [Required(ErrorMessage = "Last Name is required")]
      21:      [DisplayName("Last Name")]
      22:      [StringLength(160)]
      23:      public string LastName { get; set; }
      24:   
      25:      [Required(ErrorMessage = "Address is required")]
      26:      [StringLength(70)]
      27:      public string Address { get; set; }
      28:   
      29:      [Required(ErrorMessage = "City is required")]
      30:      [StringLength(40)]
      31:      public string City { get; set; }
      32:   
      33:      [Required(ErrorMessage = "State is required")]
      34:      [StringLength(40)]
      35:      public string State { get; set; }
      36:   
      37:      [Required(ErrorMessage = "Postal Code is required")]
      38:      [DisplayName("Postal Code")]
      39:      [StringLength(10)]
      40:      public string PostalCode { get; set; }
      41:   
      42:      [Required(ErrorMessage = "Country is required")]
      43:      [StringLength(40)]
      44:      public string Country { get; set; }
      45:   
      46:      [StringLength(24)]
      47:      public string Phone { get; set; }
      48:   
      49:      [Required(ErrorMessage = "Email Address is required")]
      50:      [DisplayName("Email Address")]
      51:      [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
      52:          ErrorMessage = "Email is is not valid.")]
      53:      [DataType(DataType.EmailAddress)]
      54:      public string Email { get; set; }
      55:   
      56:      [ScaffoldColumn(false)]
      57:      public decimal Total { get; set; }
      58:   
      59:      [ScaffoldColumn(false)]
      60:      public string PaymentTransactionId { get; set; }
      61:   
      62:      [ScaffoldColumn(false)]
      63:      public bool HasBeenShipped { get; set; }
      64:   
      65:      public List<OrderDetail> OrderDetails { get; set; }
      66:    }
      67:  }
  3. Add an OrderDetail.cs class to the Models folder.
  4. Replace the default code with the following code:

    [!code-csharpMain]

       1:  using System.ComponentModel.DataAnnotations;
       2:   
       3:  namespace WingtipToys.Models
       4:  {
       5:      public class OrderDetail
       6:      {
       7:          public int OrderDetailId { get; set; }
       8:   
       9:          public int OrderId { get; set; }
      10:   
      11:          public string Username { get; set; }
      12:   
      13:          public int ProductId { get; set; }
      14:   
      15:          public int Quantity { get; set; }
      16:   
      17:          public double? UnitPrice { get; set; }
      18:   
      19:      }
      20:  }

The Order and OrderDetail classes contain the schema to define the order information used for purchasing and shipping.

In addition, you will need to update the database context class that manages the entity classes and that provides data access to the database. To do this, you will add the newly created Order and OrderDetail model classes to ProductContext class.

  1. In Solution Explorer, find and open the ProductContext.cs file.
  2. Add the highlighted code to the ProductContext.cs file as shown below:

    [!code-csharpMain]

       1:  using System.Data.Entity;
       2:   
       3:  namespace WingtipToys.Models
       4:  {
       5:    public class ProductContext : DbContext
       6:    {
       7:      public ProductContext()
       8:        : base("WingtipToys")
       9:      {
      10:      }
      11:      public DbSet<Category> Categories { get; set; }
      12:      public DbSet<Product> Products { get; set; }
      13:      public DbSet<CartItem> ShoppingCartItems { get; set; }
      14:      public DbSet<Order> Orders { get; set; }
      15:      public DbSet<OrderDetail> OrderDetails { get; set; }
      16:    }
      17:  }

As mentioned previously in this tutorial series, the code in the ProductContext.cs file adds the System.Data.Entity namespace so that you have access to all the core functionality of the Entity Framework. This functionality includes the capability to query, insert, update, and delete data by working with strongly typed objects. The above code in the ProductContext class adds Entity Framework access to the newly added Order and OrderDetail classes.

Adding Checkout Access

The Wingtip Toys sample application allows anonymous users to review and add products to a shopping cart. However, when anonymous users choose to purchase the products they added to the shopping cart, they must log on to the site. Once they have logged on, they can access the restricted pages of the Web application that handle the checkout and purchase process. These restricted pages are contained in the Checkout folder of the application.

Add a Checkout Folder and Pages

You will now create the Checkout folder and the pages in it that the customer will see during the checkout process. You will update these pages later in this tutorial.

  1. Right-click the project name (Wingtip Toys) in Solution Explorer and select Add a New Folder.

    Checkout and Payment with PayPal - New Folder
  2. Name the new folder Checkout.
  3. Right-click the Checkout folder and then select Add->New Item.

    Checkout and Payment with PayPal - New Item
  4. The Add New Item dialog box is displayed.
  5. Select the Visual C# -> Web templates group on the left. Then, from the middle pane, select Web Form with Master Pageand name it CheckoutStart.aspx.

    Checkout and Payment with PayPal - Add New Item Dialog
  6. As before, select the Site.Master file as the master page.
  7. Add the following additional pages to the Checkout folder using the same steps above:

    • CheckoutReview.aspx
    • CheckoutComplete.aspx
    • CheckoutCancel.aspx
    • CheckoutError.aspx

Add a Web.config File

By adding a new Web.config file to the Checkout folder, you will be able to restrict access to all the pages contained in the folder.

  1. Right-click the Checkout folder and select Add -> New Item.
    The Add New Item dialog box is displayed.
  2. Select the Visual C# -> Web templates group on the left. Then, from the middle pane, select Web Configuration File, accept the default name of Web.config, and then select Add.
  3. Replace the existing XML content in the Web.config file with the following:

    [!code-xmlMain]
       1:  <?xml version="1.0"?>
       2:  <configuration>
       3:    <system.web>
       4:      <authorization>
       5:        <deny users="?"/>
       6:      </authorization>
       7:    </system.web>
       8:  </configuration>
  4. Save the Web.config file.

The Web.config file specifies that all unknown users of the Web application must be denied access to the pages contained in the Checkout folder. However, if the user has registered an account and is logged on, they will be a known user and will have access to the pages in the Checkout folder.

It’s important to note that ASP.NET configuration follows a hierarchy, where each Web.config file applies configuration settings to the folder that it is in and to all of the child directories below it.

## Enable SSL for the Project

Secure Sockets Layer (SSL) is a protocol defined to allow Web servers and Web clients to communicate more securely through the use of encryption. When SSL is not used, data sent between the client and server is open to packet sniffing by anyone with physical access to the network. Additionally, several common authentication schemes are not secure over plain HTTP. In particular, Basic authentication and forms authentication send unencrypted credentials. To be secure, these authentication schemes must use SSL.

  1. In Solution Explorer, click the WingtipToys project, then press F4 to display the Properties window.
  2. Change SSL Enabled to true.
  3. Copy the SSL URL so you can use it later.
    The SSL URL will be https://localhost:44300/ unless you’ve previously created SSL Web Sites (as shown below).
    Project Properties
  4. In Solution Explorer, right click the WingtipToys project and click Properties.
  5. In the left tab, click Web.
  6. Change the Project Url to use the SSL URL that you saved earlier.
    Project Web Properties
  7. Save the page by pressing CTRL+S.
  8. Press Ctrl+F5 to run the application. Visual Studio will display an option to allow you to avoid SSL warnings.
  9. Click Yes to trust the IIS Express SSL certificate and continue.
    IIS Express SSL certificate details
    A Security Warning is displayed.
  10. Click Yes to install the certificate to your localhost.
    Security Warning dialog box
    The browser window will be displayed.

You can now easily test your Web application locally using SSL.

## Add an OAuth 2.0 Provider

ASP.NET Web Forms provides enhanced options for membership and authentication. These enhancements include OAuth. OAuth is an open protocol that allows secure authorization in a simple and standard method from web, mobile, and desktop applications. The ASP.NET Web Forms template uses OAuth to expose Facebook, Twitter, Google and Microsoft as authentication providers. Although this tutorial uses only Google as the authentication provider, you can easily modify the code to use any of the providers. The steps to implement other providers are very similar to the steps you will see in this tutorial.

In addition to authentication, the tutorial will also use roles to implement authorization. Only those users you add to the canEdit role will be able to change data (create, edit, or delete contacts).

[!NOTE]

Windows Live applications only accept a live URL for a working website, so you cannot use a local website URL for testing logins.

The following steps will allow you to add a Google authentication provider.

  1. Open the App_Start.Auth.cs file.
  2. Remove the comment characters from the app.UseGoogleAuthentication() method so that the method appears as follows:

    [!code-csharpMain]
       1:  app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
       2:  {
       3:      ClientId = "",
       4:      ClientSecret = ""
       5:  });
  3. Navigate to the Google Developers Console. You will also need to sign-in with your Google developer email account (gmail.com). If you do not have a Google account, select the Create an account link.
    Next, you’ll see the Google Developers Console.
    Google Developers Console
  4. Click the Create Project button and enter a project name and ID (you can use the default values). Then, click the agreement checkbox and the Create button.

    Google - New Project
    Google - New Project

In a few seconds the new project will be created and your browser will display the new projects page. 5. In the left tab, click APIs & auth, and then click Credentials. 6. Click the Create New Client ID under OAuth.
The Create Client ID dialog will be displayed.
Google - Create Client ID 7. In the Create Client ID dialog, keep the default Web application for the application type. 8. Set the Authorized JavaScript Origins to the SSL URL you used earlier in this tutorial (https://localhost:44300/ unless you’ve created other SSL projects).
This URL is the origin for your application. For this sample, you will only enter the localhost test URL. However, you can enter multiple URLs to account for localhost and production. 9. Set the Authorized Redirect URI to the following:

[!code-htmlMain]
   1:  https://localhost:44300/signin-google

This value is the URI that ASP.NET OAuth users to communicate with the google OAuth server. Remember the SSL URL you used above ( https://localhost:44300/ unless you’ve created other SSL projects). 10. Click the Create Client ID button. 11. On the left menu of the Google Developers Console, click the Consent screen menu item, then set your email address and product name. When you have completed the form, click Save. 12. Click the APIs menu item, scroll down and click the off button next to Google+ API.
Accepting this option will enable the Google+ API. 13. You must also update the Microsoft.Owin NuGet package to version 3.0.0.
From the Tools menu, select NuGet Package Manager and then select Manage NuGet Packages for Solution.
From the Manage NuGet Packages window, find and update the Microsoft.Owin package to version 3.0.0. 14. In Visual Studio, update the UseGoogleAuthentication method of the Startup.Auth.cs page by copying and pasting the Client ID and Client Secret into the method. The Client ID and Client Secret values shown below are samples and will not work.

[!code-csharpMain]
   1:  using System;
   2:  using Microsoft.AspNet.Identity;
   3:  using Microsoft.AspNet.Identity.EntityFramework;
   4:  using Microsoft.AspNet.Identity.Owin;
   5:  using Microsoft.Owin;
   6:  using Microsoft.Owin.Security.Cookies;
   7:  using Microsoft.Owin.Security.DataProtection;
   8:  using Microsoft.Owin.Security.Google;
   9:  using Owin;
  10:  using WingtipToys.Models;
  11:   
  12:  namespace WingtipToys
  13:  {
  14:      public partial class Startup {
  15:   
  16:          // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
  17:          public void ConfigureAuth(IAppBuilder app)
  18:          {
  19:              // Configure the db context, user manager and signin manager to use a single instance per request
  20:              app.CreatePerOwinContext(ApplicationDbContext.Create);
  21:              app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
  22:              app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
  23:   
  24:              // Enable the application to use a cookie to store information for the signed in user
  25:              // and to use a cookie to temporarily store information about a user logging in with a third party login provider
  26:              // Configure the sign in cookie
  27:              app.UseCookieAuthentication(new CookieAuthenticationOptions
  28:              {
  29:                  AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
  30:                  LoginPath = new PathString("/Account/Login"),
  31:                  Provider = new CookieAuthenticationProvider
  32:                  {
  33:                      OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
  34:                          validateInterval: TimeSpan.FromMinutes(30),
  35:                          regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
  36:                  }
  37:              });
  38:              // Use a cookie to temporarily store information about a user logging in with a third party login provider
  39:              app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
  40:   
  41:              // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
  42:              app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
  43:   
  44:              // Enables the application to remember the second login verification factor such as phone or email.
  45:              // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
  46:              // This is similar to the RememberMe option when you log in.
  47:              app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
  48:   
  49:              // Uncomment the following lines to enable logging in with third party login providers
  50:              //app.UseMicrosoftAccountAuthentication(
  51:              //    clientId: "",
  52:              //    clientSecret: "");
  53:   
  54:              //app.UseTwitterAuthentication(
  55:              //   consumerKey: "",
  56:              //   consumerSecret: "");
  57:   
  58:              //app.UseFacebookAuthentication(
  59:              //   appId: "",
  60:              //   appSecret: "");
  61:   
  62:              app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
  63:              {
  64:                ClientId = "000000000000.apps.googleusercontent.com",
  65:                ClientSecret = "00000000000"
  66:              });
  67:          }
  68:      }
  69:  }
  1. Press CTRL+F5 to build and run the application. Click the Log in link.
  2. Under Use another service to log in, click Google.
    Log in
  3. If you need to enter your credentials, you will be redirected to the google site where you will enter your credentials.
    Google - Sign in
  4. After you enter your credentials, you will be prompted to give permissions to the web application you just created.
    Project Default Service Account
  5. Click Accept. You will now be redirected back to the Register page of the WingtipToys application where you can register your Google account.
    Register with your Google Account
  6. You have the option of changing the local email registration name used for your Gmail account, but you generally want to keep the default email alias (that is, the one you used for authentication). Click Log in as shown above.

Modifying Login Functionality

As previously mentioned in this tutorial series, much of the user registration functionality has been included in the ASP.NET Web Forms template by default. Now you will modify the default Login.aspx and Register.aspx pages to call the MigrateCart method. The MigrateCart method associates a newly logged in user with an anonymous shopping cart. By associating the user and shopping cart, the Wingtip Toys sample application will be able to maintain the shopping cart of the user between visits.

  1. In Solution Explorer, find and open the Account folder.
  2. Modify the code-behind page named Login.aspx.cs to include the code highlighted in yellow, so that it appears as follows:

    [!code-csharpMain]
       1:  using System;
       2:  using System.Web;
       3:  using System.Web.UI;
       4:  using Microsoft.AspNet.Identity;
       5:  using Microsoft.AspNet.Identity.Owin;
       6:  using Owin;
       7:  using WingtipToys.Models;
       8:   
       9:  namespace WingtipToys.Account
      10:  {
      11:      public partial class Login : Page
      12:      {
      13:          protected void Page_Load(object sender, EventArgs e)
      14:          {
      15:              RegisterHyperLink.NavigateUrl = "Register";
      16:              // Enable this once you have account confirmation enabled for password reset functionality
      17:              //ForgotPasswordHyperLink.NavigateUrl = "Forgot";
      18:              OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
      19:              var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
      20:              if (!String.IsNullOrEmpty(returnUrl))
      21:              {
      22:                  RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
      23:              }
      24:          }
      25:   
      26:          protected void LogIn(object sender, EventArgs e)
      27:          {
      28:              if (IsValid)
      29:              {
      30:                  // Validate the user password
      31:                  var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
      32:                  var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
      33:   
      34:                  // This doen't count login failures towards account lockout
      35:                  // To enable password failures to trigger lockout, change to shouldLockout: true
      36:                  var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
      37:   
      38:                  switch (result)
      39:                  {
      40:                      case SignInStatus.Success:
      41:                          WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions();
      42:                          String cartId = usersShoppingCart.GetCartId();
      43:                          usersShoppingCart.MigrateCart(cartId, Email.Text);
      44:   
      45:                          IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
      46:                          break;
      47:                      case SignInStatus.LockedOut:
      48:                          Response.Redirect("/Account/Lockout");
      49:                          break;
      50:                      case SignInStatus.RequiresVerification:
      51:                          Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}", 
      52:                                                          Request.QueryString["ReturnUrl"],
      53:                                                          RememberMe.Checked),
      54:                                            true);
      55:                          break;
      56:                      case SignInStatus.Failure:
      57:                      default:
      58:                          FailureText.Text = "Invalid login attempt";
      59:                          ErrorMessage.Visible = true;
      60:                          break;
      61:                  }
      62:              }
      63:          }
      64:      }
      65:  }
  3. Save the Login.aspx.cs file.

For now, you can ignore the warning that there is no definition for the MigrateCart method. You will be adding it a bit later in this tutorial.

The Login.aspx.cs code-behind file supports a LogIn method. By inspecting the Login.aspx page, you’ll see that this page includes a “Log in” button that when click triggers the LogIn handler on the code-behind.

When the Login method on the Login.aspx.cs is called, a new instance of the shopping cart named usersShoppingCart is created. The ID of the shopping cart (a GUID) is retrieved and set to the cartId variable. Then, the MigrateCart method is called, passing both the cartId and the name of the logged-in user to this method. When the shopping cart is migrated, the GUID used to identify the anonymous shopping cart is replaced with the user name.

In addition to modifying the Login.aspx.cs code-behind file to migrate the shopping cart when the user logs in, you must also modify the Register.aspx.cs code-behind file to migrate the shopping cart when the user creates a new account and logs in.

  1. In the Account folder, open the code-behind file named Register.aspx.cs.
  2. Modify the code-behind file by including the code in yellow, so that it appears as follows:

    [!code-csharpMain]
       1:  using System;
       2:  using System.Linq;
       3:  using System.Web;
       4:  using System.Web.UI;
       5:  using Microsoft.AspNet.Identity;
       6:  using Microsoft.AspNet.Identity.Owin;
       7:  using Owin;
       8:  using WingtipToys.Models;
       9:   
      10:  namespace WingtipToys.Account
      11:  {
      12:      public partial class Register : Page
      13:      {
      14:          protected void CreateUser_Click(object sender, EventArgs e)
      15:          {
      16:              var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
      17:              var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
      18:              IdentityResult result = manager.Create(user, Password.Text);
      19:              if (result.Succeeded)
      20:              {
      21:                  // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
      22:                  //string code = manager.GenerateEmailConfirmationToken(user.Id);
      23:                  //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
      24:                  //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");
      25:   
      26:                  IdentityHelper.SignIn(manager, user, isPersistent: false);
      27:   
      28:                  using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
      29:                  {
      30:                    String cartId = usersShoppingCart.GetCartId();
      31:                    usersShoppingCart.MigrateCart(cartId, user.Id);
      32:                  }
      33:   
      34:                  IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
      35:              }
      36:              else 
      37:              {
      38:                  ErrorMessage.Text = result.Errors.FirstOrDefault();
      39:              }
      40:          }
      41:      }
      42:  }
  3. Save the Register.aspx.cs file. Once again, ignore the warning about the MigrateCart method.

Notice that the code you used in the CreateUser_Click event handler is very similar to the code you used in the LogIn method. When the user registers or logs in to the site, a call to the MigrateCart method will be made.

Migrating the Shopping Cart

Now that you have the log-in and registration process updated, you can add the code to migrate the shopping cart using the MigrateCart method.

  1. In Solution Explorer, find the Logic folder and open the ShoppingCartActions.cs class file.
  2. Add the code highlighted in yellow to the existing code in the ShoppingCartActions.cs file, so that the code in the ShoppingCartActions.cs file appears as follows:

    [!code-csharpMain]

       1:  using System;
       2:  using System.Collections.Generic;
       3:  using System.Linq;
       4:  using System.Web;
       5:  using WingtipToys.Models;
       6:   
       7:  namespace WingtipToys.Logic
       8:  {
       9:    public class ShoppingCartActions : IDisposable
      10:    {
      11:      public string ShoppingCartId { get; set; }
      12:   
      13:      private ProductContext _db = new ProductContext();
      14:   
      15:      public const string CartSessionKey = "CartId";
      16:   
      17:      public void AddToCart(int id)
      18:      {
      19:        // Retrieve the product from the database.           
      20:        ShoppingCartId = GetCartId();
      21:   
      22:        var cartItem = _db.ShoppingCartItems.SingleOrDefault(
      23:            c => c.CartId == ShoppingCartId
      24:            && c.ProductId == id);
      25:        if (cartItem == null)
      26:        {
      27:          // Create a new cart item if no cart item exists.                 
      28:          cartItem = new CartItem
      29:          {
      30:            ItemId = Guid.NewGuid().ToString(),
      31:            ProductId = id,
      32:            CartId = ShoppingCartId,
      33:            Product = _db.Products.SingleOrDefault(
      34:             p => p.ProductID == id),
      35:            Quantity = 1,
      36:            DateCreated = DateTime.Now
      37:          };
      38:   
      39:          _db.ShoppingCartItems.Add(cartItem);
      40:        }
      41:        else
      42:        {
      43:          // If the item does exist in the cart,                  
      44:          // then add one to the quantity.                 
      45:          cartItem.Quantity++;
      46:        }
      47:        _db.SaveChanges();
      48:      }
      49:   
      50:      public void Dispose()
      51:      {
      52:        if (_db != null)
      53:        {
      54:          _db.Dispose();
      55:          _db = null;
      56:        }
      57:      }
      58:   
      59:      public string GetCartId()
      60:      {
      61:        if (HttpContext.Current.Session[CartSessionKey] == null)
      62:        {
      63:          if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
      64:          {
      65:            HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
      66:          }
      67:          else
      68:          {
      69:            // Generate a new random GUID using System.Guid class.     
      70:            Guid tempCartId = Guid.NewGuid();
      71:            HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
      72:          }
      73:        }
      74:        return HttpContext.Current.Session[CartSessionKey].ToString();
      75:      }
      76:   
      77:      public List<CartItem> GetCartItems()
      78:      {
      79:        ShoppingCartId = GetCartId();
      80:   
      81:        return _db.ShoppingCartItems.Where(
      82:            c => c.CartId == ShoppingCartId).ToList();
      83:      }
      84:   
      85:      public decimal GetTotal()
      86:      {
      87:        ShoppingCartId = GetCartId();
      88:        // Multiply product price by quantity of that product to get        
      89:        // the current price for each of those products in the cart.  
      90:        // Sum all product price totals to get the cart total.   
      91:        decimal? total = decimal.Zero;
      92:        total = (decimal?)(from cartItems in _db.ShoppingCartItems
      93:                           where cartItems.CartId == ShoppingCartId
      94:                           select (int?)cartItems.Quantity *
      95:                           cartItems.Product.UnitPrice).Sum();
      96:        return total ?? decimal.Zero;
      97:      }
      98:   
      99:      public ShoppingCartActions GetCart(HttpContext context)
     100:      {
     101:        using (var cart = new ShoppingCartActions())
     102:        {
     103:          cart.ShoppingCartId = cart.GetCartId();
     104:          return cart;
     105:        }
     106:      }
     107:   
     108:      public void UpdateShoppingCartDatabase(String cartId, ShoppingCartUpdates[] CartItemUpdates)
     109:      {
     110:        using (var db = new WingtipToys.Models.ProductContext())
     111:        {
     112:          try
     113:          {
     114:            int CartItemCount = CartItemUpdates.Count();
     115:            List<CartItem> myCart = GetCartItems();
     116:            foreach (var cartItem in myCart)
     117:            {
     118:              // Iterate through all rows within shopping cart list
     119:              for (int i = 0; i < CartItemCount; i++)
     120:              {
     121:                if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId)
     122:                {
     123:                  if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true)
     124:                  {
     125:                    RemoveItem(cartId, cartItem.ProductId);
     126:                  }
     127:                  else
     128:                  {
     129:                    UpdateItem(cartId, cartItem.ProductId, CartItemUpdates[i].PurchaseQuantity);
     130:                  }
     131:                }
     132:              }
     133:            }
     134:          }
     135:          catch (Exception exp)
     136:          {
     137:            throw new Exception("ERROR: Unable to Update Cart Database - " + exp.Message.ToString(), exp);
     138:          }
     139:        }
     140:      }
     141:   
     142:      public void RemoveItem(string removeCartID, int removeProductID)
     143:      {
     144:        using (var _db = new WingtipToys.Models.ProductContext())
     145:        {
     146:          try
     147:          {
     148:            var myItem = (from c in _db.ShoppingCartItems where c.CartId == removeCartID && c.Product.ProductID == removeProductID select c).FirstOrDefault();
     149:            if (myItem != null)
     150:            {
     151:              // Remove Item.
     152:              _db.ShoppingCartItems.Remove(myItem);
     153:              _db.SaveChanges();
     154:            }
     155:          }
     156:          catch (Exception exp)
     157:          {
     158:            throw new Exception("ERROR: Unable to Remove Cart Item - " + exp.Message.ToString(), exp);
     159:          }
     160:        }
     161:      }
     162:   
     163:      public void UpdateItem(string updateCartID, int updateProductID, int quantity)
     164:      {
     165:        using (var _db = new WingtipToys.Models.ProductContext())
     166:        {
     167:          try
     168:          {
     169:            var myItem = (from c in _db.ShoppingCartItems where c.CartId == updateCartID && c.Product.ProductID == updateProductID select c).FirstOrDefault();
     170:            if (myItem != null)
     171:            {
     172:              myItem.Quantity = quantity;
     173:              _db.SaveChanges();
     174:            }
     175:          }
     176:          catch (Exception exp)
     177:          {
     178:            throw new Exception("ERROR: Unable to Update Cart Item - " + exp.Message.ToString(), exp);
     179:          }
     180:        }
     181:      }
     182:   
     183:      public void EmptyCart()
     184:      {
     185:        ShoppingCartId = GetCartId();
     186:        var cartItems = _db.ShoppingCartItems.Where(
     187:            c => c.CartId == ShoppingCartId);
     188:        foreach (var cartItem in cartItems)
     189:        {
     190:          _db.ShoppingCartItems.Remove(cartItem);
     191:        }
     192:        // Save changes.             
     193:        _db.SaveChanges();
     194:      }
     195:   
     196:      public int GetCount()
     197:      {
     198:        ShoppingCartId = GetCartId();
     199:   
     200:        // Get the count of each item in the cart and sum them up          
     201:        int? count = (from cartItems in _db.ShoppingCartItems
     202:                      where cartItems.CartId == ShoppingCartId
     203:                      select (int?)cartItems.Quantity).Sum();
     204:        // Return 0 if all entries are null         
     205:        return count ?? 0;
     206:      }
     207:   
     208:      public struct ShoppingCartUpdates
     209:      {
     210:        public int ProductId;
     211:        public int PurchaseQuantity;
     212:        public bool RemoveItem;
     213:      }
     214:   
     215:      public void MigrateCart(string cartId, string userName)
     216:      {
     217:        var shoppingCart = _db.ShoppingCartItems.Where(c => c.CartId == cartId);
     218:        foreach (CartItem item in shoppingCart)
     219:        {
     220:          item.CartId = userName;
     221:        }
     222:        HttpContext.Current.Session[CartSessionKey] = userName;
     223:        _db.SaveChanges();
     224:      }
     225:    }
     226:  }

The MigrateCart method uses the existing cartId to find the shopping cart of the user. Next, the code loops through all the shopping cart items and replaces the CartId property (as specified by the CartItem schema) with the logged-in user name.

Updating the Database Connection

If you are following this tutorial using the prebuilt Wingtip Toys sample application, you must recreate the default membership database. By modifying the default connection string, the membership database will be created the next time the application runs.

  1. Open the Web.config file at the root of the project.
  2. Update the default connection string so that it appears as follows:

    [!code-xmlMain]

       1:  <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True" providerName="System.Data.SqlClient" />

## Integrating PayPal

PayPal is a web-based billing platform that accepts payments by online merchants. This tutorial next explains how to integrate PayPal’s Express Checkout functionality into your application. Express Checkout allows your customers to use PayPal to pay for the items they have added to their shopping cart.

Create PaylPal Test Accounts

To use the PayPal testing environment, you must create and verify a developer test account. You will use the developer test account to create a buyer test account and a seller test account. The developer test account credentials also will allow the Wingtip Toys sample application to access the PayPal testing environment.

  1. In a browser, navigate to the PayPal developer testing site:
    https://developer.paypal.com
  2. If you don’t have a PayPal developer account, create a new account by clicking Sign Upand following the sign up steps. If you have an existing PayPal developer account, sign in by clicking Log In. You will need your PayPal developer account to test the Wingtip Toys sample application later in this tutorial.
  3. If you have just signed up for your PayPal developer account, you may need to verify your PayPal developer account with PayPal. You can verify your account by following the steps that PayPal sent to your email account. Once you have verified your PayPal developer account, log back into the PayPal developer testing site.
  4. After you are logged in to the PayPal developer site with your PayPal developer account you need to create a PayPal buyer test account if you don’t already have one. To create a buyer test account, on the PayPal site click the Applications tab and then click Sandbox accounts.
    The Sandbox test accounts page is shown.

    [!NOTE]

    The PayPal Developer site already provides a merchant test account.

    Checkout and Payment with PayPal - Sandbox test accounts
  5. On the Sandbox test accounts page, click Create Account.
  6. On the Create test account page choose a buyer test account email and password of your choice.

    [!NOTE]

    You will need the buyer email addresses and password to test the Wingtip Toys sample application at the end of this tutorial.

    Checkout and Payment with PayPal - Sandbox test accounts
  7. Create the buyer test account by clicking the Create Account button.
    The Sandbox Test accounts page is displayed.

    Checkout and Payment with PayPal - PaylPal Accounts
  8. On the Sandbox test accounts page, click the facilitator email account.
    Profile and Notification options appear.
  9. Select the Profile option, then click API credentials to view your API credentials for the merchant test account.
  10. Copy the TEST API credentials to notepad.

You will need your displayed Classic TEST API credentials (Username, Password, and Signature) to make API calls from the Wingtip Toys sample application to the PayPal testing environment. You will add the credentials in the next step.

Add PayPal Class and API Credentials

You will place the majority of the PayPal code into a single class. This class contains the methods used to communicate with PayPal. Also, you will add your PayPal credentials to this class.

  1. In the Wingtip Toys sample application within Visual Studio, right-click the Logic folder and then select Add -> New Item.
    The Add New Item dialog box is displayed.
  2. Under Visual C# from the Installed pane on the left, select Code.
  3. From the middle pane, select Class. Name this new class PayPalFunctions.cs.
  4. Click Add.
    The new class file is displayed in the editor.
  5. Replace the default code with the following code:

    [!code-csharpMain]
       1:  using System;
       2:  using System.Collections;
       3:  using System.Collections.Specialized;
       4:  using System.IO;
       5:  using System.Net;
       6:  using System.Text;
       7:  using System.Data;
       8:  using System.Configuration;
       9:  using System.Web;
      10:  using WingtipToys;
      11:  using WingtipToys.Models;
      12:  using System.Collections.Generic;
      13:  using System.Linq;
      14:   
      15:  public class NVPAPICaller
      16:  {
      17:    //Flag that determines the PayPal environment (live or sandbox)
      18:    private const bool bSandbox = true;
      19:    private const string CVV2 = "CVV2";
      20:   
      21:    // Live strings.
      22:    private string pEndPointURL = "https://api-3t.paypal.com/nvp";
      23:    private string host = "www.paypal.com";
      24:   
      25:    // Sandbox strings.
      26:    private string pEndPointURL_SB = "https://api-3t.sandbox.paypal.com/nvp";
      27:    private string host_SB = "www.sandbox.paypal.com";
      28:   
      29:    private const string SIGNATURE = "SIGNATURE";
      30:    private const string PWD = "PWD";
      31:    private const string ACCT = "ACCT";
      32:   
      33:    //Replace <Your API Username> with your API Username
      34:    //Replace <Your API Password> with your API Password
      35:    //Replace <Your Signature> with your Signature
      36:    public string APIUsername = "<Your API Username>";
      37:    private string APIPassword = "<Your API Password>";
      38:    private string APISignature = "<Your Signature>";
      39:    private string Subject = "";
      40:    private string BNCode = "PP-ECWizard";
      41:   
      42:    //HttpWebRequest Timeout specified in milliseconds 
      43:    private const int Timeout = 15000;
      44:    private static readonly string[] SECURED_NVPS = new string[] { ACCT, CVV2, SIGNATURE, PWD };
      45:   
      46:    public void SetCredentials(string Userid, string Pwd, string Signature)
      47:    {
      48:      APIUsername = Userid;
      49:      APIPassword = Pwd;
      50:      APISignature = Signature;
      51:    }
      52:   
      53:    public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
      54:    {
      55:      if (bSandbox)
      56:      {
      57:        pEndPointURL = pEndPointURL_SB;
      58:        host = host_SB;
      59:      }
      60:   
      61:      string returnURL = "https://localhost:44300/Checkout/CheckoutReview.aspx";
      62:      string cancelURL = "https://localhost:44300/Checkout/CheckoutCancel.aspx";
      63:   
      64:      NVPCodec encoder = new NVPCodec();
      65:      encoder["METHOD"] = "SetExpressCheckout";
      66:      encoder["RETURNURL"] = returnURL;
      67:      encoder["CANCELURL"] = cancelURL;
      68:      encoder["BRANDNAME"] = "Wingtip Toys Sample Application";
      69:      encoder["PAYMENTREQUEST_0_AMT"] = amt;
      70:      encoder["PAYMENTREQUEST_0_ITEMAMT"] = amt;
      71:      encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
      72:      encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD";
      73:   
      74:      // Get the Shopping Cart Products
      75:      using (WingtipToys.Logic.ShoppingCartActions myCartOrders = new WingtipToys.Logic.ShoppingCartActions())
      76:      {
      77:        List<CartItem> myOrderList = myCartOrders.GetCartItems();
      78:   
      79:        for (int i = 0; i < myOrderList.Count; i++)
      80:        {
      81:          encoder["L_PAYMENTREQUEST_0_NAME" + i] = myOrderList[i].Product.ProductName.ToString();
      82:          encoder["L_PAYMENTREQUEST_0_AMT" + i] = myOrderList[i].Product.UnitPrice.ToString();
      83:          encoder["L_PAYMENTREQUEST_0_QTY" + i] = myOrderList[i].Quantity.ToString();
      84:        }
      85:      }
      86:   
      87:      string pStrrequestforNvp = encoder.Encode();
      88:      string pStresponsenvp = HttpCall(pStrrequestforNvp);
      89:   
      90:      NVPCodec decoder = new NVPCodec();
      91:      decoder.Decode(pStresponsenvp);
      92:   
      93:      string strAck = decoder["ACK"].ToLower();
      94:      if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
      95:      {
      96:        token = decoder["TOKEN"];
      97:        string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
      98:        retMsg = ECURL;
      99:        return true;
     100:      }
     101:      else
     102:      {
     103:        retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
     104:            "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
     105:            "Desc2=" + decoder["L_LONGMESSAGE0"];
     106:        return false;
     107:      }
     108:    }
     109:   
     110:    public bool GetCheckoutDetails(string token, ref string PayerID, ref NVPCodec decoder, ref string retMsg)
     111:    {
     112:      if (bSandbox)
     113:      {
     114:        pEndPointURL = pEndPointURL_SB;
     115:      }
     116:   
     117:      NVPCodec encoder = new NVPCodec();
     118:      encoder["METHOD"] = "GetExpressCheckoutDetails";
     119:      encoder["TOKEN"] = token;
     120:   
     121:      string pStrrequestforNvp = encoder.Encode();
     122:      string pStresponsenvp = HttpCall(pStrrequestforNvp);
     123:   
     124:      decoder = new NVPCodec();
     125:      decoder.Decode(pStresponsenvp);
     126:   
     127:      string strAck = decoder["ACK"].ToLower();
     128:      if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
     129:      {
     130:        PayerID = decoder["PAYERID"];
     131:        return true;
     132:      }
     133:      else
     134:      {
     135:        retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
     136:            "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
     137:            "Desc2=" + decoder["L_LONGMESSAGE0"];
     138:   
     139:        return false;
     140:      }
     141:    }
     142:   
     143:    public bool DoCheckoutPayment(string finalPaymentAmount, string token, string PayerID, ref NVPCodec decoder, ref string retMsg)
     144:    {
     145:      if (bSandbox)
     146:      {
     147:        pEndPointURL = pEndPointURL_SB;
     148:      }
     149:   
     150:      NVPCodec encoder = new NVPCodec();
     151:      encoder["METHOD"] = "DoExpressCheckoutPayment";
     152:      encoder["TOKEN"] = token;
     153:      encoder["PAYERID"] = PayerID;
     154:      encoder["PAYMENTREQUEST_0_AMT"] = finalPaymentAmount;
     155:      encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD";
     156:      encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
     157:   
     158:      string pStrrequestforNvp = encoder.Encode();
     159:      string pStresponsenvp = HttpCall(pStrrequestforNvp);
     160:   
     161:      decoder = new NVPCodec();
     162:      decoder.Decode(pStresponsenvp);
     163:   
     164:      string strAck = decoder["ACK"].ToLower();
     165:      if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
     166:      {
     167:        return true;
     168:      }
     169:      else
     170:      {
     171:        retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
     172:            "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
     173:            "Desc2=" + decoder["L_LONGMESSAGE0"];
     174:   
     175:        return false;
     176:      }
     177:    }
     178:   
     179:    public string HttpCall(string NvpRequest)
     180:    {
     181:      string url = pEndPointURL;
     182:   
     183:      string strPost = NvpRequest + "&" + buildCredentialsNVPString();
     184:      strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
     185:   
     186:      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
     187:      objRequest.Timeout = Timeout;
     188:      objRequest.Method = "POST";
     189:      objRequest.ContentLength = strPost.Length;
     190:   
     191:      try
     192:      {
     193:        using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
     194:        {
     195:          myWriter.Write(strPost);
     196:        }
     197:      }
     198:      catch (Exception)
     199:      {
     200:        // No logging for this tutorial.
     201:      }
     202:   
     203:      //Retrieve the Response returned from the NVP API call to PayPal.
     204:      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
     205:      string result;
     206:      using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
     207:      {
     208:        result = sr.ReadToEnd();
     209:      }
     210:   
     211:      return result;
     212:    }
     213:   
     214:    private string buildCredentialsNVPString()
     215:    {
     216:      NVPCodec codec = new NVPCodec();
     217:   
     218:      if (!IsEmpty(APIUsername))
     219:        codec["USER"] = APIUsername;
     220:   
     221:      if (!IsEmpty(APIPassword))
     222:        codec[PWD] = APIPassword;
     223:   
     224:      if (!IsEmpty(APISignature))
     225:        codec[SIGNATURE] = APISignature;
     226:   
     227:      if (!IsEmpty(Subject))
     228:        codec["SUBJECT"] = Subject;
     229:   
     230:      codec["VERSION"] = "88.0";
     231:   
     232:      return codec.Encode();
     233:    }
     234:   
     235:    public static bool IsEmpty(string s)
     236:    {
     237:      return s == null || s.Trim() == string.Empty;
     238:    }
     239:  }
     240:   
     241:  public sealed class NVPCodec : NameValueCollection
     242:  {
     243:    private const string AMPERSAND = "&";
     244:    private const string EQUALS = "=";
     245:    private static readonly char[] AMPERSAND_CHAR_ARRAY = AMPERSAND.ToCharArray();
     246:    private static readonly char[] EQUALS_CHAR_ARRAY = EQUALS.ToCharArray();
     247:   
     248:    public string Encode()
     249:    {
     250:      StringBuilder sb = new StringBuilder();
     251:      bool firstPair = true;
     252:      foreach (string kv in AllKeys)
     253:      {
     254:        string name = HttpUtility.UrlEncode(kv);
     255:        string value = HttpUtility.UrlEncode(this[kv]);
     256:        if (!firstPair)
     257:        {
     258:          sb.Append(AMPERSAND);
     259:        }
     260:        sb.Append(name).Append(EQUALS).Append(value);
     261:        firstPair = false;
     262:      }
     263:      return sb.ToString();
     264:    }
     265:   
     266:    public void Decode(string nvpstring)
     267:    {
     268:      Clear();
     269:      foreach (string nvp in nvpstring.Split(AMPERSAND_CHAR_ARRAY))
     270:      {
     271:        string[] tokens = nvp.Split(EQUALS_CHAR_ARRAY);
     272:        if (tokens.Length >= 2)
     273:        {
     274:          string name = HttpUtility.UrlDecode(tokens[0]);
     275:          string value = HttpUtility.UrlDecode(tokens[1]);
     276:          Add(name, value);
     277:        }
     278:      }
     279:    }
     280:   
     281:    public void Add(string name, string value, int index)
     282:    {
     283:      this.Add(GetArrayName(index, name), value);
     284:    }
     285:   
     286:    public void Remove(string arrayName, int index)
     287:    {
     288:      this.Remove(GetArrayName(index, arrayName));
     289:    }
     290:   
     291:    public string this[string name, int index]
     292:    {
     293:      get
     294:      {
     295:        return this[GetArrayName(index, name)];
     296:      }
     297:      set
     298:      {
     299:        this[GetArrayName(index, name)] = value;
     300:      }
     301:    }
     302:   
     303:    private static string GetArrayName(int index, string name)
     304:    {
     305:      if (index < 0)
     306:      {
     307:        throw new ArgumentOutOfRangeException("index", "index cannot be negative : " + index);
     308:      }
     309:      return name + index;
     310:    }
     311:  }
  6. Add the Merchant API credentials (Username, Password, and Signature) that you displayed earlier in this tutorial so that you can make function calls to the PayPal testing environment.

    [!code-csharpMain]

       1:  public string APIUsername = "<Your API Username>";
       2:  private string APIPassword = "<Your API Password>";
       3:  private string APISignature = "<Your Signature>";

[!NOTE]

In this sample application you are simply adding credentials to a C# file (.cs). However, in a implemented solution, you should consider encrypting your credentials in a configuration file.

The NVPAPICaller class contains the majority of the PayPal functionality. The code in the class provides the methods needed to make a test purchase from the PayPal testing environment. The following three PayPal functions are used to make purchases:

The ShortcutExpressCheckout method collects the test purchase information and product details from the shopping cart and calls the SetExpressCheckout PayPal function. The GetCheckoutDetails method confirms purchase details and calls the GetExpressCheckoutDetails PayPal function before making the test purchase. The DoCheckoutPayment method completes the test purchase from the testing environment by calling the DoExpressCheckoutPayment PayPal function. The remaining code supports the PayPal methods and process, such as encoding strings, decoding strings, processing arrays, and determining credentials.

[!NOTE]

PayPal allows you to include optional purchase details based on PayPal’s API specification. By extending the code in the Wingtip Toys sample application, you can include localization details, product descriptions, tax, a customer service number, as well as many other optional fields.

Notice that the return and cancel URLs that are specified in the ShortcutExpressCheckout method use a port number.

[!code-htmlMain]

   1:  string returnURL = "https://localhost:44300/Checkout/CheckoutReview.aspx";
   2:         string cancelURL = "https://localhost:44300/Checkout/CheckoutCancel.aspx";

When Visual Web Developer runs a web project using SSL, commonly the port 44300 is used for the web server. As shown above, the port number is 44300. When you run the application, you could see a different port number. Your port number needs to be correctly set in the code so that you can successful run the Wingtip Toys sample application at the end of this tutorial. The next section of this tutorial explains how to retrieve the local host port number and update the PayPal class.

Update the LocalHost Port Number in the PayPal Class

The Wingtip Toys sample application purchases products by navigating to the PayPal testing site and returning to your local instance of the Wingtip Toys sample application. In order to have PayPal return to the correct URL, you need to specify the port number of the locally running sample application in the PayPal code mentioned above.

  1. Right-click the project name (WingtipToys) in Solution Explorer and select Properties.
  2. In the left column, select the Web tab.
  3. Retrieve the port number from the Project Url box.
  4. If needed, update the returnURL and cancelURL in the PayPal class (NVPAPICaller) in the PayPalFunctions.cs file to use the port number of your web application:

    [!code-htmlMain]

       1:  string returnURL = "https://localhost:<Your Port Number>/Checkout/CheckoutReview.aspx";
       2:  string cancelURL = "https://localhost:<Your Port Number>/Checkout/CheckoutCancel.aspx";

Now the code that you added will match the expected port for your local Web application. PayPal will be able to return to the correct URL on your local machine.

Add the PayPal Checkout Button

Now that the primary PayPal functions have been added to the sample application, you can begin adding the markup and code needed to call these functions. First, you must add the checkout button that the user will see on the shopping cart page.

  1. Open the ShoppingCart.aspx file.
  2. Scroll to the bottom of the file and find the <!--Checkout Placeholder --> comment.
  3. Replace the comment with an ImageButton control so that the mark up is replaced as follows:

    [!code-aspxMain]
       1:  <asp:ImageButton ID="CheckoutImageBtn" runat="server" 
       2:                        ImageUrl="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" 
       3:                        Width="145" AlternateText="Check out with PayPal" 
       4:                        OnClick="CheckoutBtn_Click" 
       5:                        BackColor="Transparent" BorderWidth="0" />
  4. In the ShoppingCart.aspx.cs file, after the UpdateBtn_Click event handler near the end of the file, add the CheckOutBtn_Click event handler:

    [!code-csharpMain]
       1:  protected void CheckoutBtn_Click(object sender, ImageClickEventArgs e)
       2:  {
       3:      using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
       4:      {
       5:          Session["payment_amt"] = usersShoppingCart.GetTotal();
       6:      }
       7:      Response.Redirect("Checkout/CheckoutStart.aspx");
       8:  }
  5. Also in the ShoppingCart.aspx.cs file, add a reference to the CheckoutBtn, so that the new image button is referenced as follows:

    [!code-csharpMain]
       1:  protected void Page_Load(object sender, EventArgs e)
       2:  {
       3:      using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
       4:      {
       5:          decimal cartTotal = 0;
       6:          cartTotal = usersShoppingCart.GetTotal();
       7:          if (cartTotal > 0)
       8:          {
       9:              // Display Total.
      10:              lblTotal.Text = String.Format("{0:c}", cartTotal);
      11:          }
      12:          else
      13:          {
      14:              LabelTotalText.Text = "";
      15:              lblTotal.Text = "";
      16:              ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
      17:              UpdateBtn.Visible = false;
      18:              CheckoutImageBtn.Visible = false;
      19:          }
      20:      }
      21:  }
  6. Save your changes to both the ShoppingCart.aspx file and the ShoppingCart.aspx.cs file.
  7. From the menu, select Debug->Build WingtipToys.
    The project will be rebuilt with the newly added ImageButton control.

Send Purchase Details to PayPal

When the user clicks the Checkout button on the shopping cart page (ShoppingCart.aspx), they’ll begin the purchase process. The following code calls the first PayPal function needed to purchase products.

  1. From the Checkout folder, open the code-behind file named CheckoutStart.aspx.cs.
    Be sure to open the code-behind file.
  2. Replace the existing code with the following:

    [!code-csharpMain]

       1:  using System;
       2:  using System.Collections.Generic;
       3:  using System.Linq;
       4:  using System.Web;
       5:  using System.Web.UI;
       6:  using System.Web.UI.WebControls;
       7:   
       8:  namespace WingtipToys.Checkout
       9:  {
      10:      public partial class CheckoutStart : System.Web.UI.Page
      11:      {
      12:          protected void Page_Load(object sender, EventArgs e)
      13:          {
      14:              NVPAPICaller payPalCaller = new NVPAPICaller();
      15:              string retMsg = "";
      16:              string token = "";
      17:   
      18:              if (Session["payment_amt"] != null)
      19:              {
      20:                  string amt = Session["payment_amt"].ToString();
      21:   
      22:                  bool ret = payPalCaller.ShortcutExpressCheckout(amt, ref token, ref retMsg);
      23:                  if (ret)
      24:                  {
      25:                      Session["token"] = token;
      26:                      Response.Redirect(retMsg);
      27:                  }
      28:                  else
      29:                  {
      30:                      Response.Redirect("CheckoutError.aspx?" + retMsg);
      31:                  }
      32:              }
      33:              else
      34:              {
      35:                  Response.Redirect("CheckoutError.aspx?ErrorCode=AmtMissing");
      36:              }
      37:          }
      38:      }
      39:  }

When the user of the application clicks the Checkout button on the shopping cart page, the browser will navigate to the CheckoutStart.aspx page. When the CheckoutStart.aspx page loads, the ShortcutExpressCheckout method is called. At this point, the user is transferred to the PayPal testing web site. On the PayPal site, the user enters their PayPal credentials, reviews the purchase details, accepts the PayPal agreement and returns to the Wingtip Toys sample application where the ShortcutExpressCheckout method completes. When the ShortcutExpressCheckout method is complete, it will redirect the user to the CheckoutReview.aspx page specified in the ShortcutExpressCheckout method. This allows the user to review the order details from within the Wingtip Toys sample application.

Review Order Details

After returning from PayPal, the CheckoutReview.aspx page of the Wingtip Toys sample application displays the order details. This page allows the user to review the order details before purchasing the products. The CheckoutReview.aspx page must be created as follows:

  1. In the Checkout folder, open the page named CheckoutReview.aspx.
  2. Replace the existing markup with the following:

    [!code-aspxMain]
       1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CheckoutReview.aspx.cs" Inherits="WingtipToys.Checkout.CheckoutReview" %>
       2:  <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
       3:      <h1>Order Review</h1>
       4:      <p></p>
       5:      <h3 style="padding-left: 33px">Products:</h3>
       6:      <asp:GridView ID="OrderItemList" runat="server" AutoGenerateColumns="False" GridLines="Both" CellPadding="10" Width="500" BorderColor="#efeeef" BorderWidth="33">              
       7:          <Columns>
       8:              <asp:BoundField DataField="ProductId" HeaderText=" Product ID" />        
       9:              <asp:BoundField DataField="Product.ProductName" HeaderText=" Product Name" />        
      10:              <asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}"/>     
      11:              <asp:BoundField DataField="Quantity" HeaderText="Quantity" />        
      12:          </Columns>    
      13:      </asp:GridView>
      14:      <asp:DetailsView ID="ShipInfo" runat="server" AutoGenerateRows="false" GridLines="None" CellPadding="10" BorderStyle="None" CommandRowStyle-BorderStyle="None">
      15:          <Fields>
      16:          <asp:TemplateField>
      17:              <ItemTemplate>
      18:                  <h3>Shipping Address:</h3>
      19:                  <br />
      20:                  <asp:Label ID="FirstName" runat="server" Text='<%#: Eval("FirstName") %>'></asp:Label>  
      21:                  <asp:Label ID="LastName" runat="server" Text='<%#: Eval("LastName") %>'></asp:Label>
      22:                  <br />
      23:                  <asp:Label ID="Address" runat="server" Text='<%#: Eval("Address") %>'></asp:Label>
      24:                  <br />
      25:                  <asp:Label ID="City" runat="server" Text='<%#: Eval("City") %>'></asp:Label>
      26:                  <asp:Label ID="State" runat="server" Text='<%#: Eval("State") %>'></asp:Label>
      27:                  <asp:Label ID="PostalCode" runat="server" Text='<%#: Eval("PostalCode") %>'></asp:Label>
      28:                  <p></p>
      29:                  <h3>Order Total:</h3>
      30:                  <br />
      31:                  <asp:Label ID="Total" runat="server" Text='<%#: Eval("Total", "{0:C}") %>'></asp:Label>
      32:              </ItemTemplate>
      33:              <ItemStyle HorizontalAlign="Left" />
      34:          </asp:TemplateField>
      35:            </Fields>
      36:      </asp:DetailsView>
      37:      <p></p>
      38:      <hr />
      39:      <asp:Button ID="CheckoutConfirm" runat="server" Text="Complete Order" OnClick="CheckoutConfirm_Click" />
      40:  </asp:Content>
  3. Open the code-behind page named CheckoutReview.aspx.cs and replace the existing code with the following:

    [!code-csharpMain]

       1:  using System;
       2:  using System.Collections.Generic;
       3:  using System.Linq;
       4:  using System.Web;
       5:  using System.Web.UI;
       6:  using System.Web.UI.WebControls;
       7:  using WingtipToys.Models;
       8:   
       9:  namespace WingtipToys.Checkout
      10:  {
      11:    public partial class CheckoutReview : System.Web.UI.Page
      12:    {
      13:      protected void Page_Load(object sender, EventArgs e)
      14:      {
      15:        if (!IsPostBack)
      16:        {
      17:          NVPAPICaller payPalCaller = new NVPAPICaller();
      18:   
      19:          string retMsg = "";
      20:          string token = "";
      21:          string PayerID = "";
      22:          NVPCodec decoder = new NVPCodec();
      23:          token = Session["token"].ToString();
      24:   
      25:          bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
      26:          if (ret)
      27:          {
      28:            Session["payerId"] = PayerID;
      29:   
      30:            var myOrder = new Order();
      31:            myOrder.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
      32:            myOrder.Username = User.Identity.Name;
      33:            myOrder.FirstName = decoder["FIRSTNAME"].ToString();
      34:            myOrder.LastName = decoder["LASTNAME"].ToString();
      35:            myOrder.Address = decoder["SHIPTOSTREET"].ToString();
      36:            myOrder.City = decoder["SHIPTOCITY"].ToString();
      37:            myOrder.State = decoder["SHIPTOSTATE"].ToString();
      38:            myOrder.PostalCode = decoder["SHIPTOZIP"].ToString();
      39:            myOrder.Country = decoder["SHIPTOCOUNTRYCODE"].ToString();
      40:            myOrder.Email = decoder["EMAIL"].ToString();
      41:            myOrder.Total = Convert.ToDecimal(decoder["AMT"].ToString());
      42:   
      43:            // Verify total payment amount as set on CheckoutStart.aspx.
      44:            try
      45:            {
      46:              decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
      47:              decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
      48:              if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
      49:              {
      50:                Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
      51:              }
      52:            }
      53:            catch (Exception)
      54:            {
      55:              Response.Redirect("CheckoutError.aspx?" + "Desc=Amount%20total%20mismatch.");
      56:            }
      57:   
      58:            // Get DB context.
      59:            ProductContext _db = new ProductContext();
      60:   
      61:            // Add order to DB.
      62:            _db.Orders.Add(myOrder);
      63:            _db.SaveChanges();
      64:   
      65:            // Get the shopping cart items and process them.
      66:            using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
      67:            {
      68:              List<CartItem> myOrderList = usersShoppingCart.GetCartItems();
      69:   
      70:              // Add OrderDetail information to the DB for each product purchased.
      71:              for (int i = 0; i < myOrderList.Count; i++)
      72:              {
      73:                // Create a new OrderDetail object.
      74:                var myOrderDetail = new OrderDetail();
      75:                myOrderDetail.OrderId = myOrder.OrderId;
      76:                myOrderDetail.Username = User.Identity.Name;
      77:                myOrderDetail.ProductId = myOrderList[i].ProductId;
      78:                myOrderDetail.Quantity = myOrderList[i].Quantity;
      79:                myOrderDetail.UnitPrice = myOrderList[i].Product.UnitPrice;
      80:   
      81:                // Add OrderDetail to DB.
      82:                _db.OrderDetails.Add(myOrderDetail);
      83:                _db.SaveChanges();
      84:              }
      85:   
      86:              // Set OrderId.
      87:              Session["currentOrderId"] = myOrder.OrderId;
      88:   
      89:              // Display Order information.
      90:              List<Order> orderList = new List<Order>();
      91:              orderList.Add(myOrder);
      92:              ShipInfo.DataSource = orderList;
      93:              ShipInfo.DataBind();
      94:   
      95:              // Display OrderDetails.
      96:              OrderItemList.DataSource = myOrderList;
      97:              OrderItemList.DataBind();
      98:            }
      99:          }
     100:          else
     101:          {
     102:            Response.Redirect("CheckoutError.aspx?" + retMsg);
     103:          }
     104:        }
     105:      }
     106:   
     107:      protected void CheckoutConfirm_Click(object sender, EventArgs e)
     108:      {
     109:        Session["userCheckoutCompleted"] = "true";
     110:        Response.Redirect("~/Checkout/CheckoutComplete.aspx");
     111:      }
     112:    }
     113:  }

The DetailsView control is used to display the order details that have been returned from PayPal. Also, the above code saves the order details to the Wingtip Toys database as an OrderDetail object. When the user clicks on the Complete Order button, they are redirected to the CheckoutComplete.aspx page.

[!NOTE]

Tip

In the markup of the CheckoutReview.aspx page, notice that the <ItemStyle> tag is used to change the style of the items within the DetailsView control near the bottom of the page. By viewing the page in Design View (by selecting Design at the lower left corner of Visual Studio), then selecting the DetailsView control, and selecting the Smart Tag (the arrow icon at the top right of the control), you will be able to see the DetailsView Tasks.

Checkout and Payment with PayPal - Edit Fields
Checkout and Payment with PayPal - Edit Fields

By selecting Edit Fields, the Fields dialog box will appear. In this dialog box you can easily control the visual properties, such as ItemStyle, of the DetailsView control.

Checkout and Payment with PayPal - Fields Dialog
Checkout and Payment with PayPal - Fields Dialog

Complete Purchase

CheckoutComplete.aspx page makes the purchase from PayPal. As mentioned above, the user must click on the Complete Order button before the application will navigate to the CheckoutComplete.aspx page.

  1. In the Checkout folder, open the page named CheckoutComplete.aspx.
  2. Replace the existing markup with the following:

    [!code-aspxMain]
       1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CheckoutComplete.aspx.cs" Inherits="WingtipToys.Checkout.CheckoutComplete" %>
       2:  <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
       3:      <h1>Checkout Complete</h1>
       4:      <p></p>
       5:      <h3>Payment Transaction ID:</h3> <asp:Label ID="TransactionId" runat="server"></asp:Label>
       6:      <p></p>
       7:      <h3>Thank You!</h3>
       8:      <p></p>
       9:      <hr />
      10:      <asp:Button ID="Continue" runat="server" Text="Continue Shopping" OnClick="Continue_Click" />
      11:  </asp:Content>
  3. Open the code-behind page named CheckoutComplete.aspx.cs and replace the existing code with the following:

    [!code-csharpMain]

       1:  using System;
       2:  using System.Collections.Generic;
       3:  using System.Linq;
       4:  using System.Web;
       5:  using System.Web.UI;
       6:  using System.Web.UI.WebControls;
       7:  using WingtipToys.Models;
       8:   
       9:  namespace WingtipToys.Checkout
      10:  {
      11:    public partial class CheckoutComplete : System.Web.UI.Page
      12:    {
      13:      protected void Page_Load(object sender, EventArgs e)
      14:      {
      15:        if (!IsPostBack)
      16:        {
      17:          // Verify user has completed the checkout process.
      18:          if ((string)Session["userCheckoutCompleted"] != "true")
      19:          {
      20:            Session["userCheckoutCompleted"] = string.Empty;
      21:            Response.Redirect("CheckoutError.aspx?" + "Desc=Unvalidated%20Checkout.");
      22:          }
      23:   
      24:          NVPAPICaller payPalCaller = new NVPAPICaller();
      25:   
      26:          string retMsg = "";
      27:          string token = "";
      28:          string finalPaymentAmount = "";
      29:          string PayerID = "";
      30:          NVPCodec decoder = new NVPCodec();
      31:   
      32:          token = Session["token"].ToString();
      33:          PayerID = Session["payerId"].ToString();
      34:          finalPaymentAmount = Session["payment_amt"].ToString();
      35:   
      36:          bool ret = payPalCaller.DoCheckoutPayment(finalPaymentAmount, token, PayerID, ref decoder, ref retMsg);
      37:          if (ret)
      38:          {
      39:            // Retrieve PayPal confirmation value.
      40:            string PaymentConfirmation = decoder["PAYMENTINFO_0_TRANSACTIONID"].ToString();
      41:            TransactionId.Text = PaymentConfirmation;
      42:   
      43:            ProductContext _db = new ProductContext();
      44:            // Get the current order id.
      45:            int currentOrderId = -1;
      46:            if (Session["currentOrderId"] != string.Empty)
      47:            {
      48:              currentOrderId = Convert.ToInt32(Session["currentOrderID"]);
      49:            }
      50:            Order myCurrentOrder;
      51:            if (currentOrderId >= 0)
      52:            {
      53:              // Get the order based on order id.
      54:              myCurrentOrder = _db.Orders.Single(o => o.OrderId == currentOrderId);
      55:              // Update the order to reflect payment has been completed.
      56:              myCurrentOrder.PaymentTransactionId = PaymentConfirmation;
      57:              // Save to DB.
      58:              _db.SaveChanges();
      59:            }
      60:   
      61:            // Clear shopping cart.
      62:            using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart =
      63:                new WingtipToys.Logic.ShoppingCartActions())
      64:            {
      65:              usersShoppingCart.EmptyCart();
      66:            }
      67:   
      68:            // Clear order id.
      69:            Session["currentOrderId"] = string.Empty;
      70:          }
      71:          else
      72:          {
      73:            Response.Redirect("CheckoutError.aspx?" + retMsg);
      74:          }
      75:        }
      76:      }
      77:   
      78:      protected void Continue_Click(object sender, EventArgs e)
      79:      {
      80:        Response.Redirect("~/Default.aspx");
      81:      }
      82:    }
      83:  }

When the CheckoutComplete.aspx page is loaded, the DoCheckoutPayment method is called. As mentioned earlier, the DoCheckoutPayment method completes the purchase from the PayPal testing environment. Once PayPal has completed the purchase of the order, the CheckoutComplete.aspx page displays a payment transaction ID to the purchaser.

Handle Cancel Purchase

If the user decides to cancel the purchase, they will be directed to the CheckoutCancel.aspx page where they will see that their order has been cancelled.

  1. Open the page named CheckoutCancel.aspx in the Checkout folder.
  2. Replace the existing markup with the following:

    [!code-aspxMain]

       1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CheckoutCancel.aspx.cs" Inherits="WingtipToys.Checkout.CheckoutCancel" %>
       2:  <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
       3:      <h1>Checkout Cancelled</h1>
       4:      <p></p>
       5:      <h3>Your purchase has been cancelled.</h3>
       6:  </asp:Content>

Handle Purchase Errors

Errors during the purchase process will be handled by the CheckoutError.aspx page. The code-behind of the CheckoutStart.aspx page, the CheckoutReview.aspx page, and the CheckoutComplete.aspx page will each redirect to the CheckoutError.aspx page if an error occurs.

  1. Open the page named CheckoutError.aspx in the Checkout folder.
  2. Replace the existing markup with the following:

    [!code-aspxMain]

       1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CheckoutError.aspx.cs" Inherits="WingtipToys.Checkout.CheckoutError" %>
       2:  <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
       3:      <h1>Checkout Error</h1>
       4:      <p></p>
       5:  <table id="ErrorTable">
       6:      <tr>
       7:          <td class="field"></td>
       8:          <td><%=Request.QueryString.Get("ErrorCode")%></td>
       9:      </tr>
      10:      <tr>
      11:          <td class="field"></td>
      12:          <td><%=Request.QueryString.Get("Desc")%></td>
      13:      </tr>
      14:      <tr>
      15:          <td class="field"></td>
      16:          <td><%=Request.QueryString.Get("Desc2")%></td>
      17:      </tr>
      18:  </table>
      19:      <p></p>
      20:  </asp:Content>

The CheckoutError.aspx page is displayed with the error details when an error occurs during the checkout process.

Running the Application

Run the application to see how to purchase products. Note that you will be running in the PayPal testing environment. No actual money is being exchanged.

  1. Make sure all your files are saved in Visual Studio.
  2. Open a Web browser and navigate to https://developer.paypal.com.
  3. Login with your PayPal developer account that you created earlier in this tutorial.
    For PayPal’s developer sandbox, you need to be logged in at https://developer.paypal.com to test express checkout. This only applies to PayPal’s sandbox testing, not to PayPal’s live environment.
  4. In Visual Studio, press F5 to run the Wingtip Toys sample application.
    After the database rebuilds, the browser will open and show the Default.aspx page.
  5. Add three different products to the shopping cart by selecting the product category, such as “Cars” and then clicking Add to Cart next to each product.
    The shopping cart will display the product you have selected.
  6. Click the PayPal button to checkout.

    Checkout and Payment with PayPal - Cart
    Checkout and Payment with PayPal - Cart

Checking out will require that you have a user account for the Wingtip Toys sample application. 7. Click the Google link on the right of the page to log in with an existing gmail.com email account.
If you do not have a gmail.com account, you can create one for testing purposes at www.gmail.com. You can also use a standard local account by clicking “Register”.

![Checkout and Payment with PayPal - Log in](checkout-and-payment-with-paypal/_static/image21.png)
  1. Sign in with your gmail account and password.

    Checkout and Payment with PayPal - Gmail Sign In
  2. Click the Log in button to register your gmail account with your Wingtip Toys sample application user name.

    Checkout and Payment with PayPal - Register Account
  3. On the PayPal test site, add your buyer email address and password that you created earlier in this tutorial, then click the Log In button.

    Checkout and Payment with PayPal - PayPal Sign In
  4. Agree to the PayPal policy and click the Agree and Continue button.
    Note that this page is only displayed the first time you use this PayPal account. Again note that this is a test account, no real money is exchanged.

    Checkout and Payment with PayPal - PayPal Policy
  5. Review the order information on the PayPal testing environment review page and click Continue.

    Checkout and Payment with PayPal - Review Information
  6. On the CheckoutReview.aspx page, verify the order amount and view the generated shipping address. Then, click the Complete Order button.

    Checkout and Payment with PayPal - Order Review
  7. The CheckoutComplete.aspx page is displayed with a payment transaction ID.

    Checkout and Payment with PayPal - Checkout Complete
    Checkout and Payment with PayPal - Checkout Complete

## Reviewing the Database

By reviewing the updated data in the Wingtip Toys sample application database after running the application, you can see that the application successfully recorded the purchase of the products.

You can inspect the data contained in the Wingtiptoys.mdf database file by using the Database Explorer window (Server Explorer window in Visual Studio) as you did earlier in this tutorial series.

  1. Close the browser window if it is still open.
  2. In Visual Studio, select the Show All Files icon at the top of Solution Explorer to allow you to expand the App_Data folder.
  3. Expand the App_Data folder.
    You may need to select the Show All Files icon for the folder.
  4. Right-click the Wingtiptoys.mdf database file and select Open.
    Server Explorer is displayed.
  5. Expand the Tables folder.
  6. Right-click the Orderstable and select Show Table Data.
    The Orders table is displayed.
  7. Review the PaymentTransactionID column to confirm successful transactions.

    Checkout and Payment with PayPal - Review Database
  8. Close the Orders table window.
  9. In the Server Explorer, right-click the OrderDetails table and select Show Table Data.
  10. Review the OrderId and Username values in the OrderDetails table. Note that these values match the OrderId and Username values included in the Orders table.
  11. Close the OrderDetails table window.
  12. Right-click the Wingtip Toys database file (Wingtiptoys.mdf) and select Close Connection.
  13. If you do not see the Solution Explorer window, click Solution Explorer at the bottom of the Server Explorer window to show the Solution Explorer again.

Summary

In this tutorial you added order and order detail schemas to track the purchase of products. You also integrated PayPal functionality into the Wingtip Toys sample application.

Additional Resources

ASP.NET Configuration Overview
Deploy a Secure ASP.NET Web Forms App with Membership, OAuth, and SQL Database to Azure App Service
Microsoft Azure - Free Trial

Disclaimer

This tutorial contains sample code. Such sample code is provided “as is” without warranty of any kind. Accordingly, Microsoft does not guarantee the accuracy, integrity, or quality of the sample code. You agree to use the sample code at your own risk. Under no circumstances will Microsoft be liable to you in any way for any sample code, content, including but not limited to, any errors or omissions in any sample code, content, or any loss or damage of any kind incurred as a result of the use of any sample code. You are hereby notified and do hereby agree to indemnify, save and hold Microsoft harmless from and against any and all loss, claims of loss, injury or damage of any kind including, without limitation, those occasioned by or arising from material that you post, transmit, use or rely on including, but not limited to, the views expressed therein.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/checkout-and-payment-with-paypal.htm
< THANKS ME>