-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaePaySoh.js
99 lines (74 loc) · 2.9 KB
/
MaePaySoh.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
// Anonymous function
(function () {
// MaePaySoh returns new Library object that hold the function.
var MaePaySoh = function (appkey) {
return new Library(appkey);
};
var Library = function (appkey) {
this.appkey=appkey;
this.method="GET";
this.url="http://api.maepaysoh.org/";
this.async=false;
this.onError=function(req){
};
this.onCancel=function(req){
};
this.xhr = new XMLHttpRequest();
this.xhr.responseType = "json";
this.xhr.addEventListener("error", this.onError, false);
this.xhr.addEventListener("abort", this.onCancel, false);
this.token=localStorage.getItem(this.appkey);
var lib=this;
this.generateToken=function(callback){
if(lib.token===null){
lib.xhr.onload=function(req){
if(typeof req.srcElement.response._meta.status!=='undefined' && req.srcElement.response._meta.status==='ok'){
lib.token=req.srcElement.response.data.token;
console.log('token generated:'+lib.token);
localStorage.setItem(lib.appkey, lib.token);
callback();
}
};
lib.xhr.open('POST', lib.url+'token/generate');
var formData = new FormData();
formData.append('api_key', lib.appkey);
lib.xhr.send(formData);
}
else{
callback();
}
}
this.request=function(options){
if(typeof options.endpoint==='undefined')
throw new Error('No endpoint defined!');
var constructParams=function(params){
url = Object.keys(params).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
}).join('&');
return url;
};
var send=function(options){
lib.xhr.onload=options.onComplete;
var url=lib.url+options.endpoint+'?token='+lib.token;
if(typeof options.params!=='undefined'){
url=lib.url+options.endpoint+'?token='+lib.token+'&'+constructParams(options.params)
}
lib.xhr.open(lib.method,url);
lib.xhr.send();
};
if(lib.token===null){
this.generateToken(function(){
send(options)
});
}
else{
send(options);
}
};
return this;
};
// Assign our MaePaySoh object to global window object.
if(!window.MaePaySoh) {
window.MaePaySoh = MaePaySoh;
}
})();