-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
59 lines (54 loc) · 2.06 KB
/
worker.js
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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = 'https://api.helpscout.net/v2/conversations'; // Help Scout API endpoint
const json = await request.json(); // Parse the received JSON
const { searchParams } = new URL(request.url); // Get the query parameters from the request URL
const mailboxId = searchParams.get('mailboxId'); // Get the mailboxId parameter from the query parameters
const name = searchParams.get('name'); // Get the name parameter from the query parameters
if (json.message && json.message.name === name && mailboxId) {
const tokenUrl = 'https://api.helpscout.net/v2/oauth2/token';
const tokenPayload = {
grant_type: 'client_credentials',
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
};
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
body: JSON.stringify(tokenPayload),
headers: {
'Content-Type': 'application/json'
}
});
const tokenJson = await tokenResponse.json();
const accessToken = tokenJson.access_token;
const payload = {
"subject": json.message.name,
"customer": {
"id": json._embedded.customer.id
},
"mailboxId": mailboxId,
"type": "email",
"status": "active",
"threads": [{
"type": "customer",
"customer": {
"id": json._embedded.customer.id
},
"text": json.response.comment
}],
}
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
"Authorization": `Bearer ${accessToken}`
}
});
return response;
} else {
return new Response('Message error', { status: 400 });
}
}