-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsendInvoice.js
More file actions
262 lines (213 loc) · 7.15 KB
/
sendInvoice.js
File metadata and controls
262 lines (213 loc) · 7.15 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
function sendPaypalInvoice(e) {
var rowStart=e.range.rowStart;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(rowStart, 1, 1, 16);
var values = range.getValues();
var invoicesent=0;
var errorMessage='No Error Found';
var client_id='';
var secret_id='';
try{
var authorizationToken;
var authorizationObj = getAuthorizationToken(client_id,secret_id);
if(authorizationObj.error==true){
errorMessage=authorizationObj.message;
throw(new Error(errorMessage));
}
authorizationToken=authorizationObj.access_token;
var namedValues=e.namedValues;
var invoiceData=getInvoiceDetailsFromMail(namedValues);
if(invoiceData.error){
throw(new Error(invoiceData.message));
}
//check and validate invoiceData:= check valid email and the invoice amount
var draftInvoiceObject=createInvoiceDraft(invoiceData,authorizationToken);
if(draftInvoiceObject.error){
throw(new Error(JSON.stringify(draftInvoiceObject)));
}
var invoiceConfirmation = sendDraftInvoice(draftInvoiceObject.id,authorizationToken);
if(invoiceConfirmation.error){
throw(new Error(JSON.stringify(invoiceConfirmation)));
}
invoicesent=1;
values[0][15]="Invoice Sent";
}catch(err){
values[0][15]=err.message;
Logger.log(err.message);
MailApp.sendEmail("","Contact Admin- Automated invoicing Api not working",err.message);
}
range.setValues(values);
}
function sendDraftInvoice(invoiceId,authorizationToken){
head = {
'Authorization':"Bearer "+ authorizationToken,
'Content-Type': 'application/json'
}
params = {
headers: head,
method : "post",
muteHttpExceptions: true
}
tokenEndpoint='https://api.paypal.com/v1/invoicing/invoices/'+invoiceId+'/send';
request = UrlFetchApp.getRequest(tokenEndpoint, params);
response = UrlFetchApp.fetch(tokenEndpoint, params);
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
var invoiceResponse={};
if (responseCode === 202) {
invoiceResponse.error=false;
return invoiceResponse;
} else {
invoiceResponse.error=true;
invoiceResponse.message=Utilities.formatString("Request failed. Expected 202, got %d: %s", responseCode, responseBody);
return invoiceResponse;
}
}
function createInvoiceDraft(invoiceData, authorizationToken){
head = {
'Authorization':"Bearer "+ authorizationToken,
'Content-Type': 'application/json'
}
params = {
headers: head,
method : "post",
muteHttpExceptions: true,
payload:JSON.stringify(invoiceData)
}
tokenEndpoint='https://api.paypal.com/v1/invoicing/invoices';
request = UrlFetchApp.getRequest(tokenEndpoint, params);
response = UrlFetchApp.fetch(tokenEndpoint, params);
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
var invoiceResponse={};
if (responseCode === 201) {
var responseJson = JSON.parse(responseBody);
invoiceResponse.error=false;
invoiceResponse.id=responseJson.id;
} else {
invoiceResponse.error=true;
invoiceResponse.message=Utilities.formatString("Request failed. Expected 200, got %d: %s", responseCode, responseBody);
}
return invoiceResponse;
}
function getAuthorizationToken(client_id,secret_id){
var tokenEndpoint = "https://api.paypal.com/v1/oauth2/token";
var head = {
'Authorization':"Basic "+ Utilities.base64Encode(client_id+':'+secret_id),
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
var postPayload = {
"grant_type" : "client_credentials"
}
var params = {
headers: head,
contentType: 'application/x-www-form-urlencoded',
method : "post",
muteHttpExceptions: true,
payload : postPayload
}
var request = UrlFetchApp.getRequest(tokenEndpoint, params);
var response = UrlFetchApp.fetch(tokenEndpoint, params);
var responseCode = response.getResponseCode()
var responseBody = response.getContentText()
if (responseCode === 200) {
var tokenResponse={};
var responseJson = JSON.parse(responseBody);
if(responseJson&&responseJson.error){
tokenResponse.error=true;
tokenResponse.message=responseJson.error;
return tokenResponse;
}
if(responseJson.access_token){
tokenResponse.error=false;
tokenResponse.access_token=responseJson.access_token;
return tokenResponse;
}
tokenResponse.error=true;
tokenResponse.message='Access Token not found';
return tokenResponse;
} else {
var tokenResponse={};
tokenResponse.error=true;
tokenResponse.message=Utilities.formatString("Request failed. Expected 200, got %d: %s", responseCode, responseBody);
return tokenResponse;
}
}
function getInvoiceDetailsFromMail(e){
var i =0;
var data={};
data.logo_url="https://pics.paypal.com/00/s/OTdYMjA5WFBORw/p/MDBjZTNkOTUtYTU1MC00ZGY2LWE4YmQtYjUzNzcwZDE0OTQw/image_109.PNG";
var itemsFound=0;
data.cc_info=[{email:'hamza.agreed@gmail.com'},
{email:'hamza.agreed@gmail.com'},
{email:'hamza.agreed@gmail.com'}
];
data.merchant_info={};
data.merchant_info.email="agreedtech.og@gmail.com";
data.merchant_info.address= {
"line1": "2515, westbankcroft street",
"city": "New Delhi",
"state": "NCT-Delhi",
"postal_code": "110025",
"country_code": "IN"
}
data.merchant_info.business_name="Agreed Technologies Private Limited";
data.merchant_info.website="www.agreedtechnologies.com" ;
var tempBillingInfo={};
tempBillingInfo.email=e['Billing Email'][0].trim();
if(e['First Name'][0].trim().length>0){
tempBillingInfo.first_name=e['First Name'][0].trim();
}
if(e['Last Name'][0].trim().length>0){
tempBillingInfo.first_name=e['Last Name'][0].trim();
}
data.items=[];
for(i=1;i<=3;i++){
var flag=1;
var temp={};
if(e['Item '+i+' Description'][0].trim().length>0){
temp.name=e['Item '+i+' Description'][0].trim();
}else{
flag=0;
}
if(e['Item '+i+' Value'][0].trim().length>0){
temp.quantity=e['Item '+i+' Value'][0].trim();
}else{
flag=0;
}
if(e['Item '+i+' Quantity'][0].trim().length>0){
temp.unit_price={
"currency": "USD",
"value": e['Item '+i+' Quantity'][0].trim()
}
itemsFound=itemsFound+1;
}else{
flag=0;
}
if(flag==1){
data.items.push(temp);
}
}
data['merchant_memo']=e['Type of Sale'][0].trim()+'-'+e['Names'][0].trim();
var error='';
var errorFlag=0;
if(tempBillingInfo&&tempBillingInfo.email){
data.billing_info=[];
data.billing_info.push(tempBillingInfo);
}else{
errorFlag=1;
var tempData={};
tempData.error=true;
tempData.message='Billing Email missing';
return tempData;
}
if(itemsFound==0){
var tempData={};
tempData.error=true;
tempData.message='Items not found';
return tempData;
}
return data;
}