1- import { parseRequestUrl } from '../utils' ;
2- import { getOrder } from '../api' ;
1+ import {
2+ parseRequestUrl ,
3+ showLoading ,
4+ hideLoading ,
5+ showMessage ,
6+ rerender ,
7+ } from '../utils' ;
8+ import { getOrder , getPaypalClientId , payOrder } from '../api' ;
39
10+ const addPaypalSdk = async ( totalPrice ) => {
11+ const clientId = await getPaypalClientId ( ) ;
12+ showLoading ( ) ;
13+ if ( ! window . paypal ) {
14+ const script = document . createElement ( 'script' ) ;
15+ script . type = 'text/javascript' ;
16+ script . src = 'https://www.paypalobjects.com/api/checkout.js' ;
17+ script . async = true ;
18+ script . onload = ( ) => handlePayment ( clientId , totalPrice ) ;
19+ document . body . appendChild ( script ) ;
20+ } else {
21+ handlePayment ( clientId , totalPrice ) ;
22+ }
23+ } ;
24+ const handlePayment = ( clientId , totalPrice ) => {
25+ window . paypal . Button . render (
26+ {
27+ env : 'sandbox' ,
28+ client : {
29+ sandbox : clientId ,
30+ production : '' ,
31+ } ,
32+ locale : 'en_US' ,
33+ style : {
34+ size : 'responsive' ,
35+ color : 'gold' ,
36+ shape : 'pill' ,
37+ } ,
38+
39+ commit : true ,
40+ payment ( data , actions ) {
41+ return actions . payment . create ( {
42+ transactions : [
43+ {
44+ amount : {
45+ total : totalPrice ,
46+ currency : 'USD' ,
47+ } ,
48+ } ,
49+ ] ,
50+ } ) ;
51+ } ,
52+ onAuthorize ( data , actions ) {
53+ return actions . payment . execute ( ) . then ( async ( ) => {
54+ showLoading ( ) ;
55+ await payOrder ( parseRequestUrl ( ) . id , {
56+ orderID : data . orderID ,
57+ payerID : data . payerID ,
58+ paymentID : data . paymentID ,
59+ } ) ;
60+ hideLoading ( ) ;
61+ showMessage ( 'Payment was successfull.' , ( ) => {
62+ rerender ( OrderScreen ) ;
63+ } ) ;
64+ } ) ;
65+ } ,
66+ } ,
67+ '#paypal-button'
68+ ) . then ( ( ) => {
69+ hideLoading ( ) ;
70+ } ) ;
71+ } ;
472const OrderScreen = {
573 after_render : async ( ) => { } ,
674 render : async ( ) => {
@@ -19,6 +87,9 @@ const OrderScreen = {
1987 isPaid,
2088 paidAt,
2189 } = await getOrder ( request . id ) ;
90+ if ( ! isPaid ) {
91+ addPaypalSdk ( totalPrice ) ;
92+ }
2293 return `
2394 <div>
2495 <h1>Order ${ _id } </h1>
@@ -83,7 +154,8 @@ const OrderScreen = {
83154 <li><div>Items</div><div>$${ itemsPrice } </div></li>
84155 <li><div>Shipping</div><div>$${ shippingPrice } </div></li>
85156 <li><div>Tax</div><div>$${ taxPrice } </div></li>
86- <li class="total"><div>Order Total</div><div>$${ totalPrice } </div></li>
157+ <li class="total"><div>Order Total</div><div>$${ totalPrice } </div></li>
158+ <li><div class="fw" id="paypal-button"></div></li>
87159 <li>
88160
89161 </div>
0 commit comments