how to apple pay through stripe in VJs? - vue.js

I am trying to follow the guide here ( https://stripe.com/docs/stripe-js/elements/payment-request-button ) to setup Apple Pay for the web and Stripe. The initial steps such as verification of domain and all the pre-setup is done but I am having an issue following the steps for the payment.
The Apple Pay Button is showing up in my Safari browser. When the button is clicked, I fire an event called Paymentmethode() i am facing this error while checking live.Either you do not have a card saved to your Wallet or the current domain (pwafe.devco.pk) is not registered for Apple Pay. Visit https://dashboard.stripe.com/account/apple_pay to register this domain.
main.js:25. and button is hide I get lost after step 3 and not sure what to do. I am posting to my backend and on the backend, creating a payment intent and returning the client_secret
paymentMethod() {
// STEP 1 FROM GUIDE
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
// STEP 2 FROM GUIDE
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestPayerName: true,
requestPayerEmail: true,
});
// STEP 3 FROM GUIDE
var elements = stripe.elements();
var prButton = elements.create("paymentRequestButton", {
paymentRequest: paymentRequest,
});
// console.log("before api call", paymentRequest);
paymentRequest.canMakePayment().then(function (result) {
// console.log("after api called" + result);
if (result) {
prButton.mount("#payment-request-button");
} else {
//prButton.mount('#payment-request-button');
document.getElementById("payment-request-button").style.display =
"none";
}
});
// STEP 4 FROM GUIDE -- THIS RETURNS A CLIENT SECRET
let clientSecret;
axios
.post("https://pwa.devco.pk/api/Create_PaymentIntent", {})
.then((resp) => {
// Assign this previously defined variable
clientSecret = resp.client_secret;
});
paymentRequest.on("paymentmethod", function (ev) {
// Confirm the PaymentIntent without handling potential next actions (yet).
stripe
.confirmCardPayment(
clientSecret,
{
payment_method: ev.paymentMethod.id,
},
{
handleActions: false,
}
)
.then(function (confirmResult) {
if (confirmResult.error) {
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
ev.complete("fail");
} else {
// Report to the browser that the confirmation was successful, prompting
// it to close the browser payment method collection interface.
ev.complete("success");
// Check if the PaymentIntent requires any actions and if so let Stripe.js
// handle the flow. If using an API version older than "2019-02-11" instead
// instead check for: `paymentIntent.status === "requires_source_action"`.
if (confirmResult.paymentIntent.status === "requires_action") {
// Let Stripe.js handle the rest of the payment flow.
stripe.confirmCardPayment(clientSecret).then(function (result) {
if (result.error) {
let data = {
msg: "An error occurred. Please try again.",
};
this.handleShowFlashMsg(data);
// The payment failed -- ask your customer for a new payment method.
} else {
this.handleShowOrderConfirmModal();
// The payment has succeeded.
}
});
} else {
// The payment has succeeded.
}
}
});
});
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestShipping: true,
// `shippingOptions` is optional at this point:
shippingOptions: [
// The first shipping option in this list appears as the default
// option in the browser payment interface.
{
id: "free-shipping",
label: "Free shipping",
detail: "Arrives in 5 to 7 days",
amount: 0,
},
],
});
paymentRequest.on("shippingaddresschange", function (ev) {
if (ev.shippingAddress.country !== "US") {
ev.updateWith({
status: "invalid_shipping_address",
});
} else {
// Perform server-side request to fetch shipping options
fetch("/calculateShipping", {
data: JSON.stringify({
shippingAddress: ev.shippingAddress,
}),
})
.then(function (response) {
return response.json();
})
.then(function (result) {
ev.updateWith({
status: "success",
shippingOptions: result.supportedShippingOptions,
});
});
}
});
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
},

You should verify domain registration and add card into wallet.tha

Related

React Blitz.js 3rd party auth failing with passport-azure-ad

