Skip to content

Commit

Permalink
ejs changes and moved api's to server (#3)
Browse files Browse the repository at this point in the history
* ejs changes and moved api's to server
  • Loading branch information
cnallam authored Sep 19, 2023
1 parent 09513ba commit 46489c7
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 22 deletions.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,19 @@ and configuring your .env config file with your Paypal ClientId and ClientSecret
3. Run `npm run dev`
4. Navigate to `http://localhost:8080/`

### PayPal Codespaces Links
## PayPal Codespaces

PayPal codespaces require a client ID and client secret for your app.

### Link to codespaces

[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/paypal-examples/giropay)

### Learn more

You can read more about codespaces in the [PayPal Developer Docs](https://developer.paypal.com/api/rest/sandbox/codespaces).

### Feedback

* To report a bug or suggest a new feature, create an [issue in GitHub](https://github.com/paypal-examples/paypaldevsupport/issues/new/choose).
* To submit feedback, go to [GitHub Codespaces](https://developer.paypal.com/api/rest/sandbox/codespaces) and select the "Feedback" tab.
60 changes: 44 additions & 16 deletions client/index.js → client/public/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
/* eslint-disable consistent-return, new-cap, no-alert, no-console */

const order = {
purchase_units: [
{
amount: {
currency_code: 'EUR',
value: '49.11',
},
},
]
}

/* Paypal */
paypal
.Marks({
Expand All @@ -26,12 +15,37 @@ paypal
color: "silver",
},
createOrder(data, actions) {
return actions.order.create(order)
return fetch("/api/orders", {
method: "post",
// use the "body" param to optionally pass additional order information
// like product skus and quantities
body: JSON.stringify({
cart: [
{
sku: "<YOUR_PRODUCT_STOCK_KEEPING_UNIT>",
quantity: "<YOUR_PRODUCT_QUANTITY>",
},
],
}),
})
.then((response) => response.json())
.then((order) => order.id);
},
onApprove(data, actions) {
return actions.order.capture().then(function(details) {
alert(`Transaction completed by ${details.payer.name.given_name}!`)
fetch(`/api/orders/${data.orderID}/capture`, {
method: "post",
})
.then((res) => res.json())
.then((data) => {
swal(
"Order Captured!",
`Id: ${data.id}, ${Object.keys(data.payment_source)[0]}, ${
data.purchase_units[0].payments.captures[0].amount.currency_code
} ${data.purchase_units[0].payments.captures[0].amount.value}`,
"success"
);
})
.catch(console.error);
},
})
.render('#paypal-btn')
Expand Down Expand Up @@ -86,10 +100,24 @@ paypal
label: 'pay',
},
createOrder(data, actions) {
return actions.order.create(order)
return fetch("/api/orders", {
method: "post",
// use the "body" param to optionally pass additional order information
// like product skus and quantities
body: JSON.stringify({
cart: [
{
sku: "<YOUR_PRODUCT_STOCK_KEEPING_UNIT>",
quantity: "<YOUR_PRODUCT_QUANTITY>",
},
],
}),
})
.then((response) => response.json())
.then((order) => order.id);
},
onApprove(data, actions) {
fetch(`/capture/${data.orderID}`, {
fetch(`/api/orders/${data.orderID}/capture`, {
method: "post",
})
.then((res) => res.json())
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion client/index.html → client/views/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
<div id="paypal-btn"></div>
<div id="giropay-btn"></div>

<script src="https://www.paypal.com/sdk/js?client-id=AfPbdUbV4LJdK0-0B0QPeUyHnzGgVhIwZfBO3wYRoazaSYRJAIKwwHnfI0EbekJB42FJuVi-3-vgsQvi&components=buttons,payment-fields,marks,funding-eligibility&enable-funding=giropay&currency=EUR"></script>
<script src="https://www.paypal.com/sdk/js?client-id=<%= clientId %>&components=buttons,payment-fields,marks,funding-eligibility&enable-funding=giropay&currency=EUR"></script>

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js" async></script>

Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"dependencies": {
"axios": "^0.21.1",
"dotenv": "^8.2.0",
"express": "^4.17.1"
"express": "^4.17.1",
"ejs": "^3.1.9",
"open": "^8.4.0"
},
"devDependencies": {
"ngrok": "^3.4.0"
Expand Down
50 changes: 47 additions & 3 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const express = require("express");
const { resolve } = require("path");
const axios = require("axios");
const dotenv = require("dotenv");
const open = require("open")

dotenv.config();

Expand All @@ -12,17 +13,60 @@ const app = express();

const port = process.env.PORT || 8080;

app.use(express.static(resolve(__dirname, "../client")));
app.set("view engine", "ejs");
app.set('views', resolve(__dirname, "../client/views"));
app.use(express.static(resolve(__dirname, "../client/public")));

app.use(express.json());

app.get("/", (req, res) => {
res.sendFile(resolve(__dirname, "../client/index.html"));
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
if(!clientId || !clientSecret) {
res.status(500).send('Client ID and/or Client Secret is missing');
} else {
res.render("index", { clientId });
}
});

/**
* Create Order handler.
*/
app.post("/api/orders", async (req, res) => {
// use the cart information passed from the front-end to calculate the purchase unit details
const { cart } = req.body;

const { access_token } = await getAccessToken();
const { data } = await axios({
url: `${PAYPAL_API_BASE}/v2/checkout/orders`,
method: "post",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${access_token}`,
},
data: JSON.stringify({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "EUR",
value: "49.11",
},
},
]
})
});

console.log(`Order Created!`);
res.json(data);
});


/**
* Capture Order handler.
*/
app.post("/capture/:orderId", async (req, res) => {
app.post("/api/orders/:orderId/capture", async (req, res) => {
const { orderId } = req.params

const { access_token } = await getAccessToken();
Expand Down

0 comments on commit 46489c7

Please sign in to comment.