Omnipay, paypal REST with laravel 5 - php

The response i keep getting at dd($finalResponse); is:
RestResponse {#298 ▼
#statusCode: 400
#request: RestCompletePurchaseRequest {#300 ▶}
#data: array:4 [▼
"name" => "PAYMENT_NOT_APPROVED_FOR_EXECUTION"
"message" => "Payer has not approved payment"
"information_link" => "https://developer.paypal.com/webapps/developer/docs/api/#PAYMENT_NOT_APPROVED_FOR_EXECUTION"
"debug_id" => "5471589613718"
]
}
Here is the code.
$gateway = Omnipay::create('PayPal_Rest');
// Initialise the gateway
$gateway->initialize(array(
'clientId' => env('PAYMENT_SANDBOX_PAYPAL_CLIENTID'),
'secret' => env('PAYMENT_SANDBOX_PAYPAL_SECRET'),
'testMode' => true, // Or false when you are ready for live transactions
));
// Do an authorisation transaction on the gateway
$transaction = $gateway->authorize(array(
'returnUrl'=> env('PAYMENT_SANDBOX_PAYPAL_URL'),
'cancelUrl' => 'http://localhost:8000/cancel',
'amount' => '10.00',
'currency' => 'AUD',
'description' => 'This is a test authorize transaction.',
// 'card' => $card,
));
$response = $transaction->send();
if ($response->isSuccessful()) {
// Find the authorization ID
$authResponse = $response->getTransactionReference();
echo "Authorize transaction was successful!\n".$authResponse;
}else{
echo "Failed to auth transaction";
dd($response);
}
// Once the transaction has been approved, we need to complete it.
$transaction = $gateway->completePurchase(array(
'payerId' => $request->PayerID,
'transactionReference' => $authResponse
));
$finalResponse = $transaction->send();
dd($finalResponse);
if ($finalResponse->getData()) {
echo "Transaction was successful!\n";
// Find the authorization ID
$results = $finalResponse->getTransactionReference();
dd($results);
}else{
dd($finalResponse->getData());
}
After logging in as the payer and completing purchase, what else does the payer need to approve and how?

No, you aren't understanding the PayPal payment flow correctly. Here is the correct flow:
You do the call to Omnipay::create(), $gateway->initialize() and $gateway->authorize() just like you have them above. However for returnUrl you have to provide a URL on your site, just like you have for cancelUrl. Perhaps you mean to use http://localhost:8000/return (although better would be to have a transaction ID or something in the return URL).
The response from the $gateway->authorize() will be of type RedirectResponse. You can check this:
// Do an authorisation transaction on the gateway
$transaction = $gateway->authorize(array(
'returnUrl'=> env('PAYMENT_SANDBOX_PAYPAL_URL'),
'cancelUrl' => 'http://localhost:8000/cancel',
'amount' => '10.00',
'currency' => 'AUD',
'description' => 'This is a test authorize transaction.',
// 'card' => $card,
));
$response = $transaction->send();
if ($response->isRedirect()) {
// Yes it's a redirect. Redirect the customer to this URL:
$redirectUrl = $response->getRedirectUrl();
}
At that point the initial handshake with the customer is over. You have now redirected the customer to the PayPal web site where they will authorize the transaction by logging in with their PayPal account email address and password, check the invoice, click the button that says that they agree to pay.
The next thing that happens is that the customer is redirected by PayPal back to your web site, on the redirectUrl that you provided in the authorize() call. That will jump to a different place in your code. At that point you call completeAuthorize, just like you had in your code earlier:
// Once the transaction has been approved, we need to complete it.
$transaction = $gateway->completePurchase(array(
'payerId' => $request->PayerID,
'transactionReference' => $authResponse
));
$finalResponse = $transaction->send();
dd($finalResponse);
if ($finalResponse->getData()) {
echo "Transaction was successful!\n";
// Find the authorization ID
$results = $finalResponse->getTransactionReference();
dd($results);
}else{
dd($finalResponse->getData());
}
Note that you need to have stored the Payer ID and transactionReference from the authorize call and be able to recover those in your returnUrl code.
You also need to be able to handle the cancelUrl case, where the customer has decided not to agree to the payment on PayPal and gets sent back to the cancelUrl URL on your website instead.
Finally you need to be able to handle the occasional cases where the customer completes the payment on the PayPal web site but does not end back on your returnUrl. This could be because of a network issue, the browser crashed, or because the customer closed their browser between clicking "Agree to Pay" on PayPal and landing back on your site. The best way to handle those is with the omnipay-paypal calls fetchPurchase() or listPurchase().

