File: PayPalExample.C

package info (click to toggle)
witty 3.3.3%2Bdfsg-4.1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,228 kB
  • ctags: 26,694
  • sloc: cpp: 147,809; ansic: 77,999; xml: 16,331; sh: 1,303; makefile: 198; java: 86; sql: 14
file content (489 lines) | stat: -rw-r--r-- 13,835 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/*
 * Copyright (C) 2012 Emweb bvba, Kessel-Lo, Belgium.
 *
 * See the LICENSE file for terms of use.
 */
#include <Wt/WAnchor>
#include <Wt/WApplication>
#include <Wt/WBreak>
#include <Wt/WContainerWidget>
#include <Wt/WDialog>
#include <Wt/WGridLayout>
#include <Wt/WImage>
#include <Wt/WLabel>
#include <Wt/WMessageBox>
#include <Wt/WPushButton>
#include <Wt/WServer>
#include <Wt/WStringStream>
#include <Wt/WTable>
#include <Wt/WTemplate>
#include <Wt/WText>
#include <Wt/WVBoxLayout>
#include <Wt/Utils>

#include <Wt/Payment/PayPal>
#include <Wt/Payment/Customer>
#include <Wt/Payment/Money>
#include <Wt/Payment/Order>
#include <Wt/Payment/Address>

#include "boost/lexical_cast.hpp"

Wt::Payment::PayPalService *payPalService;
const char *PAYPAL_BUTTON_URL =
  "https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif";

class PayPalApplication : public Wt::WApplication
{
public:
  PayPalApplication(const Wt::WEnvironment& env)
    : Wt::WApplication(env),
      expressCheckout_(0),
      payment_(0),
      dialog_(0)
  {
    messageResourceBundle().use("text");
    useStyleSheet("css/style.css");

    Wt::WPushButton *checkout = new Wt::WPushButton("Proceed to checkout...");
    checkout->clicked().connect(this, &PayPalApplication::reviewOrder);

    Wt::WTemplate *t = new Wt::WTemplate(Wt::WString::tr("start"), root());
    t->bindWidget("checkout", checkout);
  }

  ~PayPalApplication()
  {
    if (expressCheckout_)
      delete expressCheckout_;

    clearDialog();
  }

private:
  Wt::Payment::PayPalExpressCheckout* expressCheckout_;
  Wt::WContainerWidget *payment_;

  Wt::WDialog *dialog_;
  Wt::WText *dialogText_;
  Wt::WPushButton *dialogCancelButton_;

  void reviewOrder()
  {
    /*
     * First page, shows order and pay pal button
     */

    Wt::Payment::Order order = createOrder();
    Wt::Payment::Customer customer = createCustomer();

    root()->clear();
    new Wt::WText(Wt::WString::tr("review.title"), root());
    printOrder(order, true);

    expressCheckout_ = payPalService->createExpressCheckout(customer, order);

    std::string logo = "http://www.webtoolkit.eu/css/wt/emweb_powered.jpg";
    expressCheckout_->setParameter("LOGOIMG", logo);
    expressCheckout_->setParameter("CARTBORDERCOLOR", "000CD");

    expressCheckout_->setup().connect(this, &PayPalApplication::onSetup);
    enableUpdates(true);

    payment_ = new Wt::WContainerWidget(root());
    payment_->setStyleClass("payment");
    new Wt::WText("Preparing payment...", payment_);
  }

  void onSetup(const Wt::Payment::Result& result)
  {
    enableUpdates(false);
    triggerUpdate();

    if (!result.error()) {
      payment_->clear();

      // Create the PayPal button
      Wt::WAnchor *payButton = new Wt::WAnchor(payment_);
      payButton->setImage(new Wt::WImage(PAYPAL_BUTTON_URL));

      // Clicking starts the payment process
      payButton->clicked().connect
	(expressCheckout_,
	 &Wt::Payment::PayPalExpressCheckout::startPayment);

      // Clicking also shows an information dialog
      payButton->clicked().connect
	(this, &PayPalApplication::showPaymentDialog);

      // Connect paypal response(approval) from the popup window with
      // onPaymentApproval
      expressCheckout_
	->paymentApproved().connect(this,
				    &PayPalApplication::onPaymentApproval);
    } else {
      std::cerr << "result.errorMessage: "
                << result.errorMessage().toUTF8() << std::endl;

      showError("Could not setup payment with PayPal.");
    }

    printResultMessage(result);
  }

  void showPaymentDialog()
  {
    /*
     * A dialog shown while the user pays in a popup window.
     */
    enableUpdates(true);

    dialog_ = new Wt::WDialog("Information");

    dialogText_ = new Wt::WText("<p>Payment using PayPal in progress ...</p>",
				dialog_->contents());

    dialogCancelButton_ = new Wt::WPushButton("Cancel", dialog_->contents());
    dialogCancelButton_->clicked().connect(this, &PayPalApplication::cancel);

    dialog_->show();
  }

