· 5 years ago · Jan 31, 2020, 10:40 AM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package B_servlets;
7
8import HelperClasses.Currency_Storeid;
9import HelperClasses.LineItem;
10import HelperClasses.Member;
11import HelperClasses.SaleRecord;
12import HelperClasses.ShoppingCartLineItem;
13import com.stripe.Stripe;
14import com.stripe.exception.APIConnectionException;
15import com.stripe.exception.AuthenticationException;
16import com.stripe.exception.CardException;
17import com.stripe.exception.InvalidRequestException;
18import com.stripe.exception.RateLimitException;
19import com.stripe.exception.StripeException;
20import com.stripe.model.Charge;
21
22import com.stripe.net.RequestOptions;
23import java.io.IOException;
24import java.io.PrintWriter;
25import java.util.ArrayList;
26import java.util.HashMap;
27import java.util.Map;
28import javax.servlet.ServletException;
29import javax.servlet.annotation.WebServlet;
30import javax.servlet.http.HttpServlet;
31import javax.servlet.http.HttpServletRequest;
32import javax.servlet.http.HttpServletResponse;
33import javax.servlet.http.HttpSession;
34import javax.ws.rs.client.Client;
35import javax.ws.rs.client.ClientBuilder;
36import javax.ws.rs.client.Entity;
37import javax.ws.rs.client.Invocation;
38import javax.ws.rs.client.WebTarget;
39import javax.ws.rs.core.MediaType;
40import javax.ws.rs.core.Response;
41
42/**
43 *
44 * @author user
45 */
46@WebServlet(name = "ECommerce_PaymentServlet", urlPatterns = {"/ECommerce_PaymentServlet"})
47public class ECommerce_PaymentServlet extends HttpServlet {
48
49 /**
50 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
51 * methods.
52 *
53 * @param request servlet request
54 * @param response servlet response
55 * @throws ServletException if a servlet-specific error occurs
56 * @throws IOException if an I/O error occurs
57 */
58 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
59 throws ServletException, IOException {
60 response.setContentType("text/html;charset=UTF-8");
61 try (PrintWriter out = response.getWriter()) {
62 String result = "";
63 HttpSession session;
64 session = request.getSession();
65 Member member = new Member();
66 member = (Member) session.getAttribute("member");
67 ArrayList<ShoppingCartLineItem> shoppingcart = (ArrayList<ShoppingCartLineItem>) session.getAttribute("shoppingCart");
68 long mid = member.getId();
69 double paid = Double.parseDouble(request.getParameter("finalPrice"));
70 long cid = Long.parseLong(session.getAttribute("countryID").toString());
71
72 Client csClient = ClientBuilder.newClient();
73 WebTarget csTarget = csClient
74 .target("http://localhost:8080/WebServices-Student/webresources/commerce")
75 .path("getCurrencyAndStoreId")
76 .queryParam("countryId", cid);
77 Invocation.Builder csIb = csTarget.request(MediaType.APPLICATION_JSON);
78 Response csRes = csIb.get();
79 Currency_Storeid csid = csRes.readEntity(Currency_Storeid.class);
80
81 //--------------------------Credit card charge-----------------
82 String SECRET_KEY = "sk_test_Ay5rGtpsfSjr3JpWcTOX6XyB";
83 Stripe.apiKey = SECRET_KEY;
84
85 String token = request.getParameter("stripeToken");
86 int paidInCents = (int) paid * 100;
87 Map<String, Object> params = new HashMap<>();
88 params.put("amount", paidInCents);
89 params.put("currency", csid.getCurrency());
90 params.put("description", "SEP CA5 - Charge");
91 params.put("source", token);
92
93 RequestOptions options = RequestOptions
94 .builder()
95 .setIdempotencyKey(token)
96 .build();
97
98 Charge charge = Charge.create(params, options);
99 if (charge.getPaid()) {
100 System.out.println("charge successful");
101
102 //------------End of Charging--------------
103 SaleRecord sr = new SaleRecord(mid, paid, cid, csid.getCurrency(), csid.getSaleRecordId());
104 Client client = ClientBuilder.newClient();
105 WebTarget target = client
106 .target("http://localhost:8080/WebServices-Student/webresources/commerce")
107 .path("createECommerceTransactionRecord");
108
109 Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
110 Response res = invocationBuilder.put(Entity.entity(sr, MediaType.APPLICATION_JSON));
111
112 String output = res.readEntity(String.class);
113
114 long saleid = Long.parseLong(output);
115
116 for (ShoppingCartLineItem sc : shoppingcart) {
117 LineItem li = new LineItem(saleid, sc.getId(), sc.getQuantity(), sc.getCountryID(), sc.getSKU());
118 Client lineclient = ClientBuilder.newClient();
119 WebTarget linetarget = lineclient
120 .target("http://localhost:8080/WebServices-Student/webresources/commerce")
121 .path("createECommerceLineItemRecord");
122
123 Invocation.Builder ib = linetarget.request(MediaType.APPLICATION_JSON);
124 Response lineres = ib.put(Entity.entity(li, MediaType.APPLICATION_JSON));
125
126 if (lineres.getStatus() == 201) {
127
128 result = "Thank you for shopping at Island Furniture. You have checkout successfully!";
129
130 }
131 }
132 shoppingcart.clear();
133 session.setAttribute("shoppingCart", shoppingcart);
134 response.sendRedirect("/IS3102_Project-war/B/SG/shoppingCart.jsp?goodMsg=" + result);
135 } else {
136 result = "Error. Transaction was not approved. Please try again later";
137 response.sendRedirect("/IS3102_Project-war/B/SG/shoppingCart.jsp?errMsg=" + result);
138
139 }
140
141 } catch (CardException e) {
142 // Since it's a decline, CardException will be caught
143 System.out.println("Status is: " + e.getCode());
144 System.out.println("Message is: " + e.getMessage());
145 } catch (RateLimitException e) {
146 // Too many requests made to the API too quickly
147 System.out.println("Too many payment request is made at once.");
148 } catch (InvalidRequestException e) {
149 // Invalid parameters were supplied to Stripe's API
150 System.out.println("Invalid Stripe Parameters.");
151 } catch (AuthenticationException e) {
152 // Authentication with Stripe's API failed
153 // (maybe you changed API keys recently)
154 System.out.println("API Authentication Error.");
155 } catch (APIConnectionException e) {
156 // Network communication with Stripe failed
157 System.out.println("Network communication with Stripe failed.");
158 } catch (StripeException e) {
159 // Display a very generic error to the user, and maybe send
160 // yourself an email
161 System.out.println("We encountered difficulties processing your request. \nPlease try again.");
162 } catch (Exception e) {
163 // Something else happened, completely unrelated to Stripe
164 System.out.println("Unexpected error occured!");
165 }
166 }
167
168 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
169 /**
170 * Handles the HTTP <code>GET</code> method.
171 *
172 * @param request servlet request
173 * @param response servlet response
174 * @throws ServletException if a servlet-specific error occurs
175 * @throws IOException if an I/O error occurs
176 */
177 @Override
178 protected void doGet(HttpServletRequest request, HttpServletResponse response)
179 throws ServletException, IOException {
180 processRequest(request, response);
181 }
182
183 /**
184 * Handles the HTTP <code>POST</code> method.
185 *
186 * @param request servlet request
187 * @param response servlet response
188 * @throws ServletException if a servlet-specific error occurs
189 * @throws IOException if an I/O error occurs
190 */
191 @Override
192 protected void doPost(HttpServletRequest request, HttpServletResponse response)
193 throws ServletException, IOException {
194 processRequest(request, response);
195 }
196
197 /**
198 * Returns a short description of the servlet.
199 *
200 * @return a String containing servlet description
201 */
202 @Override
203 public String getServletInfo() {
204 return "Short description";
205 }// </editor-fold>
206
207}