I am trying to create a subscription i Paymill. Ive read through their examples but i do not seem to get it.
All i really want to do is to setup a subscription, here is my current code:
$token = $_POST['paymillToken'];
if ($token) {
require "Services/Paymill/Payments.php";
require "Services/Paymill/Transactions.php";
require "Services/Paymill/Subscriptions.php";
require "Services/Paymill/Offers.php";
$params = array(
'amount' => '49900', // Cent!
'currency' => 'SEK', // ISO 4217
'token' => $token,
'description' => 'User ID# ' . $userIdMain . ' Email: ' . $userEmail
);
$transactionsObject = new Services_Paymill_Transactions(
PAYMILL_API_KEY, PAYMILL_API_HOST
);
$transaction = $transactionsObject->create($params);
echo "<br /><br />";
print_r($transaction);
echo $transaction['client']['id'];
echo $transaction['payment']['id'];
$params = array(
'client' => $transaction['client']['id'],
'offer' => 'offer_9cdffb501f565bf827a8',
'payment' => $transaction['payment']['id']
);
$subscriptionsObject = new Services_Paymill_Subscriptions(PAYMILL_API_KEY, PAYMILL_API_HOST);
$subscription = $subscriptionsObject->create($params);
echo "<br /><br />";
print_r($subscription);
}
The problem is that the above create two payments at once. But it seems like the subscription object requires me to first have a payment_id (see $transaction['payment']['id'] above).
What am i doing wrong here?
Creating a subscription will also create a transaction, which is correct. Add a Payment Object ( https://www.paymill.com/en-gb/documentation-3/reference/api-reference/#create-new-credit-card-payment-with ) instead of creating a new transaction and pass the id to the Subscription->create().
OK it's not PHP but I had the same kind of uncertainty following the right steps to set up a subscription. In the end it's kind of easy, so I am posting my code so far in case it helps.
The app is MVC .net and I am using the PayMill PayButton to generate a payment token. This is part of the model during the registration process. The following code calls the .net wrapper of the PayMill API.
private static async Task<Subscription> MakePayMillSubscription(int amount, ApplicationUser user, PaymillContext paymillContext, Payment payment, Client client)
{
SubscriptionService subscriptionService = paymillContext.SubscriptionService;
Subscription subscription = await subscriptionService.CreateAsync( payment, client, null, amount, "EUR", Interval.periodWithChargeDay(1, Interval.TypeUnit.MONTH), null, user.Id, Interval.period(10, Interval.TypeUnit.YEAR));
return subscription;
}
private static async Task<Client> MakePayMillClient(RegisterViewModel model, ApplicationUser user, PaymillContext paymillContext)
{
ClientService clientService = paymillContext.ClientService;
Client client = await clientService.CreateWithEmailAndDescriptionAsync(
model.Email,
user.Id
);
return client;
}
private static async Task<Payment> MakePayMillPayment(RegisterViewModel model,PaymillContext context, Client client)
{
Payment payment = await context.PaymentService.CreateWithTokenAndClientAsync(model.paymillToken, client);
return payment;
}
Then I call these during registration like this at the moment (I am still in a testing phase)
client = await MakePayMillClient(model, user, paymillContext);
payment = await MakePayMillPayment(model, paymillContext,client);
subscription = await MakePayMillSubscription((int)(account.TotalAmountDue * 100.0M), user, paymillContext, payment, client);
Related
i have integrated coinbase api in my web app. When charge is created, users are directed to coinbase commerce website to make payment. How do i check if the user has finished paying or not and if the exact amount has been paid. Below is my code
<?php
require_once __DIR__ . "/vendor/autoload.php";
use CoinbaseCommerce\ApiClient;
use CoinbaseCommerce\Resources\Charge;
/**
* Init ApiClient with your Api Key
* Your Api Keys are available in the Coinbase Commerce Dashboard.
* Make sure you don't store your API Key in your source code!
*/
ApiClient::init("MY API KEY HERE");
$chargeObj = new Charge();
$chargeObj->name = 'Bitcoin Deposit';
$chargeObj->description = 'Testing the payment system';
$chargeObj->local_price = [
'amount' => '100.00',
'currency' => 'USD'
];
$chargeObj->pricing_type = 'fixed_price';
try {
$chargeObj->save();
// insert into database with status pending
$queryobject->insertTransaction($_SESSION['user_id'],$chargeObj->id, $amount, $status, $currentTime,
$chargeObj->name, $chargeObj->currency);
} catch (\Exception $exception) {
echo sprintf("Sorry! payment could not be created. Error: %s \n", $exception->getMessage());
}
if ($chargeObj->id) {
$chargeObj->description = "New description";
// Retrieve charge by "id"
try {
$retrievedCharge = Charge::retrieve($chargeObj->id);
$hosted_url = $retrievedCharge->hosted_url;
header('location: '.$hosted_url);
} catch (\Exception $exception) {
echo sprintf("Enable to retrieve charge. Error: %s \n", $exception->getMessage());
}
}
You need to use webhooks for this, you can create an endpoint for this. Unfortunately Coinbase does not have a sandbox environment so you are going to need a bit of cryptocurrency in your account.
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.
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!
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.
I have stripe check out with php. It creates customers and charges them. I want to create a donation form where if same customer comes back and gives with same email address that Stripe doesn't create another customer but charges the existing customer with additional payments. Is this possible? Or does the checkout always create new customer with new customer id?
Here is my charge.php
<?php
require_once('config.php');
$token = $_POST['stripeToken'];
if($_POST) {
$error = NULL;
try{
if(!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
$customer = Stripe_Customer::create(array(
'card' => $token,
'email' => $_POST['stripeEmail'],
'description' => 'Thrive General Donor'
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $_POST['donationAmount'] * 100,
'currency' => 'usd'
));
}
catch(Exception $e) {
$eror = $e->getMessage();
}
}
?>
You will need to store the relationship between email address and Stripe customer ID in a database. I've determined this by looking at Stripe's API on Customers.
First, when creating a new customer every field is optional. This leads me to believe that every single time you POST to /v1/customers, it will "[create] a new customer object."
Also, when retrieving a customer the only field available is the id. This leads me to believe that you cannot retrieve a customer based on an email address or other field.
If you can't store this information in a database, you can always list all the customers with GET /v1/customers. This will require you to paginate through and check all customer objects until you find one with a matching email address. You can see how this would be quite inefficient if done every time you tried to create a customer.
You can list all users for a given email address.
https://stripe.com/docs/api#list_customers
In JavaScript you could do this:
const customerAlreadyExists = (email)=>{
return doGet(email)
.then(response => response.data.length > 0);
}
const doGet = (url: string)=>{
return fetch('https://api.stripe.com/v1/customers' + '?email=' + email, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + STRIPE_API_KEY
}
}).then(function (response) {
return response.json();
}).catch(function (error) {
console.error('Error:', error);
});
}