コード例 #1
0
func handleInvoiceStateChange(invoice *stripe.Invoice) error {
	cus, err := customer.Get(invoice.Customer.ID, nil)
	if err != nil {
		return err
	}

	if err := syncGroupWithCustomerID(invoice.Customer.ID); err != nil {
		return err
	}

	group, err := modelhelper.GetGroup(cus.Meta["groupName"])
	// we might get events from other environments where we might not have the
	// group in this env.
	if err == mgo.ErrNotFound {
		return nil
	}

	if err != nil {
		return err
	}

	status := group.Payment.Subscription.Status

	// if sub is in cancelled state within 2 months send an event
	if stripe.SubStatus(status) == SubStatusCanceled {
		// if group has been created in last 2 months (1 month trial + 1 month free)
		totalTrialTime := time.Now().UTC().Add(-time.Hour * 24 * 60)
		if group.Id.Time().After(totalTrialTime) {
			eventName := "trial ended without payment"
			sendEventForCustomer(invoice.Customer.ID, eventName, nil)
		}
	}

	// send instance notification to group
	go realtimehelper.NotifyGroup(
		group.Slug,
		"payment_status_changed",
		map[string]string{
			"oldStatus": string(group.Payment.Subscription.Status),
			"newStatus": string(status),
		},
	)

	eventName := fmt.Sprintf("subscription status %s", status)
	return sendEventForCustomer(invoice.Customer.ID, eventName, nil)
}
コード例 #2
0
func syncGroupWithCustomerID(cusID string) error {
	cus, err := customer.Get(cusID, nil)
	if err != nil {
		return err
	}

	group, err := modelhelper.GetGroup(cus.Meta["groupName"])
	if err == mgo.ErrNotFound {
		return nil
	}

	if err != nil {
		return err
	}

	// here sub count might be 0, but should not be gt 1
	if cus.Subs.Count > 1 {
		return errors.New("customer should only have one subscription")
	}

	subID := ""
	subStatus := SubStatusCanceled

	// if we dont have any sub, set it as canceled
	if cus.Subs.Count == 1 {
		subID = cus.Subs.Values[0].ID
		subStatus = cus.Subs.Values[0].Status
	}

	// if subID and subStatus are same, update not needed
	if group.Payment.Subscription.ID == subID &&
		stripe.SubStatus(group.Payment.Subscription.Status) == subStatus {
		return nil
	}

	return modelhelper.UpdateGroupPartial(
		modelhelper.Selector{"_id": group.Id},
		modelhelper.Selector{
			"$set": modelhelper.Selector{
				"payment.subscription.id":     subID,
				"payment.subscription.status": string(subStatus),
			},
		},
	)
}