Related

why the payment passes even I put code expired_card, without giving exception?

I tried to make the payment online for my site, I work with stripe, the payment is done with success, but I add CardErrorException to handle special error messages, when I put the code 4000 0000 0000 0069 to handle the expired_card exception it normal pass without handling the "You card has expired" exception.
CheckoutController.php
public function store(Request $request)
{
$contents = Cart::content()->map(function ($item) {
return $item->model->name.', '.$item->qty;
})->values()->toJson();
try {
// Enter Your Stripe Secret
\Stripe\Stripe::setApiKey('sk_test_PcRh9XreG5jbXyhCchJf9NCK00dku1xYGi');
$payment_intent = \Stripe\PaymentIntent::create([
'amount' => round(Cart::total() / 100),
'currency' => 'MAD',
'description' => 'Stripe Test Payment ddd',
'receipt_email' => $request->email,
'payment_method_types' => ['card'],
'metadata' => [
'content' => $contents,
'quantity' => Cart::instance('default')->count(),
]
]);
$intent = $payment_intent->client_secret;
Cart::instance('default')->destroy();
return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
} catch (CardErrorException $e) {
return back()->withErrors('Error! ' . $e->getMessage());
}
}
Your code is successfully creating a Payment Intent, but you're not confirming it. Payment is not attempted until the Payment Intent gets confirmed.
The special test card number you're using that returns an expired_card decline does not trigger until payment is attempted. That's why this code is not working as expected.
You likely want to add 'confirm' => 'true' to your arguments (assuming you want to confirm the Payment Intent server-side) or use Stripe.js to confirm the Payment Intent client-side (recommended).

Notify frontend Vue SPA if Stripe (iDEAL) charge is succeeded with Webhooks and Jobs Laravel

