首页 文章

如何使用Stripe JS PHP进行可变数量的recurent捐赠计划订阅

提问于
浏览
0

我不是一个疯狂的编码器专家,但我想使用带有这些功能的Stripe灯箱表格:

  • 用户可以为一次性捐赠输入可变金额,然后向他充电(看起来工作,我可以在Stripe中看到令牌和充电)

  • 用户可以输入年度捐款的可变金额然后向他收取费用然后发送电子邮件,最低金额为3000日元(约30美元)

问题 :

  • 在表单中,我使用技术使用户支付最少3000日元,如果他将值更改为0例如当他将输入区域重点变为3000再次变为3000时这就是为什么我使用value =“3000”但它将是更好,如果它只能占位符=“3,000 YEN最小”

  • 充电后用户Stripe没有发送电子邮件确认,我看了它在测试模式下没有这样做,仍然是真的吗?

  • 如果有可能,我想隐藏html源代码中的公钥

  • 主要问题是当用户输入可变数量并验证其启动条带灯箱窗口的表格然后它在我的服务器上启动charge2.php但是要创建计划时,必须使用唯一的计划ID修复金额 .

所以在这里我的代码,想法是生成一个日期并使用它来创建一个独特的计划ID,但它不起作用,我不确定是最好的方法,我读这个但我迷路了,我不知道如何https://support.stripe.com/questions/metered-subscription-billing

此外,我将使用此表单将其包含到我的wordpress与插件php-code-for-posts(它看起来工作查找,但我不知道它是最好的做法和安全的方式,构建一个插件对我来说太复杂了)

所以我的文件结构:

  • ROOT

  • ../Vendor/Stripe/(与作曲家合作,是否可以在没有作曲家的情况下安装?)

  • ../Wordpress/config.php

  • ../Wordpress/Stripepay.php

  • ../Wordpress/charge.php

  • ../Wordpress/charge2.php

该代码的灵感来自 https://jsfiddle.net/ywain/g2ufa8xr/

我把代码放了// !!关于我的问题的信息

config.php

<?php
// require with composer install
require_once('../vendor/autoload.php');

$stripe = array(
  "secret_key"      => "sk_test_ your secret_key",
  "publishable_key" => "pk_test_ your publishable_key"
);

\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>

stripepay.php

<?php require_once('../config.php');?>
<!-- Stripe Panel, This script only work remotely -->
<script src="https://checkout.stripe.com/checkout.js"></script> 
<!-- JQuery auto update CDN -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- /////////////////////////////// ONE SHOT PAYMENT ///////////////////////////////// -->
<h2>One Donation</h2>
Please add any value below
<!-- Form and Charge Validation -->
<form id="payment-form" action="charge1" method="POST">
    <input type="number" id="amount" name="amount" value="3000" placeholder="3,000 Minimum" min="3000" step="500.00" />
    <input type="hidden" id="stripeToken" name="stripeToken"/>
    <input type="hidden" id="stripeEmail" name="stripeEmail"/>
</form>
<input type="button" id="btn" value="Donate" class="strbtn">

<script type="text/javascript">
// JS Script Handle amount value and other Stripe options.
var handler = StripeCheckout.configure({
    key: '< ?php echo $stripe['publishable_key']; ?>', // !! Possible to hide from HTML source view ?? 
    image: '../logo.jpg',
    token: function(token) {
        $("#stripeToken").val(token.id);
        $("#stripeEmail").val(token.email);
        $("#payment-form").submit();
    }
  });

 $('#btn').on('click', function(e) {
    var amount = $("#amount").val() *1; // !! normaly it's *1000 but with YEN need to apply this ??
// Open Checkout with further options
    handler.open({
// OPTIONAL, UNCHECK THE // TO ACTIVATE IT:
      //bitcoin: 'true',
      //alipay: 'true',
      billingAddress: 'true',
      zipcode: 'true',
      allowRememberMe: 'true',
      //stripeEmail: 'true', // !! Stripe in test mode doesn't send email confirmation, there is any way to check if it will works ??
      name: 'company name',
      description: 'company description',
      locale: 'auto', // !! on reults it show i'm from USA but i'm in Japan, is it based on navigator ? There is a way to be more accurate ??
      panelLabel: 'DONATE',
      currency: 'jpy',
      amount: amount  
    });
    e.preventDefault();
  });

  // Close Checkout on page navigation
  $(window).on('popstate', function() {
    handler.close();
  });

//to prevent zero amount in the form, add 3000 when focus out of the field  
$(document).ready(function(){
    $("body").delegate('#amount', 'focusout', function(){ // !! There is a better way to make the minimum amount 3000Yen ??
        if($(this).val() < 3000){
            $(this).val('3000');
        }
    });
});
</script>



<!-- /////////////////////////////// ANNUAL PAYMENT SUBSCIPTION ///////////////////////////////// -->
<h2>Annual Recurring Donations</h2>
Please add any value below
<!-- Form and Charge Validation -->
<form id="payment-form2" action="charge2" method="POST">
    <input type="number" id="amount2" name="amount" value="3000" placeholder="3,000 Minimum" min="3000" step="500.00" />
    <input type="hidden" id="stripeToken2" name="stripeToken"/>
    <input type="hidden" id="stripeEmail2" name="stripeEmail"/>
    <input type="hidden" id="idplan" name="idplan"/>
</form>
<input type="button" id="btn2" value="Subscription" class="strbtn">

