4

I'm a little confused on how to process a subscription + fees payment with Stripe,

Here's what I got:

HTML:

<form id="req" action="/thank-you" method="post">

<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_RrE21sY9Xbtwq9ZvbKPpp0LJ"
data-name="Wizard.Build Hosting Package"
data-description=""
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-currency="usd">
</script>
...

Thank you page:

require_once('lib-stripe/init.php');

// create api key
\Stripe\Stripe::setApiKey("sk_TESTING");

// create customer
$customerO =\Stripe\Customer::create(array(
  "email" => $_POST["e"]
));
$customer = $customerO->jsonSerialize();

//var_dump($customer);

//create subscription (Package Bronze, Silver or Gold)
$subscriptionO = \Stripe\Subscription::create(array(
  "customer" => $customer["id"],
  "items" => array(
    array(
        "plan" => $_POST["pack"],
    ),
  )
));
$subscription = $subscriptionO->jsonSerialize();

//var_dump($subscription);

//create invoice (3rdparty cost)
$invoiceO = \Stripe\Invoice::create(array(
    "customer" => $customer["id"],
    "amount" =>$p3price,
    "currency" => "usd",
    "description" => "3rdp Cost",
    "subscription" => $subscription["id"]
));
$invoice = $invoiceO->jsonSerialize();

//var_dump($invoice);

I'm clearly missing how the whole process work...

I will populate the email field, but how can I request a setup fees + subscription re-occurring every month in that popup form?

Ideally the workflow is as follows:

My Website page with form: User fills name, email, item name [need this meta data], item price, package name[need this meta data], package price

hits submit button, Stripe popup form appears prepopulated with email, user agrees to package monthly payment + item price, user enters card info, user submits stripe form,

user is now charged with 1st month of package + item price, payments will occur every month for package automatically.

return to a url with all metadata, prices, package, etc, with secret code or some kind of security form field, then I process order automatically from the return url data,

Please help, thanks community!