I'm attempting to swap the default auth scheme in Blitz.js with a passport-azure-ad scheme, using the OIDCStrategy. I'm getting an error that I'm not sure about and would appreciate any help! I've created a new file under src/pages/auth/openid.tsx and into inserted the following code:
import { passportAuth } from "#blitzjs/auth"
import { api } from "src/blitz-server"
import { OIDCStrategy } from "passport-azure-ad"
const users: Array<{ oid: string }> = []
var findByOid = function (oid, fn) {
console.log("failing")
for (var i = 0, len = users.length; i < len; i++) {
const user = users[i]
console.log("we are using user: ", user)
if (user && user.oid === oid) {
return fn(null, user)
}
}
return fn(null, null)
}
export default api(
passportAuth({
successRedirectUrl: "/",
errorRedirectUrl: "/",
strategies: [
{
strategy: new OIDCStrategy(
{
identityMetadata:
"https://login.microsoftonline.com/<tenant-nam>.onmicrosoft.com/v2.0/.well-known/openid-configuration",
clientID: <client-id>,
responseType: "code id_token",
responseMode: "form_post",
redirectUrl: "http://localhost:3000/auth/openid/callback",
allowHttpForRedirectUrl: true,
clientSecret: "<client-secret>",
validateIssuer: false,
passReqToCallback: true,
scope: ["profile", "offline_access", "https://graph.microsoft.com/mail.read"],
loggingLevel: "info",
nonceMaxAmount: 5,
useCookieInsteadOfSession: false,
cookieEncryptionKeys: [
{ key: "12345678901234567890123456789012", iv: "123456789012" },
{ key: "abcdefghijklmnopqrstuvwxyzabcdef", iv: "abcdefghijkl" },
],
},
function (iss, sub, profile, accessToken, refreshToken, done) {
if (!profile.oid) {
return done(new Error("No oid found"), null)
}
// asynchronous verification, for effect...
process.nextTick(function () {
findByOid(profile.oid, function (err, user) {
if (err) {
return done(err)
}
if (!user) {
// "Auto-registration"
users.push(profile)
return done(null, profile)
}
return done(null, user)
})
})
}
),
},
],
})
)
I believe the configuration is good because I can run the example from passport-azure-ad from the github examples. The only change I make is that I set redirectUrl: "http://localhost:3000/auth/openid/callback", instead of redirectUrl: ".../return", per the blitz.js third party auth documentation. The tenantname, client_id, client_secret are redacted but I do set them to the correct values. I have also verified that the app registration is correctly set with the correct redirect uri.
I run blitz dev and when I go to the http://localhost:3000/auth/openid route I get the following error.
Here is the console output that is produced:
As you can see there is a Module not found: Can't resolve './src/build', this error only occurs if I go to the auth/openid page but the app is able to load.

Why does the 1st middleware of the array needs to call next() but the 2nd does not?

I am new in web development. While following the Node Express Mozilla Tutorial, I came accross this array of controller middlewares that made me confused regarding the use of next().
This array has 3 middlewares:
One for making sure a certain form parameter is in array format
One for doing validation and sintizaiton of the for parameters
One for processing and giving a response to the request
My doubt is: why does the 1st one calls next() but the 2nd does not?
Below the block of code with the array of controller middlewares:
// Handle book create on POST.
exports.book_create_post = [
// Convert the genre to an array.
(req, res, next) => {
if(!(req.body.genre instanceof Array)){
if(typeof req.body.genre ==='undefined')
req.body.genre = [];
else
req.body.genre = new Array(req.body.genre);
}
next();
},
// Validate and sanitise fields.
body('title', 'Title must not be empty.').trim().isLength({ min: 1 }).escape(),
body('author', 'Author must not be empty.').trim().isLength({ min: 1 }).escape(),
body('summary', 'Summary must not be empty.').trim().isLength({ min: 1 }).escape(),
body('isbn', 'ISBN must not be empty').trim().isLength({ min: 1 }).escape(),
body('genre.*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
// Create a Book object with escaped and trimmed data.
var book = new Book(
{ title: req.body.title,
author: req.body.author,
summary: req.body.summary,
isbn: req.body.isbn,
genre: req.body.genre
});
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
// Get all authors and genres for form.
async.parallel({
authors: function(callback) {
Author.find(callback);
},
genres: function(callback) {
Genre.find(callback);
},
}, function(err, results) {
if (err) { return next(err); }
// Mark our selected genres as checked.
for (let i = 0; i < results.genres.length; i++) {
if (book.genre.indexOf(results.genres[i]._id) > -1) {
results.genres[i].checked='true';
}
}
res.render('book_form', { title: 'Create Book',authors:results.authors, genres:results.genres, book: book, errors: errors.array() });
});
return;
}
else {
// Data from form is valid. Save book.
book.save(function (err) {
if (err) { return next(err); }
//successful - redirect to new book record.
res.redirect(book.url);
});
}
}
];

