I'm trying to integrate a payment system on my Laravel 6 project.
But I Have no idea how to retrieve the ClientSecret from my serverside
I have this in my CheckOutController
public function charge(Request $request)
{
Stripe::setApiKey('sk_test_GEQCwhRyT9PcK1vju3YcsIEN00gXSsjo1P');
$intent = PaymentIntent::create([
'amount' => round(Cart::total()),
'currency' => 'eur',
]);
echo json_encode($intent);
}
And I should retrieve information and work with this (from Stripe documentation)
submitButton.addEventListener('click', function(ev) {
stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card,
billing_details: {
name: 'Jenny Rosen'
}
}
}).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.
}
}
});
});
Thank you for reading me :)
The client secret that you are looking for is returned by Stripe as client_secret.
So you can get that value with:
Arr::get($intent, 'client_secret');
You can have a look at the example response from the docs here: https://stripe.com/docs/api/payment_intents/create
Related
Firebase messaging error in https server.
An error occurred while retrieving token. FirebaseError: Messaging: The notification permission was not granted and blocked instead. (messaging/permission-blocked).
What should I do to get my token?
On localhost, it's working.
Here is my code:
firebase-messaging-sw.js
// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts("https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js")
importScripts("https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js")
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: apiKey,
authDomain: authDomain,
databaseURL: databaseURL,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId,
appId: appId,
measurementId: measurementId
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
/**
* Here is is the code snippet to initialize Firebase Messaging in the Service
* Worker when your app is not hosted on Firebase Hosting.
// [START initialize_firebase_in_sw]
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': 'YOUR-SENDER-ID'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
// [END initialize_firebase_in_sw]
**/
// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
// [END background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
footer.blade.php
in //script// section:
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: apiKey,
authDomain: authDomain,
databaseURL: databaseURL,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId,
appId: appId,
measurementId: measurementId
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const tokenDivId = 'token_div';
const permissionDivId = 'permission_div';
const messaging = firebase.messaging();
messaging.usePublicVapidKey('BKotWNDl7JOuYb-UeusSlSl47onAFH9sWJ_M1WDivsjWq0AZWah5LjVfBAxbcS8T8Yo10HEw_xPX68kMnzTQC2k');
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(() => {
messaging.getToken().then((refreshedToken) => {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
setTokenSentToServer(false);
// Send Instance ID token to app server.
sendTokenToServer(refreshedToken);
// ...
}).catch((err) => {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
function resetUI() {
clearMessages();
showToken('loading...');
// [START get_token]
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
// [END get_token]
}
function showToken(currentToken) {
// Show token in console and UI.
var tokenElement = document.querySelector('#token');
tokenElement.textContent = currentToken;
}
// Send the Instance ID token your application server, so that it can:
// - send messages back to this app
// - subscribe/unsubscribe the token from topics
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...');
// TODO(developer): Send the current token to your server.
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') === '1';
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}
function showHideDiv(divId, show) {
const div = document.querySelector('#' + divId);
}
function requestPermission() {
console.log('Requesting permission...');
// [START request_permission]
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// [START_EXCLUDE]
// In many cases once an app has been granted notification permission, it
// should update its UI reflecting this.
resetUI();
// [END_EXCLUDE]
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
// [END request_permission]
}
function deleteToken() {
// Delete Instance ID token.
// [START delete_token]
messaging.getToken().then(function(currentToken) {
messaging.deleteToken(currentToken).then(function() {
console.log('Token deleted.');
setTokenSentToServer(false);
// [START_EXCLUDE]
// Once token is deleted update UI.
resetUI();
// [END_EXCLUDE]
}).catch(function(err) {
console.log('Unable to delete token. ', err);
});
// [END delete_token]
}).catch(function(err) {
console.log('Error retrieving Instance ID token. ', err);
showToken('Error retrieving Instance ID token. ', err);
});
}
// Add a message to the messages element.
function appendMessage(payload) {
const messagesElement = document.querySelector('#messages');
const dataHeaderELement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style = 'overflow-x:hidden;';
dataHeaderELement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderELement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages');
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild);
}
}
function updateUIForPushEnabled(currentToken) {
showHideDiv(tokenDivId, true);
showHideDiv(permissionDivId, false);
showToken(currentToken);
}
function updateUIForPushPermissionRequired() {
showHideDiv(tokenDivId, false);
showHideDiv(permissionDivId, true);
}
This indicates that you have blocked the push notifications permission on the deployed website. It's messaging.getToken() that is likely erroring out (see the docs for more).
If you're using Chrome, you should be able to click the lock to the left of the URL and go to "Site Settings" where you'll see a bell icon with the notification settings for the site:
This may be set to "Block" and you would need to change it to "Allow" instead.
Make sure you're not in an incognito tab - in that case the permissions dialog (Allow/Block) won't show up (in Chrome at least)
So I am using google functions to write a script to auto pay my workers! In my back end i have stored the public token and account id.. I am trying to use plaid to turn into a stripe token then use stripe to do the transfer! The stripe thing is working but the plaid functions wont return the new stripe bank account number.. any ideas?
plaidClient.exchangePublicToken("public-sandbox-6be57fb5-3286-4bc8-a770-54a16ea39283",
res => {
var accessToken = res.access_token;
// debugging = exchangedata.access_token;
//debugging = err.message;
// Generate a bank account token
plaidClient.createStripeToken(accessToken, snapshot.val().plaid_account_id,
res => {
bankAccountToken = res.stripe_bank_account_token;
stripe.transfers.create({
amount: (Number(appointmentchildSnapshot.val().price)/3).toString(),
currency: "usd",
destination:bankAccountToken,
transfer_group: "ORDER_95"
},(_err, transfer)=> {
// asynchronously called
});
});
Make you use double " " when declaring your client secret and stuff!
In order to test for errors use res.json(Error:responsetowhatfunction you are using)
-- Some bank tokens do not work with Plaid unfortunately in sandbox and they also expire pretty quickly so if its not working create a new token and try again
---With the error log stuff you can keep track of when this happens
await plaidClient.exchangePublicToken(snapshot.val().plaid_token,
async (error,response1) => {
if (error !== null) {
res.json({error:snapshot.val().plaid_token});
} else {
var accessToken = response1.access_token;
//res.json(accessToken);
// debugging = exchangedata.access_token;
//debugging = err.message;
// Generate a bank account token
debugging = await plaidClient.createStripeToken(accessToken, snapshot.val().plaid_account_id,
async (error2,response2) => {
if(error2!==null){
res.json({error:snapshot.val().plaid_account_id});
}else{
//res.json({error:response2});
// bankAccountToken = response2.stripe_bank_account_token;
stripe.transfers.create({
amount: (Number(appointmentchildSnapshot.val().price)/3).toString(),
currency: "usd",
destination:response2.stripe_bank_account_token,
transfer_group: "ORDER_95"
},(_err, transfer)=> {
// asynchronously called
});
}
it's some days that i am trying to solve a paypal issue. I'm working with the PayPal PHP SDK, my envoirment is a Linux Server (Ubuntu 16) with Php 7.2 installed and running Laravel 5.6.
I installed through composer the paypal php sdk and i integrated 'successfuly' in the code. When i try to run the code, i get back the link for make the payment (usually where u redirect the user) so it's working fine, no problem about the first request or api credential.
The problem is that, if you go to the pay link and i made the payment, it will redirect the payer to the success page of my website but i am not getting any transaction in my account (the buyer and the reciver) and also i am not getting any webhook or IPN notify (also like, user have to money or user profile is not verified, just nothing).
What i already tryed:
switching on live api and try with real paypal profile, but i got the same issue. So this is not the problem. (on paypal sdk github someone has a problem on sandbox).
Using a Laravel Packege (same issue).
This is my code (but i don't think the problem is this one):
$_api_context = new ApiContext(new OAuthTokenCredential(
'CLIENT_ID','SECRET'));
$_api_context->setConfig(array(
'mode' => env('PAYPAL_MODE', 'sandbox'),
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'DEBUG'
));
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item_1 = new Item();
$item_1->setName('Item 1') /** item name **/
->setCurrency('USD')
->setQuantity(1)
->setPrice('3'); /** unit price **/
$item_list = new ItemList();
$item_list->setItems(array($item_1));
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal('3');
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Your transaction description');
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl('https://XXXXXXX.ngrok.io/success') /** Specify return URL **/
->setCancelUrl('https://XXXXX.ngrok.io/error');
$payment = new Payment();
$payment->setIntent('Sale')
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
//dd($payment);
try {
$payment->create($_api_context);
} catch (\PayPal\Exception\PPConnectionException $ex) {
dd($ex);
}
foreach ($payment->getLinks() as $link) {
if ($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
$approvalUrl = $payment->getApprovalLink();
dd($redirect_url,$_api_context,$paypal,$paymentGateway,$approvalUrl,$payment->getId());
UPDATE
I tryed to sent money form sandbox account (personal) to the business account that own the api, and the ipn is working correctly.
For anyone that will have the same problem, u should execute the payment after the user is redirected to your success page.
I did not find where you set post request send your server to save your transactions.
Try like this way ..
code..
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '{{$form_data->net_amount}}'
}
}]
});
},
onApprove: function(data, actions) {
console.log('data');
console.log(data);
return actions.order.capture().then(function(details) {
console.log(details);
alert('Transaction completed by ' + details.payer.name.given_name);
// Call your server to save the transaction
return fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
userDetail: details,
bookingId: '{{$form_data->id}}',
_token: '{{csrf_token()}}'
})
}).then(function(){
location.reload();
});
});
}
}).render('#paypal-button-container');
</script>
I've updated a webhook URL in my database, but when I try to spawn an event in Laravel Tinker that should post a message to a slack channel, it's using the "old" testing URL and not the new URL from the database.
Each store has a one-to-many relationship to a slack integration.
>>> foreach ($store->slackIntegrations as $integration) { print $integration->webhook_url; }
https://hooks.slack.com/services/T0K572A2W/B8R8MPMV2/XXXX
When an invite event is spawned, with the id of the store_invite a notification should be posted to the configured slack channel.
>>> $e = new \App\Events\InviteEvent(179605);
=> App\Events\InviteEvent {#1005
+body: 179605,
+socket: null,
}
>>> event($e);
GuzzleHttp\Exception\ClientException with message
'Client error: `POST
https://hooks.slack.com/services/T0K572A2W/B30D7AV52/XyzXyz`
resulted in a `404 Not Found` response: No service'
/**
The above endpoint URL is invalid and no longer set in the database.
*/
The event logic is as follows.
public function handle(InviteEvent $event)
{
// This fetches the ids in the event body.
$ids = $this->getIds($event);
$store_invites = Invite::with(['store' => function ($q) {
$q->withoutGlobalScopes();
}])->find($ids);
$invites_to_slack = $store_invites->filter(function ($invite) {
return $invite->shouldSlack();
});
$invites_to_slack->each(function ($invite) {
$invite->sendToSlack();
});
}
This was an issue with me not having updated the same Database as the project .env file was referring to.
I'm using YouTube's V3 Data API to add a subscription to a channel. This occurs on a Wordpress installation.
I added Google APIs (for oauth) on Wordpress theme functions:
wp_enqueue_script( 'googleapi', 'https://apis.google.com/js/client.js?onload=googleApiClientReady', array(), '1.0.0', true );
I added in the same way the oauth javascript file, which is the first one here: https://developers.google.com/youtube/v3/code_samples/javascript.
Following this guide(https://developers.google.com/youtube/v3/docs/subscriptions/insert (Apps Script)), I extended the OAuth js with the addSubscription method.
Google Client API seems to be loaded and working as it calls correctly googleApiClientReady on the oauth javascript.
So, this is how the subscription is being inserted:
OAUTH JAVASCRIPT
... ... ...
// After the API loads
function handleAPILoaded() {
addSubscription();
}
function addSubscription() {
// Replace this channel ID with the channel ID you want to subscribe to
var channelId = 'this is filled with the channel ID';
var resource = {
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelId
}
}
};
try {
var response = YouTube.Subscriptions.insert(resource, 'snippet');
jQuery('#success').show();
} catch (e) {
if(e.message.match('subscriptionDuplicate')) {
jQuery('#success').show();
} else {
jQuery('#fail').show();
alert("Please send us a mail () with the following: ERROR: " + e.message);
}
}
So, the first error comes with
YouTube.Subscriptions.insert(resource, 'snippet')
It says YouTube is not defined. I replaced it with:
gapi.client.youtube.subscriptions.insert(resource, 'snippet');
And that error went away. When checking response, as the subscription isn't completed, this is what I get
{"wc":1,"hg":{"Ph":null,"hg":{"path":"/youtube/v3/subscriptions","method":"POST","params":{},"headers":{},"body":"snippet","root":"https://www.googleapis.com"},"wc":"auto"}}
So, I would like to know what's happening on that POST request and what's the solution to this.
I can post the full OAuth file, but it's just as in the example, plus that addSubscription method at the end.
Okay, I got it working, the problem was on the POST request. Here is the full method working:
// Subscribes the authorized user to the channel specified
function addSubscription(channelSub) {
var resource = {
part: 'id,snippet',
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelSub
}
}
};
var request = gapi.client.youtube.subscriptions.insert(resource);
request.execute(function (response) {
var result = response.result;
if (result) {
// alert("Subscription completed");
}
} else {
// alert("Subscripion failed");
// ...
}
});
}
Also make sure to load Google Apps API (in fact without it the authorize/login button won't work) and jQuery.
Any chance you can post everything that made this work...all the JS entire auth.js save for your private keys, im working on this exact problem.