So I'm building an webapp that has a shop with Laravel API and Vue as the frontend SPA.
I've been trying to use Strip to enable payments. So far, with the help of Stripe's documentation, I have been able to create a Source in the frontend. for iDEAL, Stripe highly suggests us to make use of webhooks to confirm whether a payment has succeeded. (I'm using Spatie/Laravel-Stripe-Webhook package) This is the current flow of my webapp:
Checkout.vue:
checkout() {
const sourceData = {
type: 'ideal',
amount: this.cart.total,
currency: 'eur',
owner: {
name: this.name + ' ' + this.last_name,
email: this.email,
},
metadata: {
order: JSON.stringify(order),
total_quantity: this.cart.total_quantity,
},
redirect: {
return_url: 'http://example.test/order-confirmation',
},
}
this.stripe.createSource(this.ideal, sourceData).then(function(result) {
if (result.error) {
console.log(error.message)
this.error = error.message
} else {
stripeSourceHandler(result.source)
}
})
const stripeSourceHandler = source => {
document.location.href = source.redirect.url
}
},
After filling in billing address, emails etc. the user starts the payment.
User gets redirected to iDEAL payment page where they can authorize payment.
The Source is now created. Stripe sends source.chargeable webhook:
config/stripe-webhooks.php:
'jobs' => [
'source_chargeable' => \App\Jobs\StripeWebhooks\ProcessPaymentsJob::class,
'charge_succeeded' => \App\Jobs\StripeWebhooks\ChargeSucceededJob::class,
],
ProcessPaymentsJob.php:
public function __construct(WebhookCall $webhookCall)
{
$this->webhookCall = $webhookCall;
}
public function handle()
{
$charge = $this->webhookCall->payload['data']['object'];
\Stripe\Stripe::setApiKey(config('services.stripe.secret'));
$user = '';
if(User::find(Auth::id())) {
$user = $user->name;
} else {
$user = 'a guest';
}
$payment = \Stripe\Charge::create([
'amount' => $charge['amount'],
'currency' => 'eur',
'source' => $charge['id'],
'description' => 'New payment from '. $user,
'metadata' => [
'order' => $charge['metadata']['order'],
'total_quantity' => $charge['metadata']['total_quantity'],
]
]);
}
User returns to redirect[return_url]
If all went well, Stripe should send charge.succeeded webhook:
ChargeSucceededJob.php:
public function __construct(WebhookCall $webhookCall)
{
$this->webhookCall = $webhookCall;
}
public function handle()
{
$charge = $this->webhookCall->payload['data']['object'];
$order = Order::create([
'user_id' => Auth::id() ?? null,
'payment_id' => $charge['id'],
'payment_method' => $charge['payment_method_details']['type'],
'billing_email' => $charge['billing_details']['email'],
'billing_name' => $charge['metadata']['name'],
'billing_last_name' => $charge['metadata']['last_name'],
'billing_address' => $charge['metadata']['address'],
'billing_address_number' => $charge['metadata']['address_num'],
'billing_postal_code' => $charge['metadata']['postal_code'],
'billing_city' => $charge['metadata']['city'],
'billing_phone' => strval($charge['billing_details']['phone']),
'order' => json_decode($charge['metadata']['order']),
'total_quantity' => (int) $charge['metadata']['total_quantity'],
'billing_total' => $charge['amount'],
]);
}
This is all going well. However, I do not know how to notify the customer (on the frontend) that the order has been completed. In Stripe's documentation, they explain how to retrieve the Source on the order confirmation page, but they do not explain how to retrieve the Charge, because this is what determines whether the whole order has been completed or not.
OrderConfirmation.vue:
checkPaymentStatus() {
this.stripe = Stripe(this.stripeKey)
// After some amount of time, we should stop trying to resolve the order synchronously:
const MAX_POLL_COUNT = 10;
let pollCount = 0;
let params = new URLSearchParams(location.search)
const pollForSourceStatus = async () => {
const { source } = await this.stripe.retrieveSource({id: params.get('source'), client_secret: params.get('client_secret')})
if (source.status === 'chargeable') {
// Make a request to your server to charge the Source.
// Depending on the Charge status, show your customer the relevant message.
} else if (source.status === 'pending' && pollCount < MAX_POLL_COUNT) {
// Try again in a second, if the Source is still `pending`:
pollCount += 1;
setTimeout(pollForSourceStatus, 1000);
} else {
// Depending on the Source status, show your customer the relevant message.
}
};
pollForSourceStatus();
}
How do I go from here? I am trying to notify the frontend when the Charge has been succeeded. My initial thought process was just to return the Order object, as I would do if it was a Controller, but if I understand correctly, the Job is running asynchronously, so I can't return data. I am also new to Jobs and Queues and stuff, I'm still trying to wrap my head around with it.
Another option I thought of is that I would poll requests from the frontend to the backend to request the last Order, but I have no idea how this would work and/or if this is a good solution.
Any help/tips/helpful resources would be much appreciated!
iDEAL payments are asynchronous, but they luckily do immediately notify you if the payment was successful or not.
When the iDEAL process is complete and your user is redirected to your site, Stripe automatically appends some query parameters to the URL. Meaning your users will be redirected to something like:
https://example.com/checkout/complete?payment_intent=pi_123&payment_intent_client_secret=pi_123_secret_456&source_type=ideal
The next step is to then retrieve the PaymentIntent and check on its status, which you can do by either:
Retrieving the PaymentIntent on the client using stripe.js and the PaymentIntent client secret: https://stripe.com/docs/js/payment_intents/retrieve_payment_intent
Retrieving the PaymentIntent on the server by sending an ajax request to your backend with the PaymentIntend ID: https://stripe.com/docs/api/payment_intents/retrieve
If the status is succeeded, then the payment was completed and you can proceed from there.

Braintree Drop-In (cards & paypal) + subscriptions (PHP). Problem with paymentMethodNonce

I have been able to create a test check-out (js+php) in my server using the Braintree drop-in method. I need to create subscriptions for my customers accepting paypal or credit cards. The checkout (client-side) form is working and I POST it to a php page where I get the form data and create the Customer, plan, etc.
However, I have problems when creating the subscription. I get the Cannot use a paymentMethodNonce more than once or similar errors.
This is what I do:
checkout form (drop-in) submits data to subscription.php?payload_nonce=tokencc_bc_s27k55_c7pcq8_8mvd43_xxcvvf_9p5
braintree.dropin.create({
authorization: 'sandbox_6vqkmmsy_fs5432wttyb8qpzf',
container: '#dropin-container',
locale: 'es_ES',
paypal: {
flow: 'vault'
}
}, function (createErr, instance) {
button.addEventListener('click', function () {
instance.requestPaymentMethod(function (err, payload) {
// Submit payload.nonce to your server
url = 'subscription.html?payload_nonce=' + payload.nonce;
window.location.replace(url);
});
});
});
Then in the destination page I create the Customer...
$payload_nonce = $_GET['payload_nonce'];
$result = Braintree_Customer::create(array(
'firstName' => $name,
'email' => $email,
'company' => $company
));
...his payment method...
$resultPM = Braintree_PaymentMethod::create([
'customerId' => $customerId,
'paymentMethodNonce' => $payload_nonce
]);
...and finally the subscription...
$subscriptionData = array(
'paymentMethodNonce' => $payload_nonce,
'planId' => $billingplan
);
$result = Braintree_Subscription::create($subscriptionData);
I have tried to add the paymentMethodNonce when creating the Customer, or when creating the paymentMethod, etc. with same results.
If the payment method is "credit card" I can get the mayment method token like this:
'paymentMethodToken' => $result->customer->creditCards[0]->token
But if it is PayPal there is no creditcards[0]. Which is the correct method to achieve what I need?
Thanks!

Stripe : The default source of the customer is a source and cannot be shared from existing customers

I am trying to use Stripe Connect on my website. I created connected account and customers but have a mistake while trying to share a customer to the connected account.
I get this :
"You provided a customer without specifying a source. The default source of the customer is a source and cannot be shared from existing customers."
Hier is the code I am using :
function addSource($source){
$this->source = $source;
}
function addCustomer(){
$customer = \Stripe\Customer::create(array(
"description" => "Customer ".$this->getCustomerName(),
"email" => $this->getCustomerEmail(),
"source" => $this->source
));
$this->customer = $customer;
}
function createAccount(){
$account = \Stripe\Account::create(array(
"country" => "FR",
"type" => "custom"
));
$this->account = $account->id;
}
function connectCustomer(){
$token = \Stripe\Token::create(array(
"customer" => $this->customer->id
), array("stripe_account" => $this->account));
$copiedCustomer = \Stripe\Customer::create(array(
"description" => "Customer for xxx#xxx.com",
"source" => $token->id
), array("stripe_account" => $this->account));
$this->copiedCustomer = $copiedCustomer;
}
By debugging I saw that the problem happend when I try to create $token in the connectCustomer function. The customer is well added on my Stripe Dashboard with a correct source. The account is also created.
My goal after that is to subscribe the customer to the connected account. I have succeed to subscribe him without using Stripe Connect but now I need to use it.
I tried to find a solution in many other forum but did not find anything similar.
Thanks for any help !
I know it's already too late, but here is something worked for me. I have had the same error. I have solved it by creating source instead of token.
So, replace
$token = \Stripe\Token::create(array(
"customer" => $this->customer->id
), array("stripe_account" => $this->account));
with
$token = \Stripe\Source::create([
"customer" => $this->customer->id,
], ["stripe_account" => $this->account]);
Your code looks fine to me. I'm not sure why it did not work. Maybe some steps are missing? Ran into the same issue while creating connect subscription because I was trying to associate platform customer with connected plan. The error message was not very helpful. I search google with the message and came upon this question. C'mon, I was able to use the platform customer to create one-time connected charge fine (after I create a shared source). Why can't I do the same here? Because Subscription API required customer and not a shared source. Stripe demo code wasn't of much help until I carefully read the first 4 bulleted points in the documentation here: https://stripe.com/docs/connect/subscriptions (an Ahhhhah moment!)
Using subscriptions with Connect has these restrictions:
Both the customer and the plan must be created on the connected
account (not your platform account)
Subscriptions must be created directly on the connected account (using the destination parameter is not supported)
Your platform can’t update or cancel a subscription it did not create
Your platform can’t add an application_fee to an invoice that it didn’t create or that contains invoice items it didn’t create
So, I'm just going to post some pseudo code in hoping it will help the next person who came upon this question with above error message.
You have to create a source (not token) to be reuse from the front-end/client-side javascript:
stripe.createSource(card, ownerInfo)
Then you would use this source (stripe_token) to create a customer on the platform account (stripe_customer_id). This can be useful with one-time connected charge (if you have a need for it). This is also to store the original source (stripe_token) so you can create a new re-usable token/source later for the connected/txn_customer_id.
From step 3 on, all the codes are inside of chargeMonthly function below:
Make sure the subscription plan is a connected plan created by the platform by providing a unique name (3rd bullet point above).
Next, create a new re-useable source with the platform/stripe_customer_id.
Use the new re-usable source to create a customer (txn_customer_id) on the connected account.
Create your subscription with the connected/txn_customer_id and connected plan_id.
public function createNewCustomer(&$input, $forConnect = false) {
try {
// Create new stripe customer
if ($forConnect) {
$cu = \Stripe\Customer::create(array(
'email' => $input['email'],
'source' => $input['connect_token']
), array("stripe_account" => $input['txn_account_id']));
$input['txn_customer_id'] = $cu->id;
}
else {
$cu = \Stripe\Customer::create(array(
'email' => $input['email'],
'source' => $input['stripe_token']
));
$input['stripe_customer_id'] = $cu->id;
$input['txn_customer_id'] = $cu->id;
}
} catch (\Stripe\Error\Base $e1) {
// log error
\Log::error($e1);
return false;
} catch(\Stripe\Error\Card $e2) {
\Log::error($e2);
return false;
} catch (Exception $e) {
\Log::error($e);
return false;
}
return true;
}
public function chargeMonthly(&$input, $qty = 1) {
$plan_name = 'yourplatformname-' . $input['amount'] .'-' . $input['banner_slug'];
// attempt to retrieve monthly plan
// if not found, create new plan
try {
$plan = \Stripe\Plan::retrieve($plan_name, array("stripe_account" => $input['txn_account_id']));
} catch(\Stripe\Error\InvalidRequest $e1) {
// ignore error
// \Log::error($e1);
} catch(Exception $e) {
// ignore error
// \Log::error($e);
}
try {
// create new if not found
if(empty($plan)) {
$plan = \Stripe\Plan::create(array(
'amount' => $input['amount'],
'interval' => 'month',
'currency' => 'usd',
'id' => $plan_name,
"product" => array(
"name" => $plan_name
)
), array("stripe_account" => $input['txn_account_id']));
}
$token = \Stripe\Source::create(array(
'customer' => $input['stripe_customer_id'],
'usage' => 'reusable'
), array("stripe_account" => $input['txn_account_id']));
$input['connect_token'] = $token->id;
$this->createNewCustomer($input, true);
$sub = \Stripe\Subscription::create(array(
'customer' => $input['txn_customer_id'],
'plan' => $plan->id,
'quantity' => $qty,
'application_fee_percent' => $input['application_fee_percent']),
array('stripe_account' => $input['txn_account_id'])
);
$input['txn_id'] = $sub->id;
$input['txn_log'] = json_encode($sub);
$input['recurrence_name'] = $plan->id;
// success
return true;
} catch(\Stripe\Error\InvalidRequest $e1) {
// ignore error
\Log::error($e1);
return false;
} catch(Exception $e) {
\Log::error($e);
return false;
}
}

Response object - Payment with Mollie and Omnipay

I'm trying to create a payment with Omnipay and Mollie in my Laravel project. I'm using the following 2 libraries:
https://github.com/barryvdh/laravel-omnipay
https://github.com/thephpleague/omnipay-mollie
I'm doing the following in my code:
$gateway = Omnipay\Omnipay::create('Mollie');
$gateway->setApiKey('test_gSDS4xNA96AfNmmdwB3fAA47zS84KN');
$params = [
'amount' => $ticket_order['order_total'] + $ticket_order['organiser_booking_fee'],
'description' => 'Bestelling voor klant: ' . $request->get('order_email'),
'returnUrl' => URL::action('EventCheckoutController#fallback'),
];
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
session()->push('ticket_order_' . $event_id . '.transaction_id',
$response->getTransactionReference());
return $this->completeOrder($event_id);
}
The payment works. When the payment is done he goes back to the function fallback. But I don't know what to put in this function and how to go back to the line if($response->isSuccesfull()...).
The most important thing I need to do after the payment is :
session()->push('ticket_order_' . $event_id . '.transaction_id',
$response->getTransactionReference());
return $this->completeOrder($event_id);
Can someone help me figure out how to work with the fallback function and above?
A typical setup using Mollie consists of three separate pages:
a page to create the payment;
a page where Mollie posts the final payment state to in the background; and
a page where the consumer returns to after the payment.
The full flow is described in the Mollie docs. Also take a look at the flow diagram at that page.
DISCLAIMER: I've never used Omnipay myself and did not test the following code, but it should at least give you an idea how to set up your project.
Creating the payment:
$gateway = Omnipay\Omnipay::create('Mollie');
$gateway->setApiKey('test_gSDS4xNA96AfNmmdwB3fAA47zS84KN');
$params = [
'amount' => $ticket_order['order_total'] + $ticket_order['organiser_booking_fee'],
'description' => 'Bestelling voor klant: ' . $request->get('order_email'),
'notifyUrl' => '', // URL to the second script
'returnUrl' => '', // URL to the third script
];
$response = $gateway->purchase($params)->send();
if ($response->isRedirect()) {
// Store the Mollie transaction ID in your local database
store_in_database($response->getTransactionReference());
// Redirect to the Mollie payment screen
$response->redirect();
} else {
// Payment failed: display message to the customer
echo $response->getMessage();
}
Receiving the webhook:
$gateway = Omnipay\Omnipay::create('Mollie');
$gateway->setApiKey('test_gSDS4xNA96AfNmmdwB3fAA47zS84KN');
$params = [
'transactionReference' => $_POST['id'],
];
$response = $gateway->fetchTransaction($params);
if ($response->isPaid()) {
// Store in your local database that the transaction was paid successfully
} elseif ($response->isCancelled() || $response->isExpired()) {
// Store in your local database that the transaction has failed
}
Page where the consumer returns to:
// Check the payment status of your order in your database. If the payment was paid
// successfully, you can display an 'OK' message. If the payment has failed, you
// can show a 'try again' screen.
// Most of the time the webhook will be called before the consumer is returned. For
// some payment methods however the payment state is not known immediately. In
// these cases you can just show a 'payment is pending' screen.

Categories