Skip to content

Instantly share code, notes, and snippets.

@osv
Created January 8, 2016 11:34
Show Gist options
  • Save osv/0f69866a9128581b58d0 to your computer and use it in GitHub Desktop.
Save osv/0f69866a9128581b58d0 to your computer and use it in GitHub Desktop.
server side paypal class
var paypal = new PaypalSDK();
Meteor.startup(function ObservePaypalSettings() {
/*
var paypalSchema = new SimpleSchema({
enable: {
type: Boolean,
defaultValue: false,
},
isSandBox: {
type: Boolean,
label: 'Use sandbox for paypal (demo mode)',
defaultValue: true,
},
clientId: {
type: String,
min: 50,
optional: true,
},
clientSecret: {
type: String,
min: 50,
optional: true,
}
});
var schema = new SimpleSchema({
// ...
paypal: {
type: paypalSchema,
label: 'Paypal config'
}
});
*/
var query = Settings.find({}, {limit: 1, fields: {paypal: 1}});
query.observeChanges({
added: observeSettings,
changed: observeSettings
});
function observeSettings(id, fields) {
if (fields.paypal) {
paypal.config(fields.paypal);
}
}
});
/*
* Low level paypal REST api
*/
function PaypalSDK() {
this._token = this._url = this._config = undefined;
}
_.extend(PaypalSDK.prototype, {
// congig our sdk
config: function(config) {
if (config) {
this._config = config;
this._url = config.isSandBox ? 'https://api.sandbox.paypal.com'
: 'https://api.paypal.com';
} else {
return this._config;
}
},
isEnabled: function() {
console.log('this.config()', this.config());
return (this.config() || {}).enable;
},
token: function() {
var isTokenValid = 0;
var token = this._token,
paypalConfig = this._config;
if (token) {
isTokenValid = Math.ceil((new Date().getTime() - token.timestamp) / 1000);
}
if (isTokenValid === 0 || isTokenValid > token.expires_in && paypalConfig) {
token = this._payaplToken();
token.timestamp = new Date().getTime();
token.expires_in -= 60; // minus 1 minute expires
this._token = token;
}
return token;
},
_headers: function() {
var token = this.token();
return {
'Authorization': 'Bearer ' + token.access_token,
'Accept': 'application/json',
'Content-Type': 'application/json'
};
},
_payaplToken: function() {
var paypalConfig = this._config;
var auth = paypalConfig.clientId + ':' + paypalConfig.clientSecret;
var token = EJSON.parse(Meteor.http.post(`${this._url}/v1/oauth2/token`, {
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US'
},
auth: auth,
params: {
'grant_type': 'client_credentials'
}
}).content);
return token;
},
paypalCreatePayment: function(payment) {
var res = Meteor.http.post(`${this._url}/v1/payments/payment`, {
headers: this._headers(),
data: payment
});
return res;
},
paypalExecute: function(paymentId, payerId) {
var url = `${this._url}/v1/payments/payment/${paymentId}/execute/`;
var res = Meteor.http.post(url, {
headers: this._headers(),
data: {
payer_id: payerId
}
});
return res;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment