Payment with Braintree retrieving data from vault - javascript

I first created a customer with the help of API, when a customer created successfully then it returned me customerId, with the help of customerId I created a credit card.
// for creating user
gateway->customer()->create([
'firstName' => $firstName,
'lastName' => $lastName,
'company' => $company,
'email' => $email,
'phone' => $phone,
'fax' => $fax,
'website' => $website
]);
//for creating card
$result = $this->gateway->creditCard()->create([
'customerId' => $customerId,
'number' => $number,
'expirationDate' => $expirationDate,
'cvv' => $cvv
After saving card in vault successfully it gives me a token In order to retrive data of card I did this:
$result = $this->gateway->creditCard()->find($token);
and it returned me the card detail, Now I want to perform payment with this card detail or token(as I am confused). previously I successfully done payment with drop in UI but I want to use vault this time

Full disclosure: I work at Braintree. If you have any further questions, feel free to contact
support.
Now that you have the payment method token, you can pass that value as a parameter to the Transaction Sale API Call in order to complete a transaction with the saved payment method as opposed to a payment method nonce, which represents a single use payment method.
Example
$result = $gateway->transaction()->sale(
[
'paymentMethodToken' => 'the_payment_method_token',
'amount' => '100.00'
]
);

Related

Paypal Checkout - Payment always on pending

Since three days i am trying to get the Paypal Checkout to work but i always have the problem that the order is created and the money in gone from the buying account but not reaching the payee account.
So here is my setup:
The Smart Buttons integeration in JavaScript:
paypal.Buttons({
env: enviroment,
// Set up the transaction
createOrder: function() {
let formData = new FormData();
formData.append('bookingId', bookingId);
return fetch (url_createOrder, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
return response.json()
})
.then(function(res) {
console.log(res);
return res.result.id;
});
},
// Finalize the transaction
onApprove: function(data, actions) {
console.log(data);
// This function captures the funds from the transaction.
return actions.order.capture().then(function(details) {
console.log(details);
// This function shows a transaction success message to your buyer
// window.location.href = 'danke.php';
});
}
}).render('#paypal-button-container');
As you can see the createOrder starts a AJAX call to this script:
[...]
$client = new PayPalHttpClient($environment);
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = self::buildRequestBody($price);
// 3. Call PayPal to set up a transaction
$response = $client->execute($request);
echo json_encode($response, JSON_PRETTY_PRINT);
// 4. Return a successful response to the client.
return $response;
}
private static function buildRequestBody($price) {
return array(
'intent' => 'CAPTURE',
'application_context' => array(
'brand_name' => 'Example',
'cancel_url' => 'http://localhost/example/abbruch.php',
'return_url' => 'http://localhost/example/danke.php'
),
'purchase_units' => array(
0 => array(
'reference_id' => 'example_addr',
'description' => 'example Address',
'amount' => array(
'currency_code' => 'EUR',
'value' => $price
)
)
)
);
[...]
Everything works so far to this point. I get a OrderId back which i return to the AJAX call and then i am am able to insert credentials and pay the given price.
When i finish the payment the onApprove of the smart buttons in the JS file get called back and i also get the correct response of that actions.order.capture():
{create_time: "2020-08-14T19:37:59Z", update_time: "2020-08-14T19:38:20Z", id: "6FP46164U47878440", intent: "CAPTURE", status: "COMPLETED", …}
create_time: "2020-08-14T19:37:59Z"
id: "6FP46164U47878440"
intent: "CAPTURE"
links: [{…}]
payer:
address:
country_code: "DE"
__proto__: Object
email_address: "sb-ughwh2901918#personal.example.com"
name: {given_name: "John", surname: "Doe"}
payer_id: "8Z5RM2ERW6VTL"
__proto__: Object
purchase_units: [{…}]
status: "COMPLETED"
update_time: "2020-08-14T19:38:20Z"
__proto__: Object
Afterwards the money is gone from the buyer account but it says "pending", here a screenshot (but in german)
payment_is_pending.png
On the seller account i can´t select anything like "approve". I found an example of the paypal checkout api which works similar and tried to copy it into my code but yeah... same story.
Then i thought maybe the problem is the seller sandbox account, but if i try it which an sandbox account created and given by a paypal tutorial is says pending as well.
Please, help!
The payments are pending because there is no sandbox account with the email sb-2xact2876961#business.example.com confirmed, so the payments are in an unclaimed state. Pending unclaimed payments will be automatically returned after 30 days if left unclaimed.
To claim the payments, the email sb-2xact2876961#business.example.com must be confirmed on a sandbox account, via https://www.sandbox.paypal.com/businessprofile/settings/email and https://developer.paypal.com/developer/notifications/

how to properly use Stripe api for saved card on client side

I am currently working with Stripe API. I was able to use one time payment properly, and save credit card correctly as well as process;
However, I was stuck on the 3D secure(2nd auth) for saved card on client side. I had search out the website with no success. And the official doc https://stripe.com/docs/payments/save-and-reuse#web-create-payment-intent-off-session seems with little information about using saved card on client side. Or probably I just don't understand it. Hopefully someone can guide me out with correct practice.
Below it's the critical part of codes, it currently works with one time payment and 2nd auth stripe pop out.
NOTE: I was able to create a charge based on the information from each individual card from $saved_cards in my server, however it would not trig the 3d secure hence it will always failed with cards that requires 2nd authentication
backend.php
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$intent = \Stripe\PaymentIntent::create([
'amount' => $payment * 100,
'currency' => 'usd',
]);
if (!empty(Auth::user()->stripe_id)) { //all saved card info
$saved_cards = \Stripe\PaymentMethod::all([
'customer' => Auth::user()->stripe_id,
'type' => 'card',
]);
}
return view('cart.preview', $items)->with('saved_cards', $saved_cards)->with('client_secret', $intent->client_secret);
Client.js
// this is for one time payment
var payment_method = {
card: card,
billing_details: {
name: "name"
}
};
stripe.confirmCardPayment( "{{ $client_secret }}", {
payment_method: payment_method, // <= I believe this is the place I can use the saved card?
}).then(function (result) {
if (result.error) {
// Show error to your customer (e.g., insufficient funds)
console.log(result.error.message);
} else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
// Show a success message to your customer
// There's a risk of the customer closing the window before callback
// execution. Set up a webhook or plugin to listen for the
// payment_intent.succeeded event that handles any business critical
// post-payment actions.
}
}
});
/*****************************************************************************/
Update for solution based on answer suggestion:
Disclaimer: this might be a bad practice since the secret switch happens on the frontend side. But you get the idea.
In order to use your payment_method id, you also have to attach your customer id, which happens in the backend side. So for my case I created another savedCard_intent in my backend and pass it to frontend for handle the saved card specifically.
$savedCard_intent = \Stripe\PaymentIntent::create([
'customer' => Auth::user()->stripe_id,
'amount' => $payment * 100,
'currency' => 'usd',
]);
pass it to frontend with('saved_secret' ,$savedCard_intent->client_secret);
Combine all of them together I have code like the following:
newBackend.php
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$new_intent = \Stripe\PaymentIntent::create([
'amount' => $payment * 100,
'currency' => 'usd',
]);
$savedCard_intent = \Stripe\PaymentIntent::create([
'customer' => Auth::user()->stripe_id,
'amount' => $payment * 100,
'currency' => 'usd',
]);
if (!empty(Auth::user()->stripe_id)) { //all saved card info
$saved_cards = \Stripe\PaymentMethod::all([
'customer' => Auth::user()->stripe_id,
'type' => 'card',
]);
}
return view('cart.preview', $items)->with('saved_cards', $saved_cards)->with('new_secret', $new_intent->client_secret)->with('saved_secret', $savedCard_intent->client_secret);
newClient.js
// this is for one time payment
var payment_method = {
card: card,
billing_details: {
name: "name"
}
};
var secret = (Some conditions here) ? "{{$new_secret}}" : "{{$saved_secret}}";
stripe.confirmCardPayment( secret, {
payment_method: (Some conditions here) ? payment_method : saved_payment_method.id,
}).then(function (result) {
if (result.error) {
// Show error to your customer (e.g., insufficient funds)
console.log(result.error.message);
} else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
// Show a success message to your customer
}
}
});
You are correct. You would use the PaymentMethod's id (pm_******) like so:
stripe.confirmCardPayment( "{{ $client_secret }}", {
payment_method: payment_method.id,
}). then( ... )
Documented here: https://stripe.com/docs/js/payment_intents/confirm_card_payment#stripe_confirm_card_payment-data-payment_method
You can also pass a PaymentMethod object if you're generating one on the client side, but that's not likely the approach you're looking for.

Laravel 6.0 Stripe: Must provide source or customer

I'm trying to process a credit card payment and I get this error: Must provide source or customer.
I'm not sure what Stripe means by this and I've tried the solution posted here: Stripe: Must provide source or customer
public function store(Request $request)
{
try {
$charge = Stripe::charges()->create([
// 'amount' => getNumbers()->get('newTotal') / 100,
'currency' => 'UK',
'source' => $request->stripeToken,
'description' => 'Thank you for your purchase.',
'receipt_email' => $request->email,
'customer' => $request->email,
'metadata' => [
// 'contents' => $contents,
'quantity' => Cart::count(),
],
]);
Cart::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());
}
}
As you can see, I do have a source and a customer. If I change the $customer property to equal something like 'person', Stripe will return this: No such customer: person
What exactly am I doing wrong here?
EDIT: The library I'm using is cartalyst/stripe-laravel: https://github.com/cartalyst/stripe-laravel
Thanks

How to use instafeed.js to get logged in users images

I'm building an application where users can click a button to show all of their Instagram images on a page, but in order to do that I need userId and accessToken. How do I get these?
NOTE: If it makes any difference: I'm not trying to get just my own images, but anyone who uses my app to log into their account.
I have this code:
<script>
var feed = new Instafeed ({
get: "user",
userId: ,
accessToken: ""
});
feed.run();
</script>
<div id="instafeed"></div>
And I get a verification code by clicking on a link (note I removed cliend_id and redirect_uri):
Get Instagram images
Then this returns a code like '1251251...' which I grab with GET, but after that what do I do? How do I get userId and accesToken from this?
I'm not sure if I'm on the right track, but any help would be appreciated!
Answering my own question, as I figured it out:
$url = 'https://api.instagram.com/oauth/access_token';
$data = array(
'client_id' => $clientId,
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri,
'code' => $code
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$clientId, $clientSecret and $redirectUri are taken from: https://instagram.com/developer/clients/manage/
$code is the code from your url and $result contains the userId and accessToken if successful.
Thanks to: How do I send a POST request with PHP?

Posting a link with image and text to Facebook wall

I am trying to replicate the functionality to share a story on a Facebook wall similar to what this site has.
When you click on the share it should ask you to authenticate to facebook, if you are already authenticated it should show you the story to post to facebook.
I got the authentication part to work using the JavaScript SDK . I am not sure how to show the content to post to the wall.
Could anyone please provide an example.
Thanks!
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try{
$uid = $facebook->getUser();
# let's check if the user has granted access to posting in the wall
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $uid,
'ext_perm' => 'publish_stream'
);
$can_post = $facebook->api($api_call);
if($can_post){
# post it!
# $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));
# using all the arguments
$facebook->api('/'.$uid.'/feed', 'post', array(
'message' => 'The message',
'name' => 'The name',
'description' => 'The description',
'caption' => 'The caption',
'picture' => 'http://i.imgur.com/yx3q2.png',
'link' => 'http://net.tutsplus.com/'
));
echo 'Posted!';
} else {
die('Permissions required!');
}
} catch (Exception $e){}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
?>
http://developers.facebook.com/docs/reference/api/post/

Categories

Resources