  void onPaymentApproval(const Wt::Payment::Approval& approval)
  {
    enableUpdates(false);
    triggerUpdate();

    if (!approval.error()) {
      switch (approval.outcome()) {
      case Wt::Payment::Approval::Accepted:
	updatePaymentDialog("<p>Payment successful.</p>"
			    "<p>Fetching payment details...</p>",
			    false);

        /* expressCheckout_->updateCustomerDetails() :
         * GetExpressCheckoutDetails API call: updates the customer
         * information.
         * .connect(this, &PayPalApplication::onCustomerDetails)
         * Call onCustomerDetails with paypal response(resulte).
         * The responce containes all the information that paypal has
         */
	expressCheckout_->updateCustomerDetails()
	  .connect(this, &PayPalApplication::onCustomerDetails);

	enableUpdates(true);

	break;

      case Wt::Payment::Approval::Denied:
      case Wt::Payment::Approval::Interrupted:
	cancel();

	break;
      }
    } else {
      cancel();
      showError("Error obtaining payment approval");
    }
  }

  void onCustomerDetails(const Wt::Payment::Result& result)
  {
    enableUpdates(false);
    triggerUpdate();

    clearDialog();

    if (!result.error()) {
      root()->clear();

      new Wt::WText(Wt::WString::tr("confirm.title"), root());

      printCustomer(expressCheckout_->customer());
      printOrder(expressCheckout_->order(), false);

      payment_ = new Wt::WContainerWidget(root());
      payment_->setStyleClass("payment");
      Wt::WPushButton *payB
	= new Wt::WPushButton("Confirm payment", payment_);

      payB->clicked().connect(this, &PayPalApplication::confirm);
      payB->clicked().connect(payB, &Wt::WPushButton::disable);
    } else {
      cancel();
      showError("Error while fetching payment details.");
    }

    printResultMessage(result);
  }

  void confirm()
  {
    expressCheckout_->
      completePayment(expressCheckout_->order().totalItemCost()).
      connect(this, &PayPalApplication::onConfirmed);
    enableUpdates(true);

    dialog_ = new Wt::WDialog("Information");
    dialogText_ = new Wt::WText("<p>Confirming payment...</p>",
				dialog_->contents());

    dialog_->show();
  }

  void onConfirmed(const Wt::Payment::Result& result)
  {
    enableUpdates(false);
    triggerUpdate();

    clearDialog();

    if (!result.error()) {
      root()->clear();
      new Wt::WText("Thanks for shopping with us !", root());
    } else {
      cancel();
      Wt::WString errorStr("Could not complete the payment. \n ");
      errorStr += result.errorMessage();
      showError(errorStr );
    }

    printResultMessage(result);
  }

  void updatePaymentDialog(const Wt::WString& text, bool enableCancel)
  {
    dialogText_->setText(text);
    dialogCancelButton_->setDisabled(!enableCancel);
  }

  void cancel()
  {
    clearDialog();

    if (expressCheckout_)
      delete expressCheckout_;

    expressCheckout_ = 0;

    reviewOrder();
  }

  void clearDialog()
  {
    delete dialog_;
    dialog_ = 0;
  }

  void showError(const Wt::WString& message)
  {
    dialog_ = new Wt::WMessageBox("Error", message, Wt::NoIcon, Wt::Ok);
    dialog_->exec();
  }

  void printResultMessage(const Wt::Payment::Result& result)
  {
    root()->addWidget(new Wt::WBreak());
    root()->addWidget(new Wt::WBreak());

    Wt::WPushButton *infoB = new Wt::WPushButton("Info", root());

    infoB->clicked().connect(
          boost::bind(&PayPalApplication::showInfo, this, result));
  }

  void printCustomer(const Wt::Payment::Customer& customer)
  {
    Wt::WTemplate *t = new Wt::WTemplate(Wt::WString::tr("customer.info"),
					 root());

    t->bindString("firstName", customer.firstName());
    t->bindString("lastName", customer.lastName());
    t->bindString("email", customer.email());
    t->bindString("locale", customer.locale());
    t->bindString("payerId", customer.payerId());
    t->bindString("street1", customer.shippingAddress().street1());
    t->bindString("street2", customer.shippingAddress().street2());
    t->bindString("zip", customer.shippingAddress().zip());
    t->bindString("city", customer.shippingAddress().city());
    t->bindString("state", customer.shippingAddress().state());
    t->bindString("countryCode", customer.shippingAddress().countryCode());
    t->bindString("phoneNumber", customer.shippingAddress().phoneNumber());
  }