<script type="text/javascript">
// JS Script Handle amount value and other Stripe options.
var handler = StripeCheckout.configure({
    key: '<?php echo $stripe['publishable_key']; ?>',
    image: '../str-gps-logo.jpg',
    token: function(token) {    
        $("#stripeToken2").val(token.id);
        $("#stripeEmail2").val(token.email);
        $("#payment-form2").submit();
    }
  });


 $('#btn2').on('click', function(e) {
    var amount = $("#amount2").val() *1;
    var plan = $("#idplan").val(Date); // !! Generate Date ID for the Plan to be a unique id value, possible to add milisecond too ??

// Open Checkout with further options
    handler.open({
      billingAddress: 'true',
      zipcode: 'true', // !! is it like this or zip-code: ??
      name: 'Year Plan',
      description: 'Variable Amount Year Plan',
      locale: 'auto',
      panelLabel: 'Subscribe',
      currency: 'jpy',
      amount: amount 
    });
    e.preventDefault(); 
    });

  // Close Checkout on page navigation
  $(window).on('popstate', function() {
    handler.close();
  });

//to prevent zero amount in the form, add 3000 when focus out of the field  
$(document).ready(function(){
    $("body").delegate('#amount2', 'focusout', function(){
        if($(this).val() < 3000){
            $(this).val('3000');
        }
    });
});

</script>

charge.php

<?php
  require_once('./config.php');

// Check if the user have javascript and if the token is validated.
// !! code below needed or more simple with   $token = $_POST['stripeToken'];   ??

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array();
    if (isset($_POST['stripeToken'])) {
        $token = $_POST['stripeToken'];
    } else {
        $errors['token'] = 'The order cannot be processed. You have not been charged. 
                            Please confirm that you have JavaScript enabled and try again.';
    }
}

// Create the Customer: 
  $customer = \Stripe\Customer::create(array( 
      'email' => $_POST['stripeEmail'],
      'source'  => $token
  ));

// Create the Charge:
  $charge = \Stripe\Charge::create(array(
      'customer' => $customer->id,
      'amount'   => $_POST['amount'],
      'currency' => 'jpy'
  ));

  echo '<h1>Thanks for your donation ! </h1>'; // !! There is a way to show error to user and redirect to index ?

?>

charge2.php

<?php
  require_once('./config.php');

// Check if the user have javascript and if the token is validated.
//$token  = $_POST['stripeToken'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array();
    if (isset($_POST['stripeToken'])) {
        $token = $_POST['stripeToken'];
    } else {
        $errors['token'] = 'The order cannot be processed. You have not been charged. 
                            Please confirm that you have JavaScript enabled and try again.';
    }
}

// TEST 1 inspired from http://stackoverflow.com/questions/36075869/how-to-create-variable-subscriptions-in-stripe 

// !! Find the way to generate unique id to create the plan or any other solution for a variable amount recurent donation plan subscription

$plan = \Stripe\Plan::create(array(
        'name' => $_POST['idplan'],
        'id' => $_POST['idplan'],
        'interval' => 'day', // !! interval daily for testing purpose but the final will be in years 
        'interval_count' => '1',
        'currency' => 'jpy',
        'amount' => $_POST['amount']    
    ));

$customer = \Stripe\Customer::create(array( 
      'source'  => $token,
      'email' => $_POST['stripeEmail'],
      'plan'  => $_POST['idplan'],
      'description' => 'plan description'
    ));

echo '<h1>Thanks for your annual donation ! </h1>';
?>

我确信有一种方法可以用一个更简洁的方式,只有一个充电文件和更少的ID混乱,但我不知道如何...

但如果你能帮助我解决主要问题,我真的很感激,这段代码让我发疯!

干杯!

1 回答

  • 0

    在形式上,我使用技术使用户支付最低3000日元,如果他将值更改为0例如当他将输入区域重点变为3000再次变为3000时这就是为什么我使用value =“3000”但它将是更好,如果它只能占位符=“3,000 YEN最小”

    由你来强制执行 . 我建议您添加客户端(Javascript)和服务器端(PHP)检查,以确保金额高于您的最小值 .

    充电后用户Stripe没有发送电子邮件确认,我看到它在测试模式下没有这样做,仍然是真的吗?

    是的,Stripe不会在测试模式下自动发送任何电子邮件收据 . 您仍然可以在信息中心查看特定费用,然后点击“发送回执”以手动发送回执 .

    如果有可能,我想隐藏html源代码中的公钥

    那个_2947423不是问题 . 可发布的密钥是公开可见的 . 它只能用于创建具有CheckoutStripe.js的标记,并且标记本身不执行任何操作 .

    主要问题是当用户输入可变数量并验证其启动条带灯箱窗口的表格然后它在我的服务器上启动charge2.php但是要创建计划时,必须使用唯一的计划ID修复金额 .

    有两种方法可以处理可变数量的订阅 . 最简单的可能是使用 amount=1 创建基本计划 . 然后,当您对此计划进行create subscriptions时,您将使用quantity参数来确保计费正确的金额 .

    更优雅但更复杂的解决方案是为每个客户创建一个新计划 . 在这种情况下,您需要确保每个计划都有唯一的ID - 例如,您可以使用客户的电子邮件地址:

    $plan_id = "plan_" . $_POST["stripeEmail"];
    
    $plan = \Stripe\Plan::create(array(
        "id" => $plan_id,
        "name" => "Subscription plan for " . $_POST["stripeEmail"],
        "amount" => $_POST["amount"], // amount sent by the customer's browser
        "currency" => "jpy",
        "interval" => "day",
    ));
    
    $customer = \Stripe\Customer::create(array(
        "email" => $_POST["stripeEmail"],
        "source" => $_POST["stripeToken"], // token returned by Stripe.js/Checkout
        "plan" => $plan_id,
    ));
    

    实际上,所有对Stripe API的调用都应包含在 try/catch 块中,以确保errors are handled正确 .

相关问题