blackimpala

payment_init_php

Mar 28th, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.01 KB | None | 0 0
  1. <?php
  2. // Include the configuration file
  3. // require_once 'config.php';
  4. // Include database connection file
  5. include_once '../db_connection.php';
  6. // Include the Stripe PHP library
  7. require_once '../vendor/stripe/stripe-php/init.php'
  8. // Set API key
  9. \Stripe\Stripe::setApiKey(STRIPE_SECRET_API_KEY);
  10. // Retrieve JSON from POST body
  11. $jsonStr = file_get_contents('php://input');
  12. $jsonObj = json_decode($jsonStr);
  13. // Get user ID fron current SESSION
  14. $userID = isset($_SESSION['loggedInUserID'])?$_SESSION['loggedInUserID']:0;
  15.  
  16. if ($jsonObj->request_type == 'create_customer_subscription') {
  17.   $subscr_plan_id = !empty($jsonObj->subscr_plan_id)?$jsonObj->subscr_plan_id:'';
  18.   $name = !empty($jsonObj->name)?$jsonObj->name:'';
  19.   $email = !empty($jsonObj->email)?$jsonObj->email:'';
  20.  
  21.   // Fetch plan details fron the database
  22.   $sqlQ = "SELECT `name`, `price`, `interval` FROM plans WHERE id=?";
  23.   $stmt = $con->prepare($sqlQ);
  24.   $stmt->bind_param("i", $subscr_plan_id);
  25.   $stmt->execute();
  26.   $stmt->bind_result($planName, $planPrice, $planInterval);
  27.   $stmt->fetch();
  28.  
  29.   // Convert price to cents
  30.   $planPriceCents = round($planPrice*100);
  31.  
  32.   // Add customer to Stripe
  33.   try {
  34.     $customer = \Stripe\Customer::create([
  35.       'name' => $name,
  36.       'email' => $email
  37.     ]);
  38.   } catch ( Exception $e ) {
  39.     $api_error = $e->getMessage();
  40.   }
  41.  
  42.   if (empty($api_error) && $customer) {
  43.     // Create price with subscription info and interval
  44.     try {
  45.       $price = \Stripe\Price::create([
  46.         'unit_amount' => $planPriceCents,
  47.         'currency' => STRIPE_CURRENCY,
  48.         'recurring' => ['interval' => $planInterval],
  49.         'product_data' => ['name' => $planName],
  50.       ]);
  51.     } catch ( Exception $e ) {
  52.       $api_error = $e->getMessage();
  53.     }
  54.     if (empty($api_error) && $price) {
  55.       // Create a new subscription
  56.       try {
  57.         $subscription = \Stripe\Customer::create([
  58.           'customer' => $customer->id,
  59.           'items' => [[
  60.               'price' => $price->id
  61.             ]],
  62.             'payment_behavior' => 'default_incomplete',
  63.             'expand' => ['latest_invoice.payment_intent'],
  64.         ]);
  65.       } catch ( Exception $e ) {
  66.         $api_error = $e->getMessage();
  67.       }
  68.       if (empty($api_error) && $subscription) {
  69.         $output = [
  70.           'subscriptionId' => $subscription->id,
  71.           'clientSecret' => $subscription->latest_invoice->payment_intent->client_secret,
  72.           'customerId' => $customer->id
  73.         ];
  74.         echo json_encode($output);
  75.       }else{
  76.         echo json_encode(['error' => $api_error]);
  77.       }
  78.     }else{
  79.       echo json_encode(['error' => $api_error]);
  80.     }
  81.   }else{
  82.     echo json_encode(['error' => $api_error]);
  83.   }
  84.  
  85. }elseif ($jsonObj->request_type == 'payment_insert') {
  86.   $payment_intent = !empty($jsonObj->payment_intent)?$jsonObj->payment_intent:'';
  87.   $subscription_id = !empty($jsonObj->subscription_id)?$jsonObj->subscription_id:'';
  88.   $customer_id = !empty($jsonObj->customer_id)?$jsonObj->customer_id:'';
  89.   $subscr_plan_id = !empty($jsonObj->subscr_plan_id)?$jsonObj->subscr_plan_id:'';
  90.   // Fetch plan details from the database
  91.   $sqlQ = "SELECT `interval` FROM plans WHERE id=?";
  92.   $stmt = $con->prepare($sqlQ);
  93.   $stmt->bind_param("i", $subscr_plan_id);
  94.   $stmt->execute();
  95.   $stmt->bind_result($interval);
  96.   $stmt->fetch();
  97.   $planInterval = $interval;
  98.   $stmt->close();
  99.   // Retrieve customer info
  100.   try {
  101.     $customer = \Stripe\Customer::retrieve($customer_id);
  102.   } catch ( Exception $e) {
  103.     $api_error = $e->getMessage();
  104.   }
  105.   // Check whether the charge was successful
  106.   if (!empty($payment_intent) && $payment_intent->status == 'succeeded') {
  107.     // Retrieve subscription info
  108.     try {
  109.       $subscriptionData = \Stripe\Customer::retrieve($subscription_id);
  110.     } catch ( Exception $e) {
  111.       $api_error = $e->getMessage();
  112.     }
  113.     $payment_intent_id = $payment_intent->id;
  114.     $paidAmount = $payment_intent->amount;
  115.     $paidAmount = ($paidAmount/100);
  116.     $paidCurrency = $payment_intent->currency;
  117.     $payment_status = $payment_intent->status;
  118.  
  119.     $created = date("Y-m-d H:i:s", $payment_intent->created);
  120.     $current_period_start = $current_period_end = '';
  121.     if (!empty($subscriptionData)) {
  122.       $created = date("Y-m-d H:i:s", $subscriptionData->created);
  123.       $current_period_start = date("Y-m-d H:i:s", $subscriptionData->$current_period_start);
  124.       $current_period_end = date("Y-m-d H:i:s", $subscriptionData->$current_period_end);
  125.     }
  126.  
  127.     $customer_name = $customer_email ='';
  128.     if (!empty($customer)) {
  129.       $customer_name = !empty($customer->name)?$customer->name:'';
  130.       $customer_email = !empty($customer->email)?$customer->email:'';
  131.  
  132.       if (!empty($customer_name)) {
  133.         $name_arr = explode('', $customer_name);
  134.         $first_name = !empty($name_arr[0])?$name_arr[0]:'';
  135.         $last_name = !empty($name_arr[1])?$name_arr[1]:'';
  136.       }
  137.       // Insert user details if no exists in the DB users table
  138.       if (empty($userID)) {
  139.         $sqlQ = "INSERT INTO users (first_name, last_name, email) VALUES (?,?,?)";
  140.         $stmt = $con->prepare($sqlQ);
  141.         $stmt->bind_param("sss", $first_name, $last_name, $customer_email);
  142.         $insertUser = $stmt->execute();
  143.  
  144.         if ($insertUser) {
  145.           $userID = $stmt->insert_id;
  146.         }
  147.       }
  148.     }
  149.     // Check if any transaction  data exists already with the same TXN ID
  150.     $sqlQ = "SELECT id FROM user_subscriptions WHERE stripe_payment_intent_id = ?";
  151.     $stmt = $con->prepare($sqlQ);
  152.     $stmt->bind_param("s", $payment_intent_id);
  153.     $stmt->execute();
  154.     $stmt->bind_result($id);
  155.     $stmt->fetch();
  156.     $prevPaymentID = $id;
  157.     $stmt->close();
  158.  
  159.     $payment_id = 0;
  160.     if (!empty($prevPaymentID)) {
  161.       $payment_id = $prevPaymentID;
  162.     }else{
  163.       // Insert transaction data into the database
  164.       $sqlQ = "INSERT INTO user_subscriptions (user_id, plan_id, stripe_subscription_id, stripe_customer_id, stripe_payment_intent_id,
  165.      paid_amount, paid_amount_currency, plan_interval, customer_name, customer_email, created, plan_period_start, plan_period_end, status)
  166.      VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  167.       $stmt = $con->prepare($sqlQ);
  168.       $stmt->bind_param("iisssdssssssss", $userID, $subscr_plan_id, $subscription_id, $customer_id, $payment_intent_id,
  169.       $paidAmount, $paidCurrency, $planInterval, $customer_name, $customer_email, $created, $current_period_start,
  170.       $current_period_end, $payment_status);
  171.       $insert = $stmt->execute();
  172.  
  173.       if ($insert) {
  174.         $payment_id = $stmt->insert_id;
  175.         // Update subscription ID in users table
  176.         $sqlQ = "UPDATE users SET subscription_id=? WHERE id=?";
  177.         $stmt =$con->prepare($sqlQ);
  178.         $stmt->bind_param("ii", $payment_id, $userID);
  179.         $update = $stmt->execute();
  180.       }
  181.     }
  182.     $output = [
  183.       'payment_id' => base64_encode($payment_id)
  184.     ];
  185.     echo json_encode($output);
  186.   }else{
  187.     echo json_encode(['error' => 'Transaction has been failed!']);
  188.   }
  189. }
  190.  
  191. ?>
  192.  
Add Comment
Please, Sign In to add comment