I have a pricing table that includes 3 plans with different prices.
I'm trying to charge the user the amount related to the plan they select. Is there a way to dynamically fetch the amount on the server side using PHP when the user selects a plan and the form is submitted? I'm not sure how to pass the dollar amount safely and charge them.
Edit: added PHP code
Here is the PHP i'm working with which pulls the dollar amount from the form which is inside a value. eg. "value='20'. My problem with the current setup is anyone can change that value.
<?php
require 'lib/Stripe.php';
if ($_POST) {
Stripe::setApiKey("insert_key_here");
try {
if (empty($_POST['email']))
throw new Exception("Fill out all required fields.");
if (!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
Stripe_Charge::create(array("amount" => $_POST['posted'] * 100,
"currency" => "usd",
"card" => $_POST['stripeToken'],
"description" => $_POST['email']));
$success = '<div class="alert alert-success">
<strong>Success!</strong> Your payment was successful.
</div>';
}
}
?>
I would recommend passing a an additional <input type="hidden">-field or a drop-down along with your form that contains the tier name. This can map to an enumeration (or map) on your backend that has the actual amounts associated with each tier. Then you don't run the risk of someone screwing with your Javascript and changing what they have to pay.
Related
I want to simply change the shipping method of an order on Woocommerce.
I have seen a few posts on editing shipping methods on orders but I'm not 100% clear on the exact protocol of how it works, I have a rough idea but no success yet! If you can help me to get the order to update its shipping method that would be awesome! (this is the middle of a large project so I can't share the whole plugin, let me know if you need anymore details happy to provide anything that's necessary!)
I have this small bit of code that returns me a list of orders that need shipping method updated and the new shipping method rateID that it has to be changed to, that all works fine but i have included it so you can see where it comes from.
Once the array of orders to be updated has been constructed, it then needs to be processed using the set_shipping() method. One at a time working through the array items and updating the shipping method of each, from the original to the new one provided in the toUpdate array
UPDATED: i have tried using the WC_API_Orders() class as set_shipping is a method of that. still coming up with the unrecognised error.
'Class 'Inc\Api\Callbacks\WC_API_Orders' not found'
private function updateRound()
{
if (! empty($_POST['update'])) {
$updateorderID= $_POST['orderID']; //get list of orderID to change
$updateRound= $_POST['newRound']; //list of rounds new orders want swapped to
$updateList= $_POST['update']; //uses a check box to confirm user wants to update row (stops accidentally updating the whole list)
// print_r($_POST['update']); //shows an output to check results.
$toUpdate = []; //this is the array for all the shippingmmethods to update on set order etc.
//make list of order ID's to update and their new shipping method
foreach ($updateList as $key => $value) {
$toUpdate[] = [
'orderID' => $key,
'newRound' => $updateRound[$key]
];
}
}
$absOrder = new WC_API_Orders();
foreach ($toUpdate as $updateOrder) {
//echo "</br>OrderID: ".$updateOrder['orderID']." Round updated to ".$updateOrder['newRound'];
echo "order ".$updateOrder['orderID']."updating";
$absOrder->wc_get_order($updateOrder['orderID']);
echo " order retreived";
$absOrder->set_shipping($order, $updateOrder['newRound'], 'update' );
echo "updated </br>";
}
}
This is for a very local veg delivery scheme, people can only place an order if their postcode is in the set group, so that's not so important, this shipping method we use to change from 'wed round' to 'thurs round' etc. Simple really no concern for delivery companies etc, its all in house. Tax etc. doesn't matter, it's all done elsewhere, this is simply meant to be a way of editing orders onto delivery rounds.
I want to implement a monthly subscription with Stripe and PHP. I followed that instructions: https://stripe.com/docs/recipes/subscription-signup#creating-the-signup-form-using-checkout
1- I have gone to the Dashboard and created a product: Monthtly fee and a plan of 9.99 eur/month with the name Monthly1. Let's say that the id of the product is prod_222222w
2- Index.php:
<form action="create_subscription.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_SomeNumbersAndLetters"
data-image="images/stripe.png"
data-name="F. subscription"
data-description="9.99 montly fee"
data-amount="999"
data-label="Sign Me Up!">
</script>
</form>
3-create_subscription.php. I installed Composer and I think, it works well
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("sk_test_SomeNumbersAndLetters");
try
{
$customer = \Stripe\Customer::create(array(
'email' => $_POST['stripeEmail'],
'source' => $_POST['stripeToken'],
));
$subscription = \Stripe\Subscription::create(array(
'customer' => $customer->id,
'items' => array(array('plan' => 'weekly_box')),
));
header('Location: thankyou.php');
exit;
}
catch(Exception $e)
{
header('Location:oops.php');
error_log("unable to sign up customer:" . $_POST['stripeEmail'].
", error:" . $e->getMessage());
}
If I understand I have to change the id of the plan. Where should I put that?
If I understand I have to change also the stripeToken and stripeEmail. If so, where I get that and where I have to put it?
Sorry, I am very confused. I am not a programmer. I teach myself. I managed to build a site, but implementing Stripe is the most difficult part. I would appreciate any orientation.
"If I understand I have to change the id of the plan. Where should I put that?" - from looking at the code, I assume you need to provide the plan ID here:
'items' => array(array('plan' => 'PLAN_ID_HERE'))...
"If I understand I have to change also the stripeToken and stripeEmail" - you do not need to change these, leave them as $_POST['stripeEmail'] and $_POST['stripeToken'] and these parameters will be pulled in from the Checkout application.
Be sure to use the proper 'test' data/API keys for testing, and then replace them with the correct 'live' data/API keys once you are ready to make it live.
I finally solved the problem. I give the complete solution here if someone else got that problem. The answer of Justin T is correct. You only have to change the plan ID. To get that, you have to go to Stripe > Dashboard > Billing > Products > Pricing plans and click on the name of your Pricing Plan.
I have added this code but this is not working. I want the promocodes to be saved in infusionsoft
$carray = array(
php_xmlrpc_encode($app->key),
php_xmlrpc_encode($contactId),
php_xmlrpc_encode($creditCardId),
php_xmlrpc_encode($payPlanId),
php_xmlrpc_encode(array($productId1, $productId2)),
php_xmlrpc_encode(array($subscriptionPlanId1, $subscriptionPlanId2)),
php_xmlrpc_encode($processSpecials),
php_xmlrpc_encode(array($promoCode1, $promoCode2)) // array of strings
);
$app->methodCaller("OrderService.placeOrder", $carray);
Promo Codes are read-only. This means that, while they can be used during orders and applied to invoices, you can't add new Promo Codes via the API.
This is an unfortunate limitation of the InfusionSoft API. Read more in the Table Documentation.
I'm using Stripe's php library to create a customer with a subscription that contains a coupon. I don't want to add the coupon at the customer level, I want to add it at the subscription level. The below code is what I'm currently using and according to their support, this should work, but it doesn't. I was hoping someone will be able to help.
$params = array(
'card'=>'SOME_TOKEN_FROM_JS_LIBRARY',
'plan'=>'valid_plan_id',
'coupon'=>'valid_coupon_id'
);
$c = Stripe_Customer::create($params);
if(!empty($params['coupon'])){
$c->updateSubscription(array(
'plan'=>$params['plan'],
'coupon'=>$params['coupon']
));
}
This successfully creates the customer and charges the card with the coupon applied.
Ended up going with the code below, it does what I want it to do. Also, the goal with the code below is to delete the customer if the charge fails for whatever reason, so I'm not left with customers that don't belong anywhere.
$_c = Stripe_Customer::create($params);
try{
$_c->subscriptions->create(array('plan'=>$plan, 'coupon'=>$coupon));
}catch(Exception $e){
$_c->delete();
throw new Exception($e->getMessage());
}
$c = Stripe_Customer::retrieve($_c->id); //to get the customer object with the latest data
I'm using Stripe for a payment gateway. I can successfully obtain a card's "token" as Stripe calls it, which is explained here: https://stripe.com/docs/checkout#api
Good to go with that. I successfully receive the token in my stripe dashboard. Now what I need to do is actually charge that card(token). Here is how they put it: "You've got your user's credit card details, now what? Now you charge them money. This happens on your server, and the fastest way to do it is by using one of our client libraries." Well they supply the php needed right on that page:
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://manage.stripe.com/account
Stripe::setApiKey("sk_test_68YYnDTKPzcxxRZbkxEJtOVq");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = Stripe_Charge::create(array(
"amount" => 1000, // amount in cents, again
"currency" => "usd",
"card" => $token,
"description" => "payinguser#example.com")
);
} catch(Stripe_CardError $e) {
// The card has been declined
}
You can see exactly how they explain it here: https://stripe.com/docs/tutorials/charges
Here is where things go wrong.
1) Where in this code actually pinpoints what card to charge?! I have the card's token ID number in my private dashboard. I now need to charge it, but this code doesn't say anything about the card. The only spot I see is:
$token = $_POST['stripeToken'];
'stripeToken' do I put in the card's ID number here?
2)I've created a simple page to run this with:
<div id="payment">
<form action="charge-cards.php">
<?php require 'Stripe.php';?>
<input type="submit">
</form>
</div><!--end payment-->
"charge-cards.php" is the code at the top provided by Stripe. When I click submit, I get the follow error:
Fatal error: Class 'Stripe' not found in /home/preemin/public_html/fun.dit /testing/charge-cards.php on line 5
Can anyone see what I"m doing wrong? Thanks!
I think it's worthwhile to take a step back and review the basics. First, in order to provide a secure credit card transaction, and to ensure PCI compliance, Stripe has provided a javascript library that encrypts and transmits the sensitive credit card data. They provide an example form
Make careful note of the fact that the form has no submit action. Also pay special attention to the fact that none of the sensitive card fields have a name attribute. This form should never be submitted via any way other than the secure method they have provided. To try to do so opens you up to liability.
When you submit that form, using the js class they have provided (see Step 2), it gives you back a card token, which you say you already have. You can store that card token in your database without any security issues -- it's just an arbitrary number that means nothing to a hacker.
Once you have that token, you have two options:
use it immediately to make a one-time charge, or
store it and create a customer object that you can charge multiple times.
What you need to realize is that Stripe does NOT store that card token! If you lose it, you can't get it back. You have to generate a new one. Also, the only way you can use it for multiple charges is to create a customer object. In other words, UNLESS you store it on a customer object, it's only good for a single charge. So if you charge against it before attaching it to a customer object, it's no longer valid.
Now back to the basics again, as IOIO MAD described, there are two things you must do at the top of any php file that you want to call a Stripe method from:
include the Stripe php library
set the secret key
The only time the public key is used is when you're making that javascript call to submit the card form.
If you want to charge the card immediately, you have to turn right around and make a call back to the server, sending the card hash that you just got back. You might do this with ajax, or by sticking it in a form field that you then post. Step 3 shows you one way you might do this.
But lets assume that you want to do other things before actually charging the card. To expand on your example, lets say I have collected my customer's card on one page, then on my checkout page, I want to submit the charge:
<?php
require('path/to/Stripe.php'); // MUST be done before any Stripe:: call
Stripe::setApiKey("sk_test_mkGsLqEW6SLnZa487HYfJVLf");
// retrieve stored card hash. Could have got it to this page in any number of
// ways, including: stored in cookie, stored in session, stored in database.
// Let's assume stored in session for sake of simplicity of example
$cardHash = $_SESSION['stripeToken'];
?>
<div id="payment">
<form action="charge-cards.php">
<?php require 'Stripe.php';?>
<input name="stripeToken" type="hidden" value="<?= $cardHash ?>" />
<input type="submit">
</form>
</div>
When this form is submitted, charge-cards.php will get the $cardHash from the $_POST variable, whereupon you're going to follow the example given by Stripe:
<?php
require('path/to/Stripe.php'); // MUST be done before any Stripe:: call
Stripe::setApiKey("sk_test_mkGsLqEW6SLnZa487HYfJVLf");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = Stripe_Charge::create(array(
"amount" => 1000, // amount in cents, again
"currency" => "usd",
"card" => $token,
"description" => "payinguser#example.com")
);
} catch(Stripe_CardError $e) {
// The card has been declined
}
?>
If you're still having problems, employ proper debugging skills to check whether or not your $_POST variable contains a card hash. If all else fails, contact Stripe customer support. Their API is top-notch, as is their documentation and support.
EDIT 4/15/13
OP is using the quick checkout method and using custom buttons. Most of the above still applies.
The code outlined in the Custom Buttons section assigns a click handler to the custom button, which returns a callback function that when executed, appends a hidden input to a form, assigns the stripeToken to that field, and submits the form. Just before the form is submitted, console.log or alert the stripeToken to make sure you have a legitimate value:
$('#customButton').click(function(){
var token = function(res){
var $input = $('<input type=hidden name=stripeToken />').val(res.id);
// alert the value of stripeToken
alert('stripeToken = ' + res.id);
$('form').append($input).submit();
};
This would be used in conjunction with this:
<form action="/charge" method="post">
<script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"
data-key="pk_test_yourprivatekeyhere"></script>
</form>
So what should happen is after the user presses the checkout button, the form should have a hidden input field named 'stripeToken' which contains the token value. You can get that token from the form and submit it later. Alternatively, you can listen on the 'token' event, which will be bound to your button:
jQuery(function($){
var $button = $('#customButton');
$button.on('token', function(e, token){
$button.after('<hr /><p>Your Stripe token is: <strong>' + token.id + '</strong></p>');
});
});
DISCLAIMER: I haven't used the simple checkout method yet. This code is not tested
i think may be you are missing some "include" , Class 'Stripe' not found means that the PHP File consisting of Class 'Stripe' haven't included before the call#
Note : A PHP >= 5.2 environment is required
Download The Stripe PHP library
Extract it to your HOME!
Let’s create a file called config.php, where we’re going to set up some initial configuration.
<?php
require_once('./lib/Stripe.php');
$stripe = array(
"secret_key" => "sk_test_mkGsLqEW6SLnZa487HYfJVLf",
"publishable_key" => "pk_test_czwzkTp2tactuLOEOqbMTRzG"
);
Stripe::setApiKey($stripe['secret_key']);
?>
Then at your Code file ABOVE (assumes yours.php)
include "config.php";
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
//rest as you go!