-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathAmoCRM.js
115 lines (86 loc) · 2.38 KB
/
AmoCRM.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
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
let libPrefix = 'LibAMO_CRM_'
let setUserLogin = function(login){
Bot.setProperty( libPrefix + 'userLogin', login, 'string');
}
let setApiKey = function(hash){
Bot.setProperty( libPrefix + 'apiKey', hash, 'string');
}
let setSubDomain = function(subDomain){
Bot.setProperty( libPrefix + 'subDomain', subDomain, 'string');
}
let loadOptions = function(){
return {
user: {
USER_LOGIN: Bot.getProperty( libPrefix + 'userLogin'),
USER_HASH: Bot.getProperty( libPrefix + 'apiKey' )
},
subDomain: Bot.getProperty( libPrefix + 'subDomain')
}
}
let loadCRMCredentials = function(){
// need cookie loading...
let credentials = loadOptions();
credentials.cookies = Bot.getProperty( libPrefix + 'cookies');
return credentials;
}
function verifyCallback(prms){
if(typeof(prms.onSuccess)!='string'){
throw 'Need handler callback command';
}
return true
}
function apiCallAs(apiMethod, options){
// if(!verifyCallback(prms)){ return }
let credentials = loadCRMCredentials();
let url = 'https://' + credentials.subDomain + '.amocrm.ru/api/v2/' +
options.method;
let body = options.params;
if(!body){ body = "" }
params = {
url: url,
body: body,
cookies: credentials.cookies,
success: libPrefix + 'onApiResponse ' + options.onSuccess,
// error: callbacks.onError
}
if(apiMethod=="get"){ return HTTP.get( params ) }
HTTP.post( params )
}
function apiGet(options = {}){
apiCallAs("get", options)
}
function apiPost(options = {}){
apiCallAs("post", options)
}
function onApiResponse(){
let json = JSON.parse(content);
Bot.runCommand(params, {body: json} );
}
function auth(){
let options = loadOptions();
let url = 'https://' + options.subDomain + '.amocrm.ru/private/api/auth.php?type=json'
HTTP.post( {
url: url,
body: options.user,
success: libPrefix + "SaveCookies",
// error: callbacks.onError
} )
}
function onSaveCookies(){
let json = JSON.parse(content);
if(json.response.auth){
Bot.setProperty( libPrefix + 'cookies', cookies, 'text');
}else{
Bot.sendMessage( "Error with autorization to AmoCRM. Invalid credentials?" );
}
}
publish({
setUserLogin: setUserLogin,
setApiKey: setApiKey,
setSubDomain: setSubDomain,
auth: auth,
apiGet: apiGet,
apiPost: apiPost
})
on(libPrefix + "SaveCookies", onSaveCookies);
on(libPrefix + 'onApiResponse', onApiResponse);