I am working on Square payment gateway and I created three steps creating a customer, creating a card, and then making a payment.
$create_customer_request = new \Square\Models\CreateCustomerRequest();
$address = new \Square\Models\Address();
$address->setAddressLine1($ship_address);
$address->setPostalCode($_POST['ship_postcode']);
$address->setCountry('US');
$create_customer_request->setGivenName($_POST['f_name']);
$create_customer_request->setFamilyName($_POST['f_name']);
$create_customer_request->setEmailAddress($_POST['email']);
$create_customer_request->setAddress($address);
$create_customer_request->setPhoneNumber($_POST['phone']);
$create_customer_request->setReferenceId($_POST['f_name']."-customer-".rand(10,15));
$create_customer_request->setNote('A customer');
$custcreateapiResponse = $client->getCustomersApi() >createCustomer($create_customer_request);
$custcreateapiResponse->isSuccess();
$_SESSION['temp_customer_id'] = $cust_res->getCustomer()->getId();
creating a card request
$body_card = new \Square\Models\CreateCustomerCardRequest($_POST['nonce']);
$card_api_response = $client->getCustomersApi()->createCustomerCard($_SESSION['temp_customer_id'], $body_card);
making a payment
$payments_api = $client->getPaymentsApi();
$money->setAmount(10);
$money->setCurrency('USD');
$pay_body = new \Square\Models\CreatePaymentRequest($_POST['nonce'],uniqid(),$money);
$pay_body->setCustomerId($_SESSION['temp_customer_id']);
$response = $client->getPaymentsApi()->createPayment($pay_body);
The issue I am having right now, I need to make two requests with the Nonce token but the system doesn't allow me to do it for the Square payment gateway. Don't know what to do now, Any kind of help will be appreciated. Pardon me for any mistakes here.
I tried many solutions from the internet but none of them work for me, so I try logic by myself. I know it's not a good approach, however, it works for me
in payment form, I create another hidden field
<input type="hidden" id="card-nonce-1" name="nonce1">
create a new function in sq-payment-form.js
function onGetCardNoncesecond(event) {
event.preventDefault();
paymentForm.requestCardNonce();
}
and put the value in a hidden field and submit and use it. Any suggestion would be appreciated for the betterment.
Related
In my webhook when I put $event_id = $event_json->id; I get the event id (example: id:evt_1EJ1NdIcP22cq9aQWsTXf8DY).
However, when I put $event_type = $event_json->type; I am expecting to get
charge.succeeded or charge.failed, instead I am getting customer.source.created.
I've searched the internet up and down, can't find the answer. What should I use to get what type of charge it was (charge.succeeded or charge.failed). Maybe this great community can help me solve this one.
OK, I've been banging my head against this for a few days now. I'm building a payment process into a PHP application which will allow for upselling products after a customer approves a payment.
I can get the payment charged to the customer without an issue, but if they select any kind of upsell product which requires the order value to change, then I get errors even though it is following to the letter what was in the documentation I could find...
Below is the test function I'm using, this is the function which is called when the user is redirected back to the website AFTER approving the payment.
public function confirmOrder($payer_id, $payment_id, $incentives = false){
//GET PAYMENT
$payment = Payment::get($payment_id, $this->apiContext);
//CREATE EXECUTION WITH PAYER ID
$execution = new PaymentExecution();
$execution->setPayerId($payer_id);
//APPLY PAYMENT AMOUNT - Original amount was 7.00
$amount = new Amount();
$amount = $amount->setCurrency('GBP')->setTotal('8.00');
//PATCH REPLACE
$patchReplace = new Patch();
$patchReplace = $patchReplace->setOp('replace')->setPath('/transactions/0/amount')->setValue($amount);
//CREATE PATCH OBJECT
$patchRequest = new PatchRequest();
$patchRequest = $patchRequest->setPatches(array($patchReplace));
try {
$payment->update($patchRequest, $this->apiContext);
} catch (PayPalConnectionException $ex) {
return "PATCH ERROR: State(" . $payment->getState() . ") ".$ex->getData();
}
}
This isn't the final code I will use but right now I'm just trying to get an order updated before I build in more of the logic. This code gives me the following error:
PATCH ERROR: State(created) {"name":"PAYMENT_STATE_INVALID","message":"This request is invalid due to the current state of the payment","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#PAYMENT_STATE_INVALID","debug_id":"9caacdc1d652b"}
You can see I'm outputting the getState() which is coming back as 'created' which would normally be fine for updating in everything I can find but it is still failing.
Does anyone else have experience with the PayPal PHP SDK and could help point me in the right direction?
In PayPal, once the user has approved the payment from the consent screen, the amount cannot be changed, as you can understand the user agreed to pay only the amount he/she saw on the consent screen. Modifying the amount after user approves it, is not allowed, and that's why you are seeing that state exception, as the state is already approved.
Anyway, looking at your scenario, I think you might be interested in either creating order, or capture, instead of sale.
Also, in our PayPal-PHP-SDK, there are a lot of interesting documents that could help you understand PHP-SDK better. We also provide a lot of runnable samples, that you could setup in your local machine, by one command only.
I am trying to create a paypal payment page, but for some reason when I try to add a custom web profile to the payment the option of checking out as a guest suddenly disappears.
First I am creating the web profile this way:
$flowConfig = new FlowConfig();
$flowConfig
->setLandingPageType("billing")
->setBankTxnPendingUrl("...");
$presentation = new Presentation();
$presentation
->setLogoImage("...")
->setBrandName("...")
->setLocaleCode("...");
$inputFields = new InputFields();
$inputFields
->setNoShipping(1)
->setAddressOverride(0);
$webProfile = new WebProfile();
$webProfile->setName("PROFILE" . uniqid())
->setFlowConfig($flowConfig)
->setPresentation($presentation)
->setInputFields($inputFields);
$request = clone $webProfile;
try {
$createProfileResponse = $webProfile->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
...
}
$profileId = $createProfileResponse->getId();
Then, I have updated the payment code in this way
$paypalPayment = new PayPalPayment();
$paypalPayment->setIntent("sale");
$paypalPayment->setPayer($payer);
$paypalPayment->setRedirectUrls($redirectUrls);
$paypalPayment->setTransactions(array($transaction));
$paypalPayment->setExperienceProfileId($profileId);
The weird thing is that if I comment the last line I can perform payments as a guest without any issue. If, instead, I leave it this way, I get the customized page but the "Check out as a guest" button is replaced by "Create an account".
Do I really have to choose between having a customized checkout page and the possibility to perform payments without creating paypal accounts? Or am I missing something? I didn't find anything related to this issue in the documentation nor here in stackoverflow, and it seems at least strange!
Thank you
Are you using Express Checkout? It looks like recurring payments without a PayPal account are only compatible with Website Payments Pro accounts.
You can still create recurring payments with EC but they will need a PayPal account to accept them, no guest checkout allowed by the looks of it.
https://www.paypal-community.com/t5/Merchant-services-Archive/How-to-accept-recurring-payments-from-buyers-who-don-t-have-a/td-p/178232
Banging my head for the last two days but unable to achieve this. Help!!
Whenever a shipment email is communicated I want to trigger a code which will send a SMS to the customer informing him/her that his order has been dispatched and also communicate the tracking number.
The code will be something like this:
<?php
$url = "http://www.abcde.in/binapi/pushsms.php?usr=xyz&pwd=abc&sndr=MEGYTR&ph=8888829554&text=This is test. MegaYtr&rpt=1";
$result = file_get_contents($url);
?>
Questions:
1) From where do I run this code?
2) How do I get additional info like Order Number, Customer Name, Grand Total & Tracking Number. I had done something similar for sending SMS when customer places order at that I used this code:
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_details = Mage::getModel('sales/order')->loadByIncrementId($order_id);
$shipping_address_data = $order_details->getShippingAddress();
$first_name = $shipping_address_data['firstname'];
$telephone = $shipping_address_data['telephone'];
$amount_paid = $order_details->total_paid;
$message = 'Dear '.$first_name.' thank you for shopping at abc.com. Your order'.$this->getOrderId().' amounting to Rs.'.$amount_paid.'is being processed.';
echo '<b>'.$message.' Please check your email for further details.</b>';
I am using Magento Community 1.7.0.1.
try this
i would like to give you an simple solution without need of modifying core files.
for that you need to create an observer for SuccessAction below is the event that will trigger your code when an order is successfull
checkout_onepage_controller_success_action
this will help you in creating observer for the above event create observer using this
one more thing i would like to add is in the controller at location Mage/Checkout/OnepageController search for successAction, this is the Action which is processed on the succes of order. Here on line 240 if you comment $session->clear(); than you would not require to place order again and again, just by refreshing the page you can check your changes.
And lastly FYI above event will dispatch orderId by using that you can load the order object, for doing that the below is the code
//load order object
$_order = Mage::getModel('sales/order')->loadByIncrementId($order_id_from_observer);
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!