简体   繁体   中英

Braintree update Subscription from yearly to monthly PHP

I have a Vue App that makes an ajax call to this page to "Update" a subscription I say update but what I am actually doing is canceling the current subscription and adding another. I would using the built in update function however according to Braintree's documentation it currently does not support prorating a subscription that has a different billing cycle. For example you cant use braintree::update() if you want to update a subscription that reoccurs every year to a subscription that reoccurs every month or vise versa. The code currently works but I want to prorate. How can i fake this so that I can prorate these types of subscriptions. Here's the code I currently have can someone send me a code snippet?

<?php session_start(); ob_start();
  $id=$_SESSION['braintreeid'];
  $receiver='creativegroup@codernoob.com';
  $username=$_SESSION['username'];
  $email = $_SESSION['email'];
   require 'PHPMailer/PHPMailerAutoload.php';
  date_default_timezone_set('America/Denver');
  $request_body = file_get_contents('php://input');
  $json = json_decode($request_body);
  $oldsubscriptionid=$json->oldsubscriptionid;
  require_once 'lib/Braintree.php';

  $gateway = new Braintree_Gateway([
    'environment' => 'sandbox',
    'merchantId' => '********',
    'publicKey' => '*******',
    'privateKey' => '********'
  ]);
$cancelresult=$gateway->subscription()->cancel($oldsubscriptionid);
  $result = $gateway->subscription()->create([
    'paymentMethodToken' => $json->token,
    'planId' => $json->plan
  ]);
if($result){$data['error']=0;
           $data['problemsending']=0;
           $data['emailsent']=0;
           $data['result']=$result;
           } else {$data['error']=1;
                   $data['result']=$result;

                    $mail = new PHPMailer;



                    //$mail->SMTPDebug = 3;                               // Enable verbose debug output



                    $mail->isSMTP();                                      // Set mailer to use SMTP

                    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers

                    $mail->SMTPAuth = true;                               // Enable SMTP authentication

                    $mail->Username = 'donotreply@codernoob.com';                 // SMTP username

                    $mail->Password = '*********';                           // SMTP password

                    $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted

                    $mail->Port = 465;                                    // TCP port to connect to



                    $mail->setFrom('donotreply@codernoob.com');

                    $mail->addAddress($email);     // Add a recipient

                    $mail->addAddress($receiver);               // Name is optional


                    $mail->addBCC(''); //WARNING: SMTP servers will cap 'potential' spammers to no more than 100 recipients per blast, and no more than 500 per day. If you need more than this get a professional SMTP server.



                    $mail->addAttachment('');         // Add attachments

                    $mail->addAttachment('');    // Optional name

                    $mail->isHTML(true);       // Set email format to HTML



                    $mail->Subject = 'codernoob: ERROR Updating Subscription!';



$body = "
                        <html>
                          <head>
                            <title>Error updating Subscription!</title>
                          </head>
                          <body>
                            <h1>There was an error updating subscription</h1>
                            <p>Username: ".$username."</p>
                            <p>Email: ".$email." </p>";
                            $body .= '<br><br>Had an error updating a subscription. If this is the first time you have seen this ignore it as a packet probably just dropped. However, if problem persists please have a web developer address the problem.';

                          $body .= "</body>
                        </html>
                        ";

                    $mail->Body    = $body;


                    if($mail->send()) {$data['emailsent']=1;}
                    else {$data['problemsending']=1;}
                  }
  $customer = $gateway->customer()->find($id);
  $plans = $gateway->plan()->all();

  $plansArray = array();

  foreach ($plans as $plan) {
    array_push($plansArray, $plan);
  }

  $subscriptions = array();

  foreach ($customer->creditCards as $card) {
    foreach ($card->subscriptions as $subscription) {
      array_push($subscriptions, $subscription);
    }
  }
$data['paymentMethods']=$customer->paymentMethods;
$data['plans']=$plansArray;
$data['subscriptions']=$subscriptions;
  echo json_encode($data);
?>

Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support .

Calculate a pro-rated amount to use as a one-time discount on the new monthly subscription.

  • In the Control Panel, create a discount for the monthly plan. Set the default amount to $0 and the number of billing cycles to 1.
  • Calculate the amount you want to deduct from the original subscription price as your proration amount. Braintree documents their proration formula here if you want to use that as an example.
  • Create the subscription , using the calculated proration amount as the amount of the discount:

    $result = $gateway->subscription()->create([ 'paymentMethodToken' => 'the_token', 'planId' => 'silver_plan', 'discounts' => [ 'update' => [ 'existingId' => 'discountId', 'amount' => 'proratedAmountToDiscount', ]
    ] ]);

Notes-

  1. When creating a subscription , it will automatically inherit any add-ons and/or discounts associated with the plan. You can override those details at the time you create or update the subscription. If you don't need to pro-rate, don't override the discount because the default discount will be $0.

  2. If the amount of the discount is larger than the amount of the monthly charge, the subscription will be created with a negative balance to be applied to the next billing cycle. Example : A $1 monthly subscription created with a discount of $1.50 will be created with $0 charged the first month and a balance of -$0.50 to be applied the next month. The next month's charge will be $0.50 ($1 - $0.50).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM