Files
discourse-subscriptions/assets/javascripts/discourse/controllers/s-show.js.es6
T

86 lines
2.3 KiB
JavaScript
Raw Normal View History

import Controller from "@ember/controller";
2019-12-12 12:59:26 +11:00
import Customer from "discourse/plugins/discourse-subscriptions/discourse/models/customer";
import Subscription from "discourse/plugins/discourse-subscriptions/discourse/models/subscription";
2020-05-22 11:20:05 -05:00
import I18n from "I18n";
2019-10-10 13:52:55 +11:00
export default Controller.extend({
selectedPlan: null,
init() {
this._super(...arguments);
this.set(
"stripe",
2019-12-04 11:53:05 +11:00
Stripe(Discourse.SiteSettings.discourse_subscriptions_public_key)
);
const elements = this.get("stripe").elements();
2019-11-29 15:08:51 +11:00
2019-12-10 10:15:30 +11:00
this.set("cardElement", elements.create("card", { hidePostalCode: true }));
},
alert(path) {
bootbox.alert(I18n.t(`discourse_subscriptions.${path}`));
},
2020-01-14 18:46:48 +11:00
createSubscription(plan) {
return this.stripe.createToken(this.get("cardElement")).then(result => {
if (result.error) {
return result;
} else {
const customer = Customer.create({ source: result.token.id });
return customer.save().then(c => {
const subscription = Subscription.create({
customer: c.id,
plan: plan.get("id")
});
return subscription.save();
});
}
});
},
actions: {
stripePaymentHandler() {
2019-11-14 13:43:18 +11:00
this.set("loading", true);
2019-12-10 10:55:24 +11:00
const plan = this.get("model.plans")
.filterBy("id", this.selectedPlan)
2019-12-10 10:55:24 +11:00
.get("firstObject");
if (!plan) {
this.alert("plans.validate.payment_options.required");
2019-12-10 10:55:24 +11:00
this.set("loading", false);
return;
}
2019-11-14 13:43:18 +11:00
let transaction = this.createSubscription(plan);
transaction
.then(result => {
if (result.error) {
bootbox.alert(result.error.message || result.error);
} else {
2020-01-14 20:15:54 +11:00
if (result.status === "incomplete") {
this.alert("plans.incomplete");
2020-01-14 20:15:54 +11:00
} else {
this.alert("plans.success");
2020-01-14 18:46:48 +11:00
}
2019-12-13 13:44:25 +11:00
this.transitionToRoute(
plan.type === "recurring"
? "user.billing.subscriptions"
: "user.billing.payments",
Discourse.User.current().username.toLowerCase()
);
}
})
.catch(result => {
bootbox.alert(result.errorThrown);
})
.finally(() => {
2019-11-14 13:43:18 +11:00
this.set("loading", false);
});
2019-10-10 13:52:55 +11:00
}
}
});