Moved folders to website directory

This commit is contained in:
Blade Barringer
2015-02-03 14:10:55 -06:00
parent 576eec77f7
commit 8a8ce8d80d
92 changed files with 1 additions and 1 deletions
+129
View File
@@ -0,0 +1,129 @@
var iap = require('in-app-purchase');
var async = require('async');
var payments = require('./index');
var nconf = require('nconf');
var inAppPurchase = require('in-app-purchase');
inAppPurchase.config({
// this is the path to the directory containing iap-sanbox/iap-live files
googlePublicKeyPath: nconf.get("IAP_GOOGLE_KEYDIR")
});
// Validation ERROR Codes
var INVALID_PAYLOAD = 6778001;
var CONNECTION_FAILED = 6778002;
var PURCHASE_EXPIRED = 6778003;
exports.androidVerify = function(req, res, next) {
var iapBody = req.body;
var user = res.locals.user;
iap.setup(function (error) {
if (error) {
var resObj = {
ok: false,
data: 'IAP Error'
};
console.error('IAP Setup ERROR');
console.error(error);
res.json(resObj);
return;
}
/*
google receipt must be provided as an object
{
"data": "{stringified data object}",
"signature": "signature from google"
}
*/
var testObj = {
data: iapBody.transaction.receipt,
signature: iapBody.transaction.signature
};
// iap is ready
iap.validate(iap.GOOGLE, testObj, function (err, googleRes) {
if (err) {
var resObj = {
ok: false,
data: {
code: INVALID_PAYLOAD,
message: err.toString()
}
};
res.json(resObj);
console.error(err);
return;
}
if (iap.isValidated(googleRes)) {
var resObj = {
ok: true,
data: googleRes
};
payments.buyGems({user:user, paymentMethod:'IAP GooglePlay'});
// yay good!
res.json(resObj);
}
});
});
};
exports.iosVerify = function(req, res, next) {
console.info(req.body);
var iapBody = req.body;
var user = res.locals.user;
iap.setup(function (error) {
if (error) {
var resObj = {
ok: false,
data: 'IAP Error'
};
console.error('IAP Setup ERROR');
console.error(error);
res.json(resObj);
return;
}
// iap is ready
iap.validate(iap.APPLE, iapBody.transaction.receipt, function (err, appleRes) {
if (err) {
var resObj = {
ok: false,
data: {
code: INVALID_PAYLOAD,
message: err.toString()
}
};
res.json(resObj);
console.error(err);
return;
}
if (iap.isValidated(appleRes)) {
var resObj = {
ok: true,
data: appleRes
};
payments.buyGems({user:user, paymentMethod:'IAP AppleStore'});
// yay good!
res.json(resObj);
}
});
});
};
+140
View File
@@ -0,0 +1,140 @@
/* @see ./routes.coffee for routing*/
var _ = require('lodash');
var shared = require('../../../common');
var nconf = require('nconf');
var utils = require('./../../utils');
var moment = require('moment');
var isProduction = nconf.get("NODE_ENV") === "production";
var stripe = require('./stripe');
var paypal = require('./paypal');
var members = require('../members')
var async = require('async');
var iap = require('./iap');
var mongoose= require('mongoose');
var cc = require('coupon-code');
function revealMysteryItems(user) {
_.each(shared.content.gear.flat, function(item) {
if (
item.klass === 'mystery' &&
moment().isAfter(shared.content.mystery[item.mystery].start) &&
moment().isBefore(shared.content.mystery[item.mystery].end) &&
!user.items.gear.owned[item.key] &&
!~user.purchased.plan.mysteryItems.indexOf(item.key)
) {
user.purchased.plan.mysteryItems.push(item.key);
}
});
}
exports.createSubscription = function(data, cb) {
var recipient = data.gift ? data.gift.member : data.user;
//if (!recipient.purchased.plan) recipient.purchased.plan = {}; // FIXME double-check, this should never be the case
var p = recipient.purchased.plan;
var block = shared.content.subscriptionBlocks[data.gift ? data.gift.subscription.key : data.sub.key];
var months = +block.months;
if (data.gift) {
if (p.customerId && !p.dateTerminated) { // User has active plan
p.extraMonths += months;
} else {
p.dateTerminated = moment(p.dateTerminated).add({months: months}).toDate();
if (!p.dateUpdated) p.dateUpdated = new Date();
}
if (!p.customerId) p.customerId = 'Gift'; // don't override existing customer, but all sub need a customerId
} else {
_(p).merge({ // override with these values
planId: block.key,
customerId: data.customerId,
dateUpdated: new Date(),
gemsBought: 0,
paymentMethod: data.paymentMethod,
extraMonths: +p.extraMonths
+ +(p.dateTerminated ? moment(p.dateTerminated).diff(new Date(),'months',true) : 0),
dateTerminated: null
}).defaults({ // allow non-override if a plan was previously used
dateCreated: new Date(),
mysteryItems: []
});
}
// Block sub perks
var perks = Math.floor(months/3);
if (perks) {
p.consecutive.offset += months;
p.consecutive.gemCapExtra += perks*5;
if (p.consecutive.gemCapExtra > 25) p.consecutive.gemCapExtra = 25;
p.consecutive.trinkets += perks;
}
revealMysteryItems(recipient);
if(isProduction) {
if (!data.gift) utils.txnEmail(data.user, 'subscription-begins');
utils.ga.event('subscribe', data.paymentMethod).send();
utils.ga.transaction(data.user._id, block.price).item(block.price, 1, data.paymentMethod.toLowerCase() + '-subscription', data.paymentMethod).send();
}
data.user.purchased.txnCount++;
if (data.gift) members.sendMessage(data.user, data.gift.member, data.gift);
async.parallel([
function(cb2){data.user.save(cb2)},
function(cb2){data.gift ? data.gift.member.save(cb2) : cb2(null);}
], cb);
}
/**
* Sets their subscription to be cancelled later
*/
exports.cancelSubscription = function(data, cb) {
var p = data.user.purchased.plan,
now = moment(),
remaining = data.nextBill ? moment(data.nextBill).diff(new Date, 'days') : 30;
p.dateTerminated =
moment( now.format('MM') + '/' + moment(p.dateUpdated).format('DD') + '/' + now.format('YYYY') )
.add({days: remaining}) // end their subscription 1mo from their last payment
.add({months: Math.ceil(p.extraMonths)})// plus any extra time (carry-over, gifted subscription, etc) they have. FIXME: moment can't add months in fractions...
.toDate();
p.extraMonths = 0; // clear extra time. If they subscribe again, it'll be recalculated from p.dateTerminated
data.user.save(cb);
if(isProduction) utils.txnEmail(data.user, 'cancel-subscription');
utils.ga.event('unsubscribe', data.paymentMethod).send();
}
exports.buyGems = function(data, cb) {
var amt = data.gift ? data.gift.gems.amount/4 : 5;
(data.gift ? data.gift.member : data.user).balance += amt;
data.user.purchased.txnCount++;
if(isProduction) {
if (!data.gift) utils.txnEmail(data.user, 'donation');
utils.ga.event('checkout', data.paymentMethod).send();
//TODO ga.transaction to reflect whether this is gift or self-purchase
utils.ga.transaction(data.user._id, amt).item(amt, 1, data.paymentMethod.toLowerCase() + "-checkout", "Gems > " + data.paymentMethod).send();
}
if (data.gift) members.sendMessage(data.user, data.gift.member, data.gift);
async.parallel([
function(cb2){data.user.save(cb2)},
function(cb2){data.gift ? data.gift.member.save(cb2) : cb2(null);}
], cb);
}
exports.validCoupon = function(req, res, next){
mongoose.model('Coupon').findOne({_id:cc.validate(req.params.code), event:'google_6mo'}, function(err, coupon){
if (err) return next(err);
if (!coupon) return res.json(401, {err:"Invalid coupon code"});
return res.send(200);
});
}
exports.stripeCheckout = stripe.checkout;
exports.stripeSubscribeCancel = stripe.subscribeCancel;
exports.stripeSubscribeEdit = stripe.subscribeEdit;
exports.paypalSubscribe = paypal.createBillingAgreement;
exports.paypalSubscribeSuccess = paypal.executeBillingAgreement;
exports.paypalSubscribeCancel = paypal.cancelSubscription;
exports.paypalCheckout = paypal.createPayment;
exports.paypalCheckoutSuccess = paypal.executePayment;
exports.paypalIPN = paypal.ipn;
exports.iapAndroidVerify = iap.androidVerify;
exports.iapIosVerify = iap.iosVerify;
+216
View File
@@ -0,0 +1,216 @@
var nconf = require('nconf');
var moment = require('moment');
var async = require('async');
var _ = require('lodash');
var url = require('url');
var User = require('mongoose').model('User');
var payments = require('./index');
var logger = require('../../logging');
var ipn = require('paypal-ipn');
var paypal = require('paypal-rest-sdk');
var shared = require('../../../common');
var mongoose = require('mongoose');
var cc = require('coupon-code');
// This is the plan.id for paypal subscriptions. You have to set up billing plans via their REST sdk (they don't have
// a web interface for billing-plan creation), see ./paypalBillingSetup.js for how. After the billing plan is created
// there, get it's plan.id and store it in config.json
_.each(shared.content.subscriptionBlocks, function(block){
block.paypalKey = nconf.get("PAYPAL:billing_plans:"+block.key);
});
paypal.configure({
'mode': nconf.get("PAYPAL:mode"), //sandbox or live
'client_id': nconf.get("PAYPAL:client_id"),
'client_secret': nconf.get("PAYPAL:client_secret")
});
var parseErr = function(res, err){
//var error = err.response ? err.response.message || err.response.details[0].issue : err;
var error = JSON.stringify(err);
return res.json(400,{err:error});
}
exports.createBillingAgreement = function(req,res,next){
var sub = shared.content.subscriptionBlocks[req.query.sub];
async.waterfall([
function(cb){
if (!sub.discount) return cb(null, null);
if (!req.query.coupon) return cb('Please provide a coupon code for this plan.');
mongoose.model('Coupon').findOne({_id:cc.validate(req.query.coupon), event:sub.key}, cb);
},
function(coupon, cb){
if (sub.discount && !coupon) return cb('Invalid coupon code.');
var billingPlanTitle = "HabitRPG Subscription" + ' ($'+sub.price+' every '+sub.months+' months, recurring)';
var billingAgreementAttributes = {
"name": billingPlanTitle,
"description": billingPlanTitle,
"start_date": moment().add({minutes:5}).format(),
"plan": {
"id": sub.paypalKey
},
"payer": {
"payment_method": "paypal"
}
};
paypal.billingAgreement.create(billingAgreementAttributes, cb);
}
], function(err, billingAgreement){
if (err) return parseErr(res, err);
// For approving subscription via Paypal, first redirect user to: approval_url
req.session.paypalBlock = req.query.sub;
var approval_url = _.find(billingAgreement.links, {rel:'approval_url'}).href;
res.redirect(approval_url);
});
}
exports.executeBillingAgreement = function(req,res,next){
var block = shared.content.subscriptionBlocks[req.session.paypalBlock];
delete req.session.paypalBlock;
async.auto({
exec: function (cb) {
paypal.billingAgreement.execute(req.query.token, {}, cb);
},
get_user: function (cb) {
User.findById(req.session.userId, cb);
},
create_sub: ['exec', 'get_user', function (cb, results) {
payments.createSubscription({
user: results.get_user,
customerId: results.exec.id,
paymentMethod: 'Paypal',
sub: block
}, cb);
}]
},function(err){
if (err) return parseErr(res, err);
res.redirect('/');
})
}
exports.createPayment = function(req, res) {
// if we're gifting to a user, put it in session for the `execute()`
req.session.gift = req.query.gift || undefined;
var gift = req.query.gift ? JSON.parse(req.query.gift) : undefined;
var price = !gift ? 5.00
: gift.type=='gems' ? Number(gift.gems.amount/4).toFixed(2)
: Number(shared.content.subscriptionBlocks[gift.subscription.key].price).toFixed(2);
var description = !gift ? "HabitRPG Gems"
: gift.type=='gems' ? "HabitRPG Gems (Gift)"
: shared.content.subscriptionBlocks[gift.subscription.key].months + "mo. HabitRPG Subscription (Gift)";
var create_payment = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": nconf.get('BASE_URL') + '/paypal/checkout/success',
"cancel_url": nconf.get('BASE_URL')
},
"transactions": [{
"item_list": {
"items": [{
"name": description,
//"sku": "1",
"price": price,
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": price
},
"description": description
}]
};
paypal.payment.create(create_payment, function (err, payment) {
if (err) return parseErr(res, err);
var link = _.find(payment.links, {rel: 'approval_url'}).href;
res.redirect(link);
});
}
exports.executePayment = function(req, res) {
var paymentId = req.query.paymentId,
PayerID = req.query.PayerID,
gift = req.session.gift ? JSON.parse(req.session.gift) : undefined;
delete req.session.gift;
async.waterfall([
function(cb){
paypal.payment.execute(paymentId, {payer_id: PayerID}, cb);
},
function(payment, cb){
async.parallel([
function(cb2){ User.findById(req.session.userId, cb2); },
function(cb2){ User.findById(gift ? gift.uuid : undefined, cb2); }
], cb);
},
function(results, cb){
if (_.isEmpty(results[0])) return cb("User not found when completing paypal transaction");
var data = {user:results[0], customerId:PayerID, paymentMethod:'Paypal', gift:gift}
var method = 'buyGems';
if (gift) {
gift.member = results[1];
if (gift.type=='subscription') method = 'createSubscription';
data.paymentMethod = 'Gift';
}
payments[method](data, cb);
}
],function(err){
if (err) return parseErr(res, err);
res.redirect('/');
})
}
exports.cancelSubscription = function(req, res, next){
var user = res.locals.user;
if (!user.purchased.plan.customerId)
return res.json(401, {err: "User does not have a plan subscription"});
async.auto({
get_cus: function(cb){
paypal.billingAgreement.get(user.purchased.plan.customerId, cb);
},
verify_cus: ['get_cus', function(cb, results){
var hasntBilledYet = results.get_cus.agreement_details.cycles_completed == "0";
if (hasntBilledYet)
return cb("The plan hasn't activated yet (due to a PayPal bug). It will begin "+results.get_cus.agreement_details.next_billing_date+", after which you can cancel to retain your full benefits");
cb();
}],
del_cus: ['verify_cus', function(cb, results){
paypal.billingAgreement.cancel(user.purchased.plan.customerId, {note: "Canceling the subscription"}, cb);
}],
cancel_sub: ['get_cus', 'verify_cus', function(cb, results){
var data = {user: user, paymentMethod: 'Paypal', nextBill: results.get_cus.agreement_details.next_billing_date};
payments.cancelSubscription(data, cb)
}]
}, function(err){
if (err) return parseErr(res, err);
res.redirect('/');
user = null;
});
}
/**
* General IPN handler. We catch cancelled HabitRPG subscriptions for users who manually cancel their
* recurring paypal payments in their paypal dashboard. Remove this when we can move to webhooks or some other solution
*/
exports.ipn = function(req, res, next) {
console.log('IPN Called');
res.send(200); // Must respond to PayPal IPN request with an empty 200 first
ipn.verify(req.body, function(err, msg) {
if (err) return logger.error(msg);
switch (req.body.txn_type) {
// TODO what's the diff b/w the two data.txn_types below? The docs recommend subscr_cancel, but I'm getting the other one instead...
case 'recurring_payment_profile_cancel':
case 'subscr_cancel':
User.findOne({'purchased.plan.customerId':req.body.recurring_payment_id},function(err, user){
if (err) return logger.error(err);
if (_.isEmpty(user)) return; // looks like the cancellation was already handled properly above (see api.paypalSubscribeCancel)
payments.cancelSubscription({user:user, paymentMethod: 'Paypal'});
});
break;
}
});
};
@@ -0,0 +1,93 @@
// This file is used for creating paypal billing plans. PayPal doesn't have a web interface for setting up recurring
// payment plan definitions, instead you have to create it via their REST SDK and keep it updated the same way. So this
// file will be used once for initing your billing plan (then you get the resultant plan.id to store in config.json),
// and once for any time you need to edit the plan thereafter
require('coffee-script');
var path = require('path');
var nconf = require('nconf');
_ = require('lodash');
nconf.argv().env().file('user', path.join(path.resolve(__dirname, '../../../config.json')));
var paypal = require('paypal-rest-sdk');
var blocks = require('../../../common').content.subscriptionBlocks;
var live = nconf.get('PAYPAL:mode')=='live';
var OP = 'create'; // list create update remove
paypal.configure({
'mode': nconf.get("PAYPAL:mode"), //sandbox or live
'client_id': nconf.get("PAYPAL:client_id"),
'client_secret': nconf.get("PAYPAL:client_secret")
});
// https://developer.paypal.com/docs/api/#billing-plans-and-agreements
var billingPlanTitle ="HabitRPG Subscription";
var billingPlanAttributes = {
"name": billingPlanTitle,
"description": billingPlanTitle,
"type": "INFINITE",
"merchant_preferences": {
"auto_bill_amount": "yes",
"cancel_url": live ? 'https://habitrpg.com' : 'http://localhost:3000',
"return_url": (live ? 'https://habitrpg.com' : 'http://localhost:3000') + '/paypal/subscribe/success'
},
payment_definitions: [{
"type": "REGULAR",
"frequency": "MONTH",
"cycles": "0"
}]
};
_.each(blocks, function(block){
block.definition = _.cloneDeep(billingPlanAttributes);
_.merge(block.definition.payment_definitions[0], {
"name": billingPlanTitle + ' ($'+block.price+' every '+block.months+' months, recurring)',
"frequency_interval": ""+block.months,
"amount": {
"currency": "USD",
"value": ""+block.price
}
});
})
switch(OP) {
case "list":
paypal.billingPlan.list({status: 'ACTIVE'}, function(err, plans){
console.log({err:err, plans:plans});
});
break;
case "get":
paypal.billingPlan.get(nconf.get("PAYPAL:billing_plans:12"), function (err, plan) {
console.log({err:err, plan:plan});
})
break;
case "update":
var update = {
"op": "replace",
"path": "/merchant_preferences",
"value": {
"cancel_url": "https://habitrpg.com"
}
};
paypal.billingPlan.update(nconf.get("PAYPAL:billing_plans:12"), update, function (err, res) {
console.log({err:err, plan:res});
});
break;
case "create":
paypal.billingPlan.create(blocks["google_6mo"].definition, function(err,plan){
if (err) return console.log(err);
if (plan.state == "ACTIVE")
return console.log({err:err, plan:plan});
var billingPlanUpdateAttributes = [{
"op": "replace",
"path": "/",
"value": {
"state": "ACTIVE"
}
}];
// Activate the plan by changing status to Active
paypal.billingPlan.update(plan.id, billingPlanUpdateAttributes, function(err, response){
console.log({err:err, response:response, id:plan.id});
});
});
break;
case "remove": break;
}
+123
View File
@@ -0,0 +1,123 @@
var nconf = require('nconf');
var stripe = require("stripe")(nconf.get('STRIPE_API_KEY'));
var async = require('async');
var payments = require('./index');
var User = require('mongoose').model('User');
var shared = require('../../../common');
var mongoose = require('mongoose');
var cc = require('coupon-code');
/*
Setup Stripe response when posting payment
*/
exports.checkout = function(req, res, next) {
var token = req.body.id;
var user = res.locals.user;
var gift = req.query.gift ? JSON.parse(req.query.gift) : undefined;
var sub = req.query.sub ? shared.content.subscriptionBlocks[req.query.sub] : false;
async.waterfall([
function(cb){
if (sub) {
async.waterfall([
function(cb2){
if (!sub.discount) return cb2(null, null);
if (!req.query.coupon) return cb2('Please provide a coupon code for this plan.');
mongoose.model('Coupon').findOne({_id:cc.validate(req.query.coupon), event:sub.key}, cb2);
},
function(coupon, cb2){
if (sub.discount && !coupon) return cb2('Invalid coupon code.');
var customer = {
email: req.body.email,
metadata: {uuid: user._id},
card: token,
plan: sub.key
};
stripe.customers.create(customer, cb2);
}
], cb);
} else {
stripe.charges.create({
amount: !gift ? "500" //"500" = $5
: gift.type=='subscription' ? ""+shared.content.subscriptionBlocks[gift.subscription.key].price*100
: ""+gift.gems.amount/4*100,
currency: "usd",
card: token
}, cb);
}
},
function(response, cb) {
if (sub) return payments.createSubscription({user:user, customerId:response.id, paymentMethod:'Stripe', sub:sub}, cb);
async.waterfall([
function(cb2){ User.findById(gift ? gift.uuid : undefined, cb2) },
function(member, cb2){
var data = {user:user, customerId:response.id, paymentMethod:'Stripe', gift:gift};
var method = 'buyGems';
if (gift) {
gift.member = member;
if (gift.type=='subscription') method = 'createSubscription';
data.paymentMethod = 'Gift';
}
payments[method](data, cb2);
}
], cb);
}
], function(err){
if (err) return res.send(500, err.toString()); // don't json this, let toString() handle errors
res.send(200);
user = token = null;
});
};
exports.subscribeCancel = function(req, res, next) {
var user = res.locals.user;
if (!user.purchased.plan.customerId)
return res.json(401, {err: "User does not have a plan subscription"});
async.auto({
get_cus: function(cb){
stripe.customers.retrieve(user.purchased.plan.customerId, cb);
},
del_cus: ['get_cus', function(cb, results){
stripe.customers.del(user.purchased.plan.customerId, cb);
}],
cancel_sub: ['get_cus', function(cb, results) {
var data = {
user: user,
nextBill: results.get_cus.subscription.current_period_end*1000, // timestamp is in seconds
paymentMethod: 'Stripe'
};
payments.cancelSubscription(data, cb);
}]
}, function(err, results){
if (err) return res.send(500, err.toString()); // don't json this, let toString() handle errors
res.redirect('/');
user = null;
});
};
exports.subscribeEdit = function(req, res, next) {
var token = req.body.id;
var user = res.locals.user;
var user_id = user.purchased.plan.customerId;
var sub_id;
async.waterfall([
function(cb){
stripe.customers.listSubscriptions(user_id, cb);
},
function(response, cb) {
sub_id = response.data[0].id;
console.warn(sub_id);
console.warn([user_id, sub_id, { card: token }]);
stripe.customers.updateSubscription(user_id, sub_id, { card: token }, cb);
},
function(response, cb) {
user.save(cb);
}
], function(err, saved){
if (err) return res.send(500, err.toString()); // don't json this, let toString() handle errors
res.send(200);
token = user = user_id = sub_id;
});
};