  void printOrder(const Wt::Payment::Order &order, bool showDetails)
  {
    Wt::WTemplate *t = new Wt::WTemplate(Wt::WString::tr("order.info"),
					 root());

    t->bindString("itemTotalCost", order.totalItemCost().toString());
    t->bindString("tax", order.tax().toString());
    t->bindString("handlingCost", order.handling().toString());
    t->bindString("shippingCost", order.shipping().toString());
    t->bindString("shippingDiscount", order.shippingDiscount().toString());
    t->bindString("shippingInsurance", order.shippingInsurance().toString());
    t->bindString("totalCost", order.totalOrderCost().toString());

    if (showDetails && order.items().size() > 0) {
      Wt::WContainerWidget *items = new Wt::WContainerWidget();
      items->addStyleClass("items");
      items->addWidget(new Wt::WText(Wt::WString::tr("items.header")));

      for (unsigned i = 0; i < order.items().size(); ++i) {
	const Wt::Payment::OrderItem &item = order.items()[i];
	Wt::WTemplate *it = new Wt::WTemplate(Wt::WString::tr("item.info"));
	it->bindString("name", item.name());
	it->bindString("description", item.description());
	it->bindString("number", item.number());
	it->bindString("quantity",
		       boost::lexical_cast<std::string>(item.quantity()));
	it->bindString("unitCost", item.unitCost().toString());
	it->bindString("totalCost",
		       (item.unitCost() * item.quantity()).toString());

	items->addWidget(it);
      }
      
      t->bindWidget("items", items);
    } else
      t->bindEmpty("items");
  }

  void showInfo(const Wt::Payment::Result& result)
  {
    Wt::WDialog dialog("Info");
    Wt::WContainerWidget *container = new Wt::WContainerWidget();

    container->addWidget(new Wt::WText("Request message:"));
    container->addWidget(new Wt::WBreak());
    container->addWidget(new Wt::WBreak());

    std::map<std::string, std::string> map = result.requestMessage();
    std::map<std::string, std::string>::iterator it;

    for (it = map.begin(); it != map.end(); ++it) {
      Wt::WStringStream text;
      text << (*it).first << " = "
           << Wt::Utils::urlDecode((*it).second);
      container->addWidget(new Wt::WText(Wt::WString(text.str())));
      container->addWidget(new Wt::WBreak());
    }

    container->addWidget(new Wt::WBreak());
    container->addWidget(new Wt::WText("Paypal response message:"));
    container->addWidget(new Wt::WBreak());
    container->addWidget(new Wt::WBreak());

    map = result.responseMessage();

    for(it = map.begin(); it != map.end(); ++it){
      Wt::WStringStream text;
      text << (*it).first << " = " << (*it).second;
      container->addWidget(new Wt::WText(Wt::WString(text.str())));
      container->addWidget(new Wt::WBreak());
    }

    container->setOverflow(Wt::WContainerWidget::OverflowScroll);
    dialog.resize("70%", "70%");

    Wt::WVBoxLayout *layout = new Wt::WVBoxLayout(dialog.contents());
    layout->addWidget(container, 1);

    Wt::WPushButton ok("Close");
    layout->addWidget(&ok, 0, Wt::AlignCenter);

    ok.clicked().connect(&dialog, &Wt::WDialog::accept);

    dialog.exec();
  }

  Wt::Payment::Order createOrder()
  {
    Wt::Payment::OrderItem item1, item2;

    item1.setName("Waffle Maker");
    item1.setNumber("00001");
    item1.setDescription("Emweb FlipSide Belgian Waffle Maker");
    item1.setQuantity(1);
    item1.setUnitCost(Wt::Payment::Money(49, 99, "USD"));

    item2.setName("Waffle Mix");
    item2.setNumber("00002");
    item2.setDescription("Mix for authentic Belgian Luikse Waffles");
    item2.setQuantity(2);
    item2.setUnitCost(Wt::Payment::Money(4, 99, "USD"));

    Wt::Payment::Order order;

    order.items().push_back(item1);
    order.items().push_back(item2);

    order.setHandling(Wt::Payment::Money(0, 99, "USD"));
    order.setShipping(Wt::Payment::Money(7, 1, "USD"));
    order.setShippingDiscount(Wt::Payment::Money(-7, 0, "USD"));
    order.setShippingInsurance(Wt::Payment::Money(2, 23, "USD"));
    order.setTax(Wt::Payment::Money(11, 63, "USD"));

    order.setTotalItemCost(order.computeTotalItemCost());
    order.setTotalOrderCost(order.computeTotalOrderCost());

    return order;
  }

  Wt::Payment::Customer createCustomer()
  {
    Wt::Payment::Customer customer;

    /*
     * This is optional, may help a user register with Paypal.
     */

    /*
    customer.setEmail("Waffle@emwab.be");
    customer.setFirstName("Name");
    customer.setLastName("LastName");

    Wt::Payment::Address address;
    address.setCity("Leuven");
    address.setCountryCode("BE");
    address.setPhoneNumber("123456789");
    address.setStreet2("Brusselsstraat");

    customer.setShippingAddress(address);
    */

    return customer;
  }

};

Wt::WApplication *createApplication(const Wt:: WEnvironment& env)
{
  return new PayPalApplication(env);
}

int main(int argc, char **argv)
{
  try {
    Wt::WServer server(argv[0]);

    server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);
    server.addEntryPoint(Wt::Application, createApplication);

    payPalService = new Wt::Payment::PayPalService();

    if (!payPalService->configureFromProperties())
      payPalService->configureTestSandbox();

    if (server.start()) {
      Wt::WServer::waitForShutdown();
      server.stop();
    }
  } catch (Wt::WServer::Exception& e) {
    std::cerr << e.what() << std::endl;
  } catch (std::exception &e) {
    std::cerr << "exception: " << e.what() << std::endl;
  }

  delete payPalService;
}