/** * @return mixed */ public function getSubscriptions() { return $this->hasMany(SubscriptionModel::className(), ['userId' => 'id'])->orderBy(['createdAt' => SORT_DESC]); }
/** * Get the user for the given subscription ID. * * @param string $subscriptionId * * @return null|SubscriptionModel */ protected function getSubscriptionById($subscriptionId) { return SubscriptionModel::findOne(['braintreeId' => $subscriptionId]); }
/** * Create a new Braintree subscription. * * @param string|null $token * @param array $customerOptions * @param array $subscriptionOptions * * @return SubscriptionModel * * @throws Exception */ public function create($token = null, array $customerOptions = [], array $subscriptionOptions = []) { $payload = $this->getSubscriptionPayload($this->getBraintreeCustomer($token, $customerOptions), $subscriptionOptions); if ($this->coupon) { $payload = $this->addCouponToPayload($payload); } $response = BraintreeSubscription::create($payload); if (!$response->success) { throw new Exception('Braintree failed to create subscription: ' . $response->message); } if ($this->skipTrial) { $trialEndsAt = null; } else { $trialEndsAt = $this->trialDays ? Carbon::now()->addDays($this->trialDays) : null; } $subscriptionModel = Yii::createObject(['class' => SubscriptionModel::className(), 'userId' => $this->user->id, 'name' => $this->name, 'braintreeId' => $response->subscription->id, 'braintreePlan' => $this->plan, 'trialEndAt' => $trialEndsAt, 'endAt' => null]); if ($subscriptionModel->save()) { return $subscriptionModel; } else { throw new Exception('Subscription was not saved.'); } }