• PHP Help
  • creating stripe connected subscriber account

I'm trying to first create a stripe account, then create the subscription and customer via the created account ID, and then ultimately link the two to create a 'connected' subscriber account on stripe and for it to appear under my connected accounts in my dashboard. So far the script is failing.


// Include Stripe PHP library
require_once 'stripe-php/init.php';

// Set API key
\Stripe\Stripe::setApiKey($STRIPE_API_KEY);

	// Create Account
try {
	$stripe = \Stripe\Account::create(array(
		"email" => $email,
		"country"  => "US",
        "type"  => "custom",
        'capabilities' => [
        'card_payments' => ['requested' => true],
        'transfers' => ['requested' => true],
    ],
	));

// Add customer to stripe
try {
	$customer = \Stripe\Customer::create(array(
		"email" => $email,
		"source"  => $token
    ), array("stripe_account" => $stripe->id));

}catch(Exception $e) {
    $api_error = $e->getMessage();
}

if(empty($api_error) && $customer){

	// Convert price to cents
	$priceCents = round($planPrice*100);

	// Create a plan
	try {
		$plan = \Stripe\Plan::create(array(
			"product" => [
				"name" => $planName
			],
			"amount" => $priceCents,
			"currency" => $currency,
			"interval" => $planInterval,
			"interval_count" => 1
    ), array("stripe_account" => $stripe->id));

	}catch(Exception $e) {
		$api_error = $e->getMessage();
	}


	if(empty($api_error) && $plan){
		// Creates a new subscription
		try {


        $subscription = \Stripe\Subscription::create(array(
        "customer" => $customer->id,
        "items" => ["plan" => $plan->id]
), array("stripe_account" => $stripe->id));

		}catch(Exception $e) {
			$api_error = $e->getMessage();
		}

        echo $api_error;

crawdidly So far the script is failing.

Any errors (including checking the PHP error log)?

    I edited the code on a few items, but overall the page breaks, 500 error page. I can't see it. The query portion is fine as I tried taking that out, but still had error.

    
    <?php session_start();
    include 'config.php';
    
    // Get user ID from current SESSION
    $userID = $_SESSION["memberid"];
    $payment_id = $statusMsg = $api_error = '';
    $ordStatus = 'error';
    
    // Check whether stripe token is not empty
    if(!empty($_POST['subscr_plan']) && (!empty($_POST['stripeToken']))){
    
    // Retrieve stripe token and user info from the submitted form data
    $token  = $_POST['stripeToken'];
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    // Plan info
    $planID = $_POST['subscr_plan'];
    $planInfo = $plans['$planID'];
    $planName = $planInfo['name'];
    $planPrice = $planInfo['price'];
    $planInterval = $planInfo['interval'];
    
    // Include Stripe PHP library
    require_once 'stripe-php/init.php';
    
    // Set API key
    \Stripe\Stripe::setApiKey($STRIPE_API_KEY);
    
    	// Create Account
    try {
    	$stripe = \Stripe\Account::create(array(
    		"email" => $email,
    		"country"  => "US",
            "type"  => "custom",
            'capabilities' => [
            'card_payments' => ['requested' => true],
            'transfers' => ['requested' => true],
        ],
    	), array("stripe_account" => $stripe->id));
    
    // Add customer to stripe
    try {
    	$customer = \Stripe\Customer::create(array(
    		"email" => $email,
    		"source"  => $token
        ), array("stripe_account" => $stripe->id));
    
    }catch(Exception $e) {
        $api_error = $e->getMessage();
    }
    
    if(empty($api_error) && ($customer)){
    
    	// Convert price to cents
    	$priceCents = round($planPrice*100);
    
    	// Create a plan
    	try {
    		$plan = \Stripe\Plan::create(array(
    			"product" => [
    				"name" => $planName
    			],
    			"amount" => $priceCents,
    			"currency" => $currency,
    			"interval" => $planInterval,
    			"interval_count" => 1
        ), array("stripe_account" => $stripe->id));
    
    	}catch(Exception $e) {
    		$api_error = $e->getMessage();
    	}
    
    	if(empty($api_error) && ($plan)){
    		// Creates a new subscription
    		try {
    
    
            $subscription = \Stripe\Subscription::create(array(
            "customer" => $customer->id,
            "items" => ["plan" => $plan->id]
    ), array("stripe_account" => $stripe->id));
    
    		}catch(Exception $e) {
    			$api_error = $e->getMessage();
    		}
    
        	if(empty($api_error) && ($subscription)){
    			// Retrieve subscription data
    			$subsData = $subscription->jsonSerialize();
    
    			// Check whether the subscription activation is successful
    			if($subsData['status'] == 'active'){
    				// Subscription info
    				$subscrID = $subsData['id'];
    				$custID = $subsData['customer'];
    				$planID = $subsData['plan']['id'];
    				$planAmount = ($subsData['plan']['amount']/100);
    				$planCurrency = $subsData['plan']['currency'];
    				$planinterval = $subsData['plan']['interval'];
    				$planIntervalCount = $subsData['plan']['interval_count'];
    				$created = date("Y-m-d H:i:s", $subsData['created']);
    				$current_period_start = date("Y-m-d H:i:s", $subsData['current_period_start']);
    				$current_period_end = date("Y-m-d H:i:s", $subsData['current_period_end']);
    				$status = $subsData['status'];
    
    				// Include database connection file
    				include '../includes/dbconnect.php';
    
    				// Insert transaction data into the database
    				$sql = "INSERT INTO user_subscriptions(user_id,stripe_subscription_id,stripe_customer_id,stripe_plan_id,plan_amount,plan_amount_currency,plan_interval,plan_interval_count,payer_email,created,plan_period_start,plan_period_end,status) VALUES('".$userID."','".$subscrID."','".$custID."','".$planID."','".$planAmount."','".$planCurrency."','".$planinterval."','".$planIntervalCount."','".$email."','".$created."','".$current_period_start."','".$current_period_end."','".$status."')";
    				$insert = $db->query($sql);
    
    				// Update subscription id in the users table
    				if($insert && !empty($userID)){
    					$subscription_id = $db->insert_id;
    					$update = $db->query("UPDATE steam_contributors SET subscription_id = {$subscription_id} WHERE memberid = {$userID}");
    				}
    
    				$ordStatus = 'success';
    				$statusMsg = 'Your Subscription Payment has been Successful!';
    			}else{
    				$statusMsg = "Subscription activation failed!";
    			}
    		}else{
    			$statusMsg = "Subscription creation failed! ".$api_error;
    		}
    	}else{
    		$statusMsg = "Plan creation failed! ".$api_error;
    	}
    }else{
        $statusMsg = "Invalid card details! $api_error";
    }
    }else{
    	$statusMsg = "Error on form submission, please try again.";
    }
    ?>
    
     

      Stick this at the top before anything else gets processed:

      <?php
      ini_set('display_errors', true); // set to false in production
      error_reporting(E_ALL);
      
      // rest of script . . .
      

      Then hopefully you'll at least see whatever errors/exceptions/warnings are happening.

        Well, my editor right away highlighted some syntax issues. Here's a stab at fixing them. However, all that nesting of if/else blocks is a strong "code smell" that you need to modularize things by at least putting a lot of the atomic bits of functionality into (well named) functions, so that you don't have that long, intricate, multiple-layered tangle of code. 😉 (started by just using one try/catch block to rule them all.)

        <?php
        ini_set('display_errors', true); // set to false in production
        error_reporting(E_ALL);
        session_start();
        include 'config.php';
        // Get user ID from current SESSION
        $userID = $_SESSION["memberid"];
        $payment_id = $statusMsg = $api_error = '';
        $ordStatus = 'error';
        try {
            // Check whether stripe token is not empty
            if(!empty($_POST['subscr_plan']) && (!empty($_POST['stripeToken']))){
                // Retrieve stripe token and user info from the submitted form data
                $token  = $_POST['stripeToken'];
                $name = $_POST['name'];
                $email = $_POST['email'];
                // Plan info
                $planID = $_POST['subscr_plan'];
                $planInfo = $plans['$planID'];
                $planName = $planInfo['name'];
                $planPrice = $planInfo['price'];
                $planInterval = $planInfo['interval'];
                // Include Stripe PHP library
                require_once 'stripe-php/init.php';
                // Set API key
                \Stripe\Stripe::setApiKey($STRIPE_API_KEY);
                // Create Account
                $stripe = \Stripe\Account::create(array(
                    "email" => $email,
                    "country"  => "US",
                    "type"  => "custom",
                    'capabilities' => [
                    'card_payments' => ['requested' => true],
                    'transfers' => ['requested' => true],
                ],
                ), array("stripe_account" => $stripe->id));
            // Add customer to stripe
                $customer = \Stripe\Customer::create(array(
                    "email" => $email,
                    "source"  => $token
                ), array("stripe_account" => $stripe->id));
                if(empty($api_error) && ($customer)){
                    // Convert price to cents
                    $priceCents = round($planPrice*100);
                    // Create a plan
                        $plan = \Stripe\Plan::create(array(
                            "product" => [
                                "name" => $planName
                            ],
                            "amount" => $priceCents,
                            "currency" => $currency,
                            "interval" => $planInterval,
                            "interval_count" => 1
                    ), array("stripe_account" => $stripe->id));
                    if(empty($api_error) && ($plan)){
                        // Creates a new subscription
                        $subscription = \Stripe\Subscription::create(array(
                        "customer" => $customer->id,
                        "items" => ["plan" => $plan->id]
                ), array("stripe_account" => $stripe->id));
                        if(empty($api_error) && ($subscription)){
                            // Retrieve subscription data
                            $subsData = $subscription->jsonSerialize();
                            // Check whether the subscription activation is successful
                            if($subsData['status'] == 'active'){
                                // Subscription info
                                $subscrID = $subsData['id'];
                                $custID = $subsData['customer'];
                                $planID = $subsData['plan']['id'];
                                $planAmount = ($subsData['plan']['amount']/100);
                                $planCurrency = $subsData['plan']['currency'];
                                $planinterval = $subsData['plan']['interval'];
                                $planIntervalCount = $subsData['plan']['interval_count'];
                                $created = date("Y-m-d H:i:s", $subsData['created']);
                                $current_period_start = date("Y-m-d H:i:s", $subsData['current_period_start']);
                                $current_period_end = date("Y-m-d H:i:s", $subsData['current_period_end']);
                                $status = $subsData['status'];
                                // Include database connection file
                                include '../includes/dbconnect.php';
                                // Insert transaction data into the database
                                $sql = "INSERT INTO user_subscriptions(user_id,stripe_subscription_id,stripe_customer_id,stripe_plan_id,plan_amount,plan_amount_currency,plan_interval,plan_interval_count,payer_email,created,plan_period_start,plan_period_end,status) VALUES('".$userID."','".$subscrID."','".$custID."','".$planID."','".$planAmount."','".$planCurrency."','".$planinterval."','".$planIntervalCount."','".$email."','".$created."','".$current_period_start."','".$current_period_end."','".$status."')";
                                $insert = $db->query($sql);
                                // Update subscription id in the users table
                                if($insert && !empty($userID)){
                                    $subscription_id = $db->insert_id;
                                    $update = $db->query("UPDATE steam_contributors SET subscription_id = {$subscription_id} WHERE memberid = {$userID}");
                                }
                                $ordStatus = 'success';
                                $statusMsg = 'Your Subscription Payment has been Successful!';
                            }else{
                                $statusMsg = "Subscription activation failed!";
                            }
                        }else{
                            $statusMsg = "Subscription creation failed! ".$api_error;
                        }
                    }else{
                        $statusMsg = "Plan creation failed! ".$api_error;
                    }
                }else{
                    $statusMsg = "Invalid card details! $api_error";
                }
            }else{
                $statusMsg = "Error on form submission, please try again.";
            } 
        } catch(Exception $e) {
            $api_error = $e->getMessage();
        }
        
        

          That appears to have kept it from breaking, I'm able to view errors now.

          Notice: Undefined variable: stripe in /home/dh_t352um/steamn.net/subscription/payment.php on line 36
          Notice: Trying to get property 'id' of non-object in /home/dh_t352um/steamn.net/subscription/payment.php on line 36.
          

          I removed the 'stripe_account = $stripe => id' array after the first call to create the account and above error disappeared. After checking my dashboard, it did create a connected account however it's not creating the subscription like it did previously. Does anyone have experience with this? It's restricted so perhaps I need to supply the onboarding process before I can actually make a subscription charge.

          https://stripe.com/docs/connect/subscriptions
          https://stripe.com/docs/connect/custom-accounts

                    $stripe = \Stripe\Account::create(array(
                            "email" => $email,
                            "country"  => "US",
                    "type"  => "custom",
                    'capabilities' => [
                    'card_payments' => ['requested' => true],
                    'transfers' => ['requested' => true],
                ],
                    ), array("stripe_account" => $stripe->id));
            

            Which looks weird because to construct the variable in $stripe it needs a property (id) from the very object that hasn't been constructed yet.

            Stripe's own documentation for creating an account looks a bit different:

            $stripe = new \Stripe\StripeClient(
              'sk_test_4eC39HqLyjWDarjtT1zdp7dc'
            );
            $stripe->accounts->create([
              'type' => 'custom',
              'country' => 'US',
              'email' => 'jenny.rosen@example.com',
              'capabilities' => [
                'card_payments' => ['requested' => true],
                'transfers' => ['requested' => true],
              ],
            ]);
            

            Except the API key would really come from \Stripe\Stripe::getApiKey(), and you'd put the return value (an account object) into a variable.

            That's all I got from a couple of minutes of looking at the Stripe documentation.

              Write a Reply...