"You must provide card details, token or paymentMethodId " error when calling confirmPayment function in stripe

I am using stripe in expo app, when calling confirmPayment method it gives error "You must provide card details, token or paymentMethodId " , here is my code
const handlePayPress = async () => {
//1.Gather the customer's billing information (e.g., email)
if (!cardDetails?.complete || !email) {
Alert.alert("Please enter Complete card details and Email");
return;
}
const billingDetails = {
email: email,
};
//2.Fetch the intent client secret from the backend
try {
const { clientSecret, error } = await fetchPaymentIntentClientSecret();
//2. confirm the payment
if (error) {
console.log("Unable to process payment");
} else {
const { paymentIntent, error } = await confirmPayment(clientSecret, {
type: "Card",
billingDetails: billingDetails,
});
if (error) {
alert(`Payment Confirmation Error ${error.message}`);
} else if (paymentIntent) {
alert("Payment Successful");
console.log("Payment successful ", paymentIntent);
}
}
} catch (e) {
console.log(e);
}
//3.Confirm the payment with the card details
};
You need to integrate either the Payment Sheet or the CardField to collect the payment details for the payment. Unlike the web/Stripe.js versions of this, the reference is not needed explicitly during the confirm call, but you do still need to have them in your app.

How to add selling plan in graphql checkout shopify

I'm new to use Shopify graphql APIs. I create checkout using the below code. My Checkout working fine.
Now I want to add a product with a subscription plan.
I'm getting all plan data and id of the subscription plan added on product data. On the Shopify backend, we use the rechargepayments.com app that is installed in over admin. This is supported by JQuery and an over website subscription working fine.
const query = `
mutation {
checkoutCreate(input: {
lineItems: [{ variantId: "${item.variantId}", quantity: 1, customAttributes: {key: "Shipping Styles", value: "Mixed"} }]
}) {
checkout {
id
webUrl
lineItems(first: 5) {
edges {
node {
title
quantity
}
}
}
}
}
}`
axios({
url: `https://mystore.myshopify.com/api/2021-07/graphql.json`,
method: 'POST',
body: query,
onSuccess: (data) => {
onSuccess({ value: 'Checkout item added' })
},
onFailure: (err) => {
console.log('updateCheckout err ', err);
onFailure({ value: 'fail' })
},
});
Please help me how can I add a selling plan or a subscription using graphql from the mobile application.

Anonymous meeting join - Skype UCWA for online

