Skip to content

Commit

Permalink
Adding ejs support and codespaces (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
sdarshale authored Sep 20, 2023
1 parent a8c9563 commit bebb975
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 27 deletions.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,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/p24)

### 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.
74 changes: 54 additions & 20 deletions client/index.js → client/public/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
/* eslint-disable no-alert, no-unused-vars */

var order = {
purchase_units: [
{
amount: {
currency_code: "EUR",
value: "99.99",
},
},
]
};

/* Paypal */
paypal
.Marks({
Expand All @@ -25,13 +14,41 @@ paypal
label: "pay",
color: "silver",
},
createOrder(data, actions) {
return actions.order.create(order);
createOrder() {
return fetch("/api/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// 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}!`);
});
return 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 @@ -60,11 +77,28 @@ paypal.Buttons({
style: {
label: "pay",
},
createOrder(data, actions) {
return actions.order.create(order);
createOrder() {
return fetch("/api/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// 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}`, {
onApprove(data) {
return 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="p24-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=p24&currency=EUR"></script>
<script src="https://www.paypal.com/sdk/js?client-id=<%= clientId %>&components=buttons,payment-fields,marks,funding-eligibility&enable-funding=p24&currency=EUR"></script>

<script src="./index.js"></script>

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dependencies": {
"axios": "^0.21.1",
"dotenv": "^8.2.0",
"ejs": "^3.1.9",
"express": "^4.17.1"
},
"devDependencies": {
Expand Down
48 changes: 43 additions & 5 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,53 @@ const { getAccessToken } = require("./oauth");
const { WEBHOOK_ID, PORT, PAYPAL_API_BASE } = require("./config");

const app = express();

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 });
}
});

app.post("/capture/:orderId", async (req, res) => {
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;

Check failure on line 31 in server/index.js

View workflow job for this annotation

GitHub Actions / build

'cart' is assigned a value but never used

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: "99.99",
},
},
]
})
});

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

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

const { access_token } = await getAccessToken();
Expand Down Expand Up @@ -106,4 +144,4 @@ app.post("/webhook", async (req, res) => {
app.listen(PORT, async () => {
await open(`http://localhost:${PORT}`);
console.log(`Example app listening at http://localhost:${PORT}`);
});
});

0 comments on commit bebb975

Please sign in to comment.