Skip to content

Commit

Permalink
server code WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam Ban committed Sep 15, 2022
1 parent b7b7783 commit 3427f9b
Show file tree
Hide file tree
Showing 7 changed files with 101 additions and 164 deletions.
38 changes: 17 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,23 @@ How to use:
- Scope can be "Admin client" (not recommended) or "Manage" Cart discounts and Discount codes
- Download the created API client's "Environment variables (.env)" file before closing the popup
- Add the .env file to the project root
- Run `node get-cart-discounts.js`, copy the desired ID (UUID format, like `f9c4718e-0792-4f08-a802-70f81ef9d46d`)
- Run `node generate-discount-codes.js STUD20- f9c4718e-0792-4f08-a802-70f81ef9d46d 20 > newcodes.csv`
- Check `newcodes.csv` for the generated discount codes
- Sanity check the generated discount codes in Merchant Center > Discounts > Discount code list
- Test code behaviours in the cart without using them, or by removing the used up codes from the csv
- On https://my.sheerid.com/
- Create a SheerID program, e.g. "Student discount"
- Upload `newcodes.csv` to the Codes step "Single-Use Codes" card
- Copy the Web URL from Publish step "New Page"

- Add the copied Web URL to your website as a banner link or button
- Test linked banner on your website, fill the form, copy the code and test cart and checkout (the code will be invalidated in SheerID system immediately after successful verification)
- Don't forget to switch the program to Live mode on https://my.sheerid.com/

## Server for SheerID webhook

As an example for running a server providing a webhook endpoint for [SheerID Settings](https://my.sheerid.com/settings) Webhook (coming), see `server.js`.

To avoid the need of changing `.env` file `server.js` has several hardcoded entries that should be part of configuration,
like port.
The created cart rules are not "empty", but they need setting up in Merchant Center after the webhook.
- Log in to your SheerID Dashboard and
- Create a SheerID program, that you will use e.g. "Student discount"
- Configure your program with eligibility, theme etc
- Set Codes section to "No Code"
- In Program Settings
- set Webhook for eligible verification to `https://<your_server_address>/api/success-webhook`
- add cartid as Campaign Metadata field
- Copy access token from Settings > Access Tokens page
- Edit the downloaded .env file, add
```
SHEERID_TOKEN=<your copied SheerID Access Token>
SHEERID_API_URL=https://services.sheerid.com/rest/v2/
URL=https://sheeriddemo.gpmd.net/
PORT=8080
```
- Run `node server.js` or `yarn server` to run the bridge application.
- Check that it's running by visiting the server URL indicated by the application.

## This repository

Expand Down
63 changes: 0 additions & 63 deletions generate-discount-codes.js

This file was deleted.

29 changes: 0 additions & 29 deletions get-cart-discounts.js

This file was deleted.

30 changes: 0 additions & 30 deletions get-discount-codes.js

This file was deleted.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
},
"dependencies": {
"dotenv": "^16.0.2",
"node-fetch": "^3.2.10"
"node-fetch": "^3.2.10",
"redis": "^4.3.1"
},
"imports": {
"@/*": "./src/*"
Expand Down
66 changes: 58 additions & 8 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,41 @@
import { config } from 'dotenv';
import { config } from './src/config.js';
import http from 'http';
import { auth } from './src/auth.js';
import url from 'url';
import { createClient } from 'redis';
import { createWebhook, getVerification } from './src/sheerid.js';

const redis = createClient();
redis.on('error', (err) => console.log('Redis Client Error', err));

console.log('connecting to Redis...');
await redis.connect();

const verificationStatus = async (verificationId) => {
return await getVerification(verificationId);
}

const onSuccess = async (cartId, verificationData) => {
// create new discount code
// add directDiscount to cart
return await redis.set(`cart-${cartId}`, JSON.stringify(verificationData))
}

import { getCartDiscounts, createCartDiscount, createDiscountCode } from './src/discount.js';

const token = await auth();

http.createServer(async (req, res) => {
if (req.url === '/' && req.method === 'GET') {
console.log('get /');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('SheerID - commercetools Demo server');
} else if (req.url === '/cart-discounts' && req.method === 'GET') {
} else if (req.url.startsWith('/api/create-webhook')) {
const q = url.parse(req.url, true).query;
const r = await createWebhook(q.pid);
res.end(JSON.stringify(r));
} else if (req.url === '/api/cart-discounts' && req.method === 'GET') {
console.log('get /api/cart-discounts');
res.writeHead(200, {'Content-Type': 'application/json'});
const discounts = await getCartDiscounts(token.access_token);
console.log('number of discounts:', discounts.total);
Expand All @@ -20,19 +45,43 @@ http.createServer(async (req, res) => {
o[element.id] = element.name.en;
});
res.end(JSON.stringify(o));
} else if (req.url === '/success-webhook' && req.method === 'POST') {
} else if (req.url.startsWith('/api/verify') && req.method === 'GET') {
const q = url.parse(req.url, true).query;
console.log('get /api/verify', q.cid);
let cartJson = await redis.get(`cart-${q.cid}`)
if (cartJson === null) {
cartJson = `{}`;
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(cartJson);
} else if (req.url === '/api/success-webhook' && req.method === 'POST') {
console.log('post /api/success-webhook');
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
res.end('OK');
if (body != undefined && body.length > 0) {
const discount = JSON.parse(body);
createDiscountCode("SHEERID-", discount.name, cartDiscountId);
const res = JSON.parse(body);
verificationStatus(res.verificationId).then((r) => {
try {
if (r.personInfo?.metadata != undefined) {
const cartId = r.personInfo.metadata.cartid;
console.log(`saving ${cartId} cart id`);
onSuccess(cartId, r);
updateStatus(cartId, r);
} else {
console.log('no metadata', r);
}
} catch(err) {
console.log('error:', err);
}
});
}
});
} else if (req.url === '/webhook' && req.method === 'POST') {
} else if (req.url === '/api/webhook' && req.method === 'POST') {
console.log('post /api/cart-discounts');
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
Expand All @@ -46,8 +95,9 @@ http.createServer(async (req, res) => {
}
});
} else {
console.log('404', req);
res.statusCode = 404;
res.end('404: File Not Found');
}
}).listen(80);
console.log('server is running on http://localhost/');
}).listen(config.PORT);
console.log(`server is running on http://localhost:${config.PORT}/`);
36 changes: 24 additions & 12 deletions src/sheerid.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
import fetch from 'node-fetch';
import { config } from './config.js';

const createWebhook = async (programID) => {
const createWebhook = async (programId) => {
const res = await fetch(
`${config.SHEERID_API_URL}/rest/v2/program/${programID}/webhook`, {
'method': 'post',
'headers': {
'Authorization': `Basic ${config.SHEERID_TOKEN}`,
'Content-Type': 'application/json'
},
data: {
'scope': config.URL + '/success-webhook'
}
`${config.SHEERID_API_URL}/program/${programId}/webhook`, {
'method': 'POST',
'headers': {
'Authorization': `Bearer ${config.SHEERID_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
'callbackUri': `${config.URL}/api/success-webhook`,
})
});
return await res.json();
return res.json();
}

export { createWebhook };
const getVerification = async (verificationId) => {
const res = await fetch(
`${config.SHEERID_API_URL}/verification/${verificationId}/details`, {
'method': 'GET',
'headers': {
'Authorization': `Bearer ${config.SHEERID_TOKEN}`,
'Content-Type': 'application/json'
},
});
return res.json();
}

export { createWebhook, getVerification };


0 comments on commit 3427f9b

Please sign in to comment.