php - 前 30 天到期后,如何取消每月定期费用?

标签 php mysql stripe-payments

我正在使用 stripe 创建订阅计划,一切都很顺利,但我想创建一个取消订阅按钮,我已经通过 stackoverflow 寻找答案,但我找不到任何帮助、任何有用的资源或非常感谢代码!

高级.php:

<?php
require_once 'app/init.php';
include 'app/dbh.inc.php';
?>
<html>
<body>
    <p>You're about to go premium.</p>
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>Premium</title>
      </head>
      <body>
    <form action="premium_charge.php" method="POST">
      <script
        src="https://checkout.stripe.com/checkout.js"
        class="stripe-button"
        data-key="<?php echo $stripe['publishable']; ?>"
        data-name="Connect Kitty"
        data-description="Catwalk"
        data-email="<?php echo $user->email; ?>"
        data-amount="599"
        data-currency="usd">
      </script>
    </form>
  </body>
</html>

premium_charge.php:

<?php

 require_once 'app/init.php';

if(isset($_POST['stripeToken'])) {

   $token = $_POST['stripeToken'];

   try {

      Stripe_Charge::create([
      "amount" => 599,
      "currency" => "usd",
      "source" => $token,
      "description" => $user->email
      ]);
      $db->query("
        UPDATE tbl_twitter_user SET premium = 1
        WHERE user_id = {$user->user_id}
      ");

   } catch(Stripe_CardError $e) {

   }
   header('Location: index1.php');
   exit();
}
?>

init.php:

<?php
session_start();

require_once 'vendor/autoload.php';

$stripe = [
   'publishable' => 'pk_test_QR1JpboiLh5acjEhK6vwclar00N1Y0Evjd',
   'private' => 'sk_test_N62K1YeWqBN1WyEsWmK149Rh00It8OTxqg'
];

Stripe::setApiKey($stripe['private']);

$db = new PDO('mysql:host=127.0.0.1;dbname=am', 'nt', 'f9');

$userQuery = $db->prepare("
   SELECT user_id, username, email, premium
   FROM tbl_twitter_user
   WHERE username = :username
");

$userQuery->execute(['username' => $_SESSION['username']]);

$user = $userQuery->fetchObject();
?>

我已经包含了所有代码,因为我不确定需要使用哪个文件。

还有,如果有人担心 SQL 注入(inject)!

最佳答案

创建订阅时,您应该将订阅 ID 保存在数据库中。当用户要求取消订阅时,从数据库获取其订阅 ID 并调用 Stripe API:

$stmt = $db->prepare("SELECT subscription_id FROM tbl_twitter_user WHERE user_id = :userid");
$stmt->execute(['user_id' => $user->user_id]);
$row = $stmt->fetch(PDO::FETCH_OBJ);
$sub = \Stripe\Subscription::retrieve($row->subscription_id);
$sub->cancel();

关于php - 前 30 天到期后,如何取消每月定期费用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664311/

相关文章:

mysql - 如何从 varchar 转换为 float 并忽略非数字字符?

python - 在 django/python 中创建 Stripe 电荷的正确方法

php - laravel 如何加载配置文件

php - 奇怪的sql和javascript ajax错误

Php 页面无法从 mysql 值中识别 "ø"

php - 在 PHP 和 MySQL 中显示来自 URL 的图像

PHP代码点火器: remove element from a two-dimensional column from its id

PHP MySQL 对象优化

php - Stripe : How to retrieve transfer information from a connected account

ruby-on-rails - Stripe Connect API (Ruby) 用 "Managed Account": delete bank account, 添加多个银行账户