Luc Laverdure
  • 1,398
  • 2
  • 19
  • 36
  • Do you want their default form or your own custom form? – Lakindu Gunasekara Feb 03 '18 at 07:12
  • Their default form – Luc Laverdure Feb 03 '18 at 07:16
  • Have you reviewed this [documentation](https://stripe.com/docs/quickstart) – Barmar Feb 03 '18 at 07:21
  • What is the issue - error message, wrong results, nothing happens? – June7 Feb 03 '18 at 07:43
  • I need the payment popup with their UI, but I need backend processing of creating user, subscription and invoice, I'm just uncertain how everything ties together... – Luc Laverdure Feb 03 '18 at 07:55
  • Right now popup displays, but backend processing doesnt work – Luc Laverdure Feb 03 '18 at 07:56
  • Could you check if you pass in the card token from their popup? You seem to create the customer, add subscription, etc. but never process the `source` I.e. card token in your PHP code. – Máté Feb 03 '18 at 08:45
  • I don't want to manage cards, can't stripe manage that? – Luc Laverdure Feb 03 '18 at 08:47
  • Stripe manages the cards for you through their tokens API, when you add a card, you get back a token (which you can use as `source` for the transaction / subscription. But without that source - a connection between your customer and the card, you won't be able to charge your customers. – Máté Feb 06 '18 at 15:23
  • I don't want the customer to enter more than 1 form, is it possible to add subscription on the popup? I found the token id, but I want the user to pay subscription + setup fee on a single form, how do I go about this? – Luc Laverdure Feb 08 '18 at 03:08

3 Answers3

4

I think i can guide you with the process, there are very simple steps you have to follow and check that everything goes perfectly.

  1. Create a plan using Stripe dashboard or Stripe API (PHP code example below)

    \Stripe\Stripe::setApiKey("<YOUR SECRET KEY>");
    
    $plan = \Stripe\Plan::create([
      'product' => {'name' => 'Plan name'},
      'nickname' => 'Plan code',
      'interval' => 'month',
      'currency' => 'usd',
      'amount' => 10,
    ]);
    
  2. Create a customer in Stripe using the JS/PHP etc and save the id for reference.(PHP code example below)

    \Stripe\Stripe::setApiKey("<YOUR SECRET KEY>");
    
    $customer = \Stripe\Customer::create([
      'email' => 'customer@example.com',
    ]);
    

    The response of this call will give a json for customer created at stripe

    {
      "id": "<UNIQUE ID>",
      ...
    }
    

    You will need to persist the id in a variable or database

  3. Subscribe customer to for plan.(PHP example code below)

    \Stripe\Stripe::setApiKey("<YOUR SECRET KEY>");
    
    $subscription = \Stripe\Subscription::create([
      'customer' => '<UNIQUE ID>',
      'items' => [['plan' => '<PLAN ID>']],
    ]);
    

You can find more details on the Official Stripe documentation

Nahid Ali
  • 636
  • 3
  • 11
1

generate plan either code or using admin panel and put the plan id to subscription method.. make sure if you have generate plan id using admin panel then it will run only in live key and generated plan id using code it run both key..

$plan = \Stripe\Plan::create([
  'product' => {'name' => 'Basic Product'},
  'nickname' => 'Basic Monthly',
  'interval' => 'month',
  'currency' => 'usd',
  'amount' => 0,
]); 
1

In a gist, you should implement the basic Stripe Charge API flow (create customer, create a charge etc), and call for a subscription plan id within the payment's returned promise, attach it to the user (with a successful charge).

You do not have to create this plan programmatically (unless you need to dynamically create unique plans for each customer), you can do that via the slack dashboard, user plans section. You only need to make a call to "subscribe" the customer to your given plan.

Create a user first, upon successfully creating this user, "charge" call passes in the unique id for this customer, later on when the charge is successfuly (in your successful callback as opposed to error one) call the subscribe call with your earlier created plan id.

When you use the test mode and pay with this setup, look into payment details (make sure dashboard is switched to test mode) and you will see this charge and user has the subscription plan attached to it, what will happen is stripe will attempt the charge again within the end of this subscription period (you may set this all up via dashboard, weekly/monthly plan etc), it's best to test with stripe's own tools (you don't have to wait this period to test, look it up in the relevant api docs section)

Let me know if you need help with the code too, but it's pretty straightforward to follow on the api docs once you get your head around this easy flow I explained above.

Dashboard url: https://dashboard.stripe.com/ (switch "view test data" on to see your test payment details)

API calls ref: https://stripe.com/docs/api#create_customer https://stripe.com/docs/api#create_charge https://stripe.com/docs/api#create_subscription (you don't have to do this via api, do it from the dashboard, much easier)

Take a look at the code segment from my test code, I use NodeJS, but you may use this with your php project too in the frontend, just lookup setting up stripe on frontend in getting started docs

    stripe.customers.create({
      description: "NR user twitter: " + req.body.twusername + ", job title being paid for: " + req.body.jobRawTitle,
      source: req.body.token,
      email: req.body.email
    }, function(err, customer) {
      if (err) {
          // bad things
          console.log("DEBUG payment charge error: " + JSON.stringify(err));
      } else {
        //update user with given Email
        // Charge the user's card:
        return stripe.charges.create({
          amount: 29900, //the last 2 0s are cents
          currency: "usd",
          customer: customer.id,
          description: "Jobs 1 month paid for nextreality job titled:" + req.body.jobRawTitle
        }, function(err, charge) {
          if (err) {
              // bad things
              console.log("DEBUG payment charge error: " + JSON.stringify(err) );
               console.log("charge: "+ charge);
          } else {
              // successful charge
              return stripe.subscriptions.create({
                customer: customer.id,
                items: [
                  {
                    plan: "jobs_monthly",
                  },
                ],
              }, function(err, subscription) {
                // asynchronously called
                console.log("DEBUG payment subscription error: " + err + ' subs:' + JSON.stringify(subscription) );
                return Response(req, res, {});

              });
          }
        });
      }
    });
sed
  • 5,431
  • 2
  • 24
  • 23