@@ -16,8 +16,64 @@ interface ILeadInformation {
1616@Injectable ( )
1717export class LeadService {
1818 private log = process . env . NODE_ENV === 'local' ;
19+ private maAccessTokenDate : Date ;
20+ private maAccessToken : string ;
21+
22+ private async getMaAccessToken ( ) : Promise < string > {
23+ if (
24+ this . maAccessToken &&
25+ this . maAccessTokenDate &&
26+ new Date ( ) . getTime ( ) - this . maAccessTokenDate . getTime ( ) < 3500000
27+ ) {
28+ if ( this . log ) console . log ( 'Using cached ma access token' ) ;
29+
30+ // 3500000 = 58 minutes
31+ return this . maAccessToken ;
32+ }
33+ if ( process . env . LEAD_REFRESH_TOKEN && process . env . LEAD_CLIENT_ID && process . env . LEAD_CLIENT_SECRET ) {
34+ // eslint-disable-next-line max-len
35+ const url = `https://accounts.zoho.com/oauth/v2/token?client_id=${ process . env . LEAD_CLIENT_ID } &grant_type=refresh_token&client_secret=${ process . env . LEAD_CLIENT_SECRET } &refresh_token=${ process . env . LEAD_REFRESH_TOKEN } ` ;
36+ if ( this . log ) console . log ( 'Lead URL' , url ) ;
37+
38+ const response = await axios . post ( url ) ;
39+ this . maAccessTokenDate = new Date ( ) ;
40+ this . maAccessToken = response . data . access_token ;
41+ if ( this . log ) console . log ( 'New access token generated' , this . maAccessToken ) ;
42+
43+ return response . data . access_token ;
44+ }
45+
46+ return undefined ;
47+ }
1948
2049 public async createLead ( data : ILeadInformation ) : Promise < void > {
50+ const maAccessToken = await this . getMaAccessToken ( ) ;
51+ if ( maAccessToken ) {
52+ const leadData = JSON . stringify ( {
53+ 'First Name' : data [ 'First Name' ] ,
54+ 'Last Name' : data [ 'Last Name' ] ,
55+ 'Lead Email' : data [ 'Lead Email' ] ,
56+ } ) ;
57+ // Add Lead to marketing automation
58+ // eslint-disable-next-line max-len
59+ const maUrl = `https://marketingautomation.zoho.com/api/v1/json/listsubscribe?listkey=${ process . env . LEAD_LIST_KEY } &leadinfo=${ leadData } &topic_id=${ process . env . LEAD_TOPIC_ID } ` ;
60+ if ( this . log ) console . log ( maUrl ) ;
61+
62+ try {
63+ const maResponse = await axios . post (
64+ maUrl ,
65+ { } ,
66+ {
67+ headers : {
68+ Authorization : `Zoho-oauthtoken ${ maAccessToken } ` ,
69+ } ,
70+ }
71+ ) ;
72+ if ( this . log ) console . log ( 'Lead created' , maResponse . data ) ;
73+ } catch ( error ) {
74+ captureException ( error ) ;
75+ }
76+ }
2177 if ( process . env . LEAD_MAKE_WEBHOOK_URL ) {
2278 try {
2379 await axios . post ( process . env . LEAD_MAKE_WEBHOOK_URL , {
0 commit comments