I am trying to join a meeting anonymously through a meeting URI and this does not seem to work. I went to the SKYPE UCWA site and went to the interactive SDK - and tried to join a meeting anonymously from there but the page does not do anything.
https://ucwa.skype.com/websdk
Below is the code that I am trying to join a meeting anonymously, but the call to client.signInManager.signIn never completes and neither any exception is thrown.
Looking for suggestions to resolve this issue. Also, if someone has working code of joining a meeting anonymously using SKYPE web sdk (UCWA), please share the same. Thanks.
function InitialiseSkype() {
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebAppCtor = api.application;
window.skypeWebApp = new api.application();
client = new window.skypeWebAppCtor;
//once intialised, sign in
alert("Skype SDK Initialized");
JoinAnonymous();
}, function (err) {
console.log(err);
alert('Cannot load the SDK.');
});
}
function JoinAnonymous(){
client.signInManager.signIn({
version: config.Version,
name: $('#name').val(),
meeting: $('#meetingUri').val()
}).then(function () {
alert('Signed In, Anonymously');
var conversation = application.conversationsManager.getConversationByUri(uri);
}, function (error) {
alert(error);
});
}
Actually I did sign in anonymously using that code :
//Init
var config = {apiKey: 'a42fcebd-5b43-4b89-a065-74450fb91255', // SDK
apiKeyCC: '9c967f6b-a846-4df2-b43d-5167e47d81e1' // SDK+UI
};
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebApp = new api.application;
}, function (err) {
console.log("cannot load the sdk package", err);
});
//Actual code
var uri ="sip:xxxxxxxx;gruu;opaque=app:conf:focus:id:xxxxxxxx";
window.skypeWebApp.signInManager.signIn({
name: "pseudo",
meeting:uri
}).then(function () {
alert('Signed In, Anonymously');
}, function (error) {
alert(error);
});
I did connect with the uri given in the ucwa.skype interactive web sdk page.
But I did not manage to join the conversation after that, probably because the interactive sample does not really create the room.
I can join a meeting from a office365 account while logged in with a sample account. However I can not join anonymously my meeting room.
Do you try with an on-premise account or with a office365 account ?
Looks like Anonymous join for a meeting is not yet available for Skype For Business online.
New update of WebSDK now support anonymous meeting join for SfB Online
(function () {
'use strict';
// this will be populated when the auth token is fetched
// it is later needed to sign into Skype for Business
var authDetails = {};
// A reference to the Skype SDK application object
// set during initialization
var app;
displayStep(0);
registerUIListeners();
// Initializing the Skype application
Skype.initialize({
apiKey: '9c967f6b-a846-4df2-b43d-5167e47d81e1'
}, function (api) {
console.log('Skype SDK initialization successful');
app = api.UIApplicationInstance;
// Once it is initialized, display a UI prompt for a meeting URL
displayStep(1);
}, function (err) {
console.error('Skype SDK initialization error:', err);
});
// After the user submits the meeting URL the next step is to
// fetch an auth token
function getToken(evt) {
var input = evt.target.querySelector('input'),
meetingUrl = input.value,
request = new XMLHttpRequest(),
data;
evt.preventDefault();
console.log('Fetching auth token from meeting url:', meetingUrl);
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
var sessionId = guid();
data = 'ApplicationSessionId=' + sessionId +
'&AllowedOrigins=' + encodeURIComponent(window.location.href) +
'&MeetingUrl=' + encodeURIComponent(meetingUrl);
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
authDetails.discoverUrl = response.DiscoverUri;
authDetails.authToken = "Bearer " + response.Token;
console.log('Successfully fetched the anonymous auth token and discoverUrl', authDetails);
displayStep(2);
}
else {
console.error('An error occured, fetching the anonymous auth token', request.responseText);
}
}
};
request.open('post', 'http://webrtctest.cloudapp.net/getAnonTokenJob');
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
// This uses the auth token and discovery URL to sign into Skype
// and join the meeting
function joinAVMeeting(evt) {
var input = evt.target.querySelector('input'),
name = input.value;
evt.preventDefault();
console.log('Joinig meeting as:', name);
app.signInManager.signIn({
name: name,
cors: true,
root: { user: authDetails.discoverUrl },
auth: function (req, send) {
// Send token with all requests except for the GET /discover
if (req.url != authDetails.discoverUrl)
req.headers['Authorization'] = authDetails.authToken;
return send(req);
}
}).then(function () {
// When joining a conference anonymously, the SDK automatically creates
// a conversation object to represent the conference being joined
var conversation = app.conversationsManager.conversations(0);
console.log('Successfully signed in with anonymous online meeting token');
registerAppListeners(conversation);
// This turns on local video and joins the meeting
startVideoService(conversation);
}).catch(function (error) {
console.error('Unable to join conference anonymously:', error);
});
function registerAppListeners(conversation) {
conversation.selfParticipant.video.state.when('Connected', function () {
console.log('Showing self video');
document.querySelector('.self').style.display = 'inline-block';
setupContainer(conversation.selfParticipant.video.channels(0), document.querySelector('.self .video'));
displayName(document.querySelector('.self'), conversation.selfParticipant);
console.log('The video mode of the application is:', conversation.videoService.videoMode());
if (conversation.videoService.videoMode() === 'MultiView') {
// Loading the sample in any other browser than Google Chrome means that
// the videoMode is set to 'MultiView'
// Please refer to https://msdn.microsoft.com/en-us/skype/websdk/docs/ptvideogroup
// on an example on how to implement group video.
}
// When in active speaker mode only one remote channel is available.
// To display videos of multiple remote parties the video in this one channel
// is switched out automatically, depending on who is currently speaking
if (conversation.videoService.videoMode() === 'ActiveSpeaker') {
var activeSpeaker = conversation.videoService.activeSpeaker;
setupContainer(activeSpeaker.channel, document.querySelector('.remote .video'));
activeSpeaker.channel.isVideoOn.when(true, function () {
document.querySelector('.remote').style.display = 'inline-block';
activeSpeaker.channel.isStarted(true);
console.log('ActiveSpeaker video is available and has been turned on.');
});
activeSpeaker.channel.isVideoOn.when(false, function () {
document.querySelector('.remote').style.display = 'none';
activeSpeaker.channel.isStarted(false);
console.log('ActiveSpeaker video is not available anymore and has been turned off.');
});
// the .participant object changes when the active speaker changes
activeSpeaker.participant.changed(function (newValue, reason, oldValue) {
console.log('The ActiveSpeaker has changed. Old ActiveSpeaker:', oldValue && oldValue.displayName(), 'New ActiveSpeaker:', newValue && newValue.displayName());
if (newValue) {
displayName(document.querySelector('.remote'), newValue);
}
});
}
});
conversation.state.changed(function (newValue, reason, oldValue) {
if (newValue === 'Disconnected' && (oldValue === 'Connected' || oldValue === 'Connecting')) {
console.log('The conversation has ended.');
reset();
}
});
}
function setupContainer(videoChannel, videoDiv) {
videoChannel.stream.source.sink.format('Stretch');
videoChannel.stream.source.sink.container(videoDiv);
}
function displayName(container, person) {
container.querySelector('.displayName .detail').innerHTML = person.displayName();
}
function startVideoService(conversation) {
conversation.videoService.start().then(null, function (error) {
console.error('An error occured joining the conversation:', error);
});
displayStep(3);
}
}
function endConversation(evt) {
var conversation = app.conversationsManager.conversations(0);
evt.preventDefault();
conversation.leave().then(function () {
console.log('The conversation has ended.');
reset();
}, function (error) {
console.error('An error occured ending the conversation:', error);
}).then(function () {
reset();
});
}
//-----------------------------------------------------------------------
//UI helper functions
function displayStep(step) {
var nodes = document.querySelectorAll('.step');
for (var i = 0; i < nodes.length; ++i) {
var node = nodes[i];
node.style.display = 'none';
if (i === step) {
node.style.display = 'block';
}
}
}
function registerUIListeners() {
document.querySelector('.step1').onsubmit = getToken;
document.querySelector('.step2').onsubmit = joinAVMeeting;
document.querySelector('.step3').onsubmit = endConversation;
}
function reset() {
window.location = window.location.href;
}
})();
https://github.com/OfficeDev/skype-docs/blob/master/Skype/WebSDK/samples/Meetings/Anonymous%20Online/standalone/index.js