Cannot find name 'require'. ANGULAR 2 - javascript

I have an angular2 app where I need to use a payment API.
https://stripe.com/docs/quickstart
In this code sample on the nodejs section they say to use it like this:
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
var stripe = require("stripe")("sk_test_BQokikJOvBiI2HlWgH4olfQ2");
// Token is created using Stripe.js or Checkout!
// Get the payment token submitted by the form:
var token = request.body.stripeToken; // Using Express
// Charge the user's card:
var charge = stripe.charges.create({
amount: 1000,
currency: "usd",
description: "Example charge",
source: token,
}, function(err, charge) {
// asynchronously called
});
We installed requireJS with NPM, however when we run it we get this error:
Cannot find name 'require'.
L48: pagar() {
L49: var stripe = require("stripe")("sk_test_ayzCMDmjq2QOIW0s3dTihxNR");

Try this instead:
import * as stripe from "stripe";
public stripeKey = stripe("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

Related

why messaging().sendtodevice is not working sometimes?

I'm using the following code to send a notification from one device to another using FCM. Everything works fine until before return admin.messaging().sendToDevice(...). The 'Token ID: ' log displays token ID of the receiver, but when I set the variable token_id to the sendToDevice function, the notification is not called, therefore the notification is not sent. Can someone tell me what's wrong?
var firebase = require("firebase-admin");
var serviceAccount = require("./julla-tutorial.json");
console.log("enter in then Firebase Api");
const firebaseToken = [
'e0T6j1AiRjaa7IXweJniJq:APA91bHNznSHSIey08s-C-c3gchci6wepvhP1QxQyYbmZ8LySI3wnu64iW7Q23GhA6VCdc4yodZoCFOgynfAb5C8O8VE81OcSv_LL-K3ET1IKGZ_6h35n-_q5EKFtfJWlzOqZr4IvpiB',
'dNWnSqyCQbufzv1JutNEWr:APA91bFcI9FDyRxHRBEcdw4791X0e-V0k1FjXcSstUA67l94hSojMRCd6LWr2b57azNEt3z_XLwLljMX4u2mc9cZDrAVm55Mw9CHGyue-09KofWnnHNR9XWBibc4T76xOV_DWX7T2RvW',
'cq65rtuaTCKGk5lHk7UabN:APA91bFR3kAArg6lhuBq7ktNuBk7Z9MXXk3PskqhYa8CgNaEl6MX4TQ5lo35d6XhnCQ4fEkCkyZ_j08evxE9Y4oVCRTEdqsrkccCVTE8Di47lfmDR3i1NdoL3re9oLw6F_uNsnvRoQcq'
]
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount)
})
const payload = {
notification: {
title: 'Demo 2345',
body: 'dfghj',
sound: 'default',
color: 'yellow',
android_channel_id: 'default',
channel_id: 'default'
},
data: { id: 'broadcast', channelId: 'default' }
}
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24, // 1 day
};
console.log('------payload---',payload);
console.log('-----TOKEN_Array----',firebaseToken);
console.log('-------options-----',options);
firebase.messaging().sendToDevice(firebaseToken, payload, options).then(function (response) {
console.log('--------response',response);
}) .catch(function (error) {
console.log('-------rejet',reject);
});
It looks like you did not change the code from this tutorial:
https://medium.com/#jullainc/firebase-push-notifications-to-mobile-devices-using-nodejs-7d514e10dd4
you will need to change the 2nd line of code:
var serviceAccount = require("./julla-tutorial.json");
to actually point to your own firebase-push-admin.json file which holds your private keys registering your backend app with the firebase cloud messaging api. you can download this file from the firebase console as mentioned in the above article.
I recommend hiding this file from your git history by adding it to .gitignore so you dont accidentally push your private keys to a public repo.
I will link you another resource in addition to above link which helped me implement firebase push notifications in a nodeJS backend app.
https://izaanjahangir.medium.com/setting-schedule-push-notification-using-node-js-and-mongodb-95f73c00fc2e
https://github.com/izaanjahangir/schedule-push-notification-nodejs
Further I will also link you another repo where I am currently working on a fully functional firebase push notification implementation. Maybe it helps to actually see some example code.
https://gitlab.com/fiehra/plants-backend

How do I resolve WalletLoginError in web3auth?

I'm currently working on web3auth authentication, In their documentation most of the code is in typescript. But I'm using javascript in my Next.js project. I'm using core packages to build custom ui interface. But getting this wallet error when I tried to login using walletAdapters
This is my code for that
const web3AuthCoreCtorParams = {
clientId,
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget:
"https://rinkeby.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161", // This is the testnet RPC we have added, please pass on your own endpoint while creating an app
},
};
// creating new web3auth instance
const web3AuthInstance = new Web3AuthCore(web3AuthCoreCtorParams);
subscribeAuthEvents(web3AuthInstance);
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
clientId,
network: "testnet",
uxMode: "redirect",
},
});
web3AuthInstance.configureAdapter(openloginAdapter);
const web3authProvider = await web3AuthInstance.connectTo(
WALLET_ADAPTERS.OPENLOGIN,
{
relogin: true,
loginProvider: "discord",
}
);
setProvider(web3authProvider);
};
And the error I'm getting is
Unhandled Runtime Error
WalletLoginError: Failed to connect with walletFailed to login with openlogin
Call Stack
Function.fromCode
node_modules/#web3auth/base/dist/base.esm.js (315:0)
Function.connectionError
node_modules/#web3auth/base/dist/base.esm.js (320:0)
OpenloginAdapter.connect
node_modules/#web3auth/openlogin-adapter/dist/openloginAdapter.esm.js (141:12)
async Web3AuthCore.connectTo
node_modules/#web3auth/core/dist/core.esm.js (105:0)
I'm using version 1.0.0

Pass JWT to rabbitmq over websockets

This is my current RabbitMQ / Stomp setup which works fine with username and password authentication.
My end goal is to pass a JWT instead of username and password. I already have access to the token on the front-end and I do not want to conduct a UAA server. I have added this plugin to RabbitMQ and tried doing what step 3 of the Authorization flow says with no luck.
Client passes the token as password when connecting to a RabbitMQ
node. The username field is ignored.
I get the following error:
<<< ERROR
content-length:16
version:1.0,1.1,1.2
content-type:text/plain
message:Processing error
content-length:16
Edit
Another observation is that after adding "Authorization: Bearer" in front of the token I get the a new error.
<<< ERROR
content-length:33
version:1.0,1.1,1.2
content-type:text/plain
message:Bad CONNECT
content-length:33
Access refused for user 'rabbit'
RabbitMQ Setup
Docker
FROM rabbitmq
RUN rabbitmq-plugins enable --offline rabbitmq_management
RUN rabbitmq-plugins enable --offline rabbitmq_stomp
RUN rabbitmq-plugins enable --offline rabbitmq_web_stomp
RUN rabbitmq-plugins enable --offline rabbitmq_auth_backend_oauth2
COPY ./advanced.config /etc/rabbitmq/advanced.config
COPY ./rabbitmq.conf /etc/rabbitmq/rabbitmq.conf
EXPOSE 15671 15672 15674 61613
advanced.config
[
{rabbit, [
{default_user, <<"admin">>},
{default_pass, <<"guest">>},
{auth_backends, [rabbit_auth_backend_oauth2, rabbit_auth_backend_internal]}
]},
{rabbitmq_management, [
{enable_uaa, false}
]},
{rabbitmq_auth_backend_oauth2, [
{resource_server_id, <<"rabbitmq">>},
{key_config, [
{default_key, <<"key-1">>},
{signing_keys,
#{<<"key-1">> => {pem, <<"-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAr8xZBLjW7yMZJobc/IFo
6New9jlCvSx8I6aSBrU+EU+TN6iXF13Tqqp62L/TWlTrYlErsu2yvLknhN4VU7qX
g38/2wZn9/kKFYCkeaDe3lDxl+4rNGq1TSEXCzndIDfVzgxZvKZ0Vt5+mvr1cxR7
7V6MFcJvIHMv4MdIqAUwABFFHvonp56yzh7g/UsAk6XlaqhoZQ1NrPyWpG6YgHwg
hFibyh0ZI3gD7H0UshpR9VVPLTgrAUnf3qWMpEXKO2ePmrTVwwDpL25n5DdhaBz6
e+YSonTT7KigxeklRPrKc7km29l0frml+8jOsQsx7L2WCD/HqR6J5iVDZ5mDfeKN
vcixi+nkLTCyV1jsHEzteSmGgmAE6SrSMXV+oPz2xLGKEGJJQWS+Ll1l5BD1MmZE
6DqLoe8FHew54M7zniCxkhDIHcpVY3IYcv2gohhaxm9MHkSHaj6bwAGQcORwgGho
ETVr7RXyvCD5Vsr6VqDqknjleP1tLi/gnlzP099SLmGiB6y/v1mW1s3tDpI/F7b7
WWDyHRqW9YfGEPYOmNdELcizW9UxY2MFvK4LlacRaXzzDEXmiP/FK84Qse14Nmyi
6tfqIYe+PRWbA7ztOaBlmDnkhxHcLufB48t4dleUWmj+6VOXQGXef10p4rQNeOo5
N5dJoYqveUJ6Lfln3C25NJcCAwEAAQ==
-----END PUBLIC KEY-----">>}
}
}]
}
]}
].
rabbitmq.conf
loopback_users.guest = false
total_memory_available_override_value = 2684354560
listeners.tcp.default = 5672
management.tcp.port = 15672
web_stomp.ws_frame = binary
Current Stomp client setup
var client = new StompJs.Client({
brokerURL: 'ws://localhost:5900/ws',
connectHeaders: {
login: 'admin',
passcode: 'guest'
},
debug: log => (
console.log(
log
)
),
reconnectDelay: 5 * 1000,
heartbeatIncoming: 4 * 1000,
heartbeatOutgoing: 4 * 1000,
});
Ideal JWT setup
var client = new StompJs.Client({
brokerURL: 'ws://localhost:5900/ws',
connectHeaders: {
login: 'rabbit',
passcode: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc0FjdGl2ZSI6dHJ1ZSwiX2lkIjoiNWZkNzc0MDY4NzE3NTU2OWFlMTIxNmRmIiwiY29kZSI6IjIwMDAwMDEwNiIsInVzZXJuYW1lIjoiYW50b25pc2NvZGV1cCIsImVtYWlsIjoiYW50b25pc0Bjb2RldXAuc29mdHdhcmUiLCJmaXJzdE5hbWUiOiJBbnRvbmlzIiwibGFzdE5hbWUiOiJQaXNoaWFzIiwib3JnYW5pc2F0aW9uIjoiQ29kZVVwIFNvZnR3YXJlIEx0ZCIsInJvbGUiOnsiX2lkIjoiNWZkMmEyM2VjOTJmOTFjNTFkOTIzMTZiIiwibmFtZSI6ImN1c3RvbWVyIiwicmVhZCI6W3siX2lkIjoiNWZkMmEyM2VjOTJmOTFjNTFkOTIzMTViIiwibmFtZSI6ImFjY291bnRzIn0seyJfaWQiOiI1ZmQyYTIzZWM5MmY5MWM1MWQ5MjMxNWMiLCJuYW1lIjoiY3JtIn0seyJfaWQiOiI1ZmQyYTIzZWM5MmY5MWM1MWQ5MjMxNWQiLCJuYW1lIjoid2FyZWhvdXNlIn1dLCJjcmVhdGUiOltdLCJ1cGRhdGUiOltdLCJtb3ZlIjpbXSwiX192IjowfSwiX192Ijo3LCJzY29wZXMiOlsicmFiYml0bXEuY29uZmlndXJlOiovKiIsInJhYmJpdG1xLndyaXRlOiovKiIsInJhYmJpdG1xLnJlYWQ6Ki8qIl0sImlhdCI6MTYwNzk1NjkzNCwiZXhwIjoxNjA4NTYxNzM0LCJhdWQiOlsiaHR0cHM6Ly9iaXpjb3VyaWVyLmV1IiwicmFiYml0bXEiXSwiaXNzIjoiaHR0cHM6Ly9yZXN0LmJpemNvdXJpZXIuZXUifQ.Ypqa16YuqH3rfwxAQZ_RdJRF21h6jYX07r-zaB3AP_qshU_xBiP9RpFvFkws13i0_X3Ou-qKxSdAF51T1t-Ob5V4LiXLJKsesmZIeIGXs-Dhc79u5UqhOdGIzPgRTlieOIUmrFKsPBWf7FnoR-lgd9gH8ge3Wp2f2vOqU24JsEjkvtlTGLS1aId27UVz0d2qxMLWf-9kLxW4mmuM2UCeRsnznpPaZbAfhq2tHHIy3EtGeIIiOsAE0lM9BfJRF36kjZcpcMZSnhTrkZjiDsrUuiVd-W27MVJRYFVpULkGrpa5RkkDG5ZbwNNSn0VUMZB2PiQTchtNyoffutPzhktxieDO5T0OzrSXl5VAtgZFHi5oPLWtPGVejNiWMFsY9u1ale6NRDSReeQjPPEqzpH-tfnugkwyv_jhL6WnfmoeEBgcuyK7eBvrg7uJbQFdwMrRQXkGn_ATn0XhJWI-Hia3muNbNbvdL0jgkZBv0HFPsx84n3-IEx672_6Wy2qtLtFcnUgGr4ThRVp8PE0ro21JdvjFbwgq9k5Qhv5MA6wgB6nt7vtuP1SZ17ekIPE6izwHUPZsWsqJg6v108H1B13J2yxK5LcdsCb8Z8uRhiRSKt4Cs6MHsZg0GCOjym2YHXyN21Wpw3behq0GxUiSrU4qkADujDb6nNzaLq2_ecn5bOI'
},
debug: log => (
console.log(
log
)
),
reconnectDelay: 5 * 1000,
heartbeatIncoming: 4 * 1000,
heartbeatOutgoing: 4 * 1000,
});
You can decode the JWT here
I think that you are missing a scope in your JWT
See the documentation here:
https://github.com/rabbitmq/rabbitmq-server/tree/master/deps/rabbitmq_auth_backend_oauth2
It says:
Token scope returned by OAuth 2.0 provider must include RabbitMQ resource scopes that follow a convention used by this plugin: configure:%2F/foo means "configure permissions for 'foo' in vhost '/'") (scope field can be changed using extra_scopes_source in advanced.config file.
(BTW: I coudn't find the "extra_scopes_source" in your advanced.config as well)
Although I didn't test it, failing to provide the scope would logically result in an access denied error.

Stripe charge not going through

I'm using the Stripe API to test out charges and the charge is not going through. I tokenize the credit card then use the token as a "source" parameter. I did the exact same thing in Python and it worked fine, but when I tried using this with Node.js, it didn't work.
Here's my code:
var stripe = require("stripe")(<key>);
var pay = stripe.tokens.create({
card: {
number: '<number>', // note, for now I'm just using the stripe test credentials
exp_month: <exp>,
exp_year: <year>,
cvc: '<cvc>'
}
}, function(err, token) {
console.log(err); // null
console.log(token); // token information (works fine)
return token;
});
stripe.charges.create({
amount: 500,
currency: "usd",
source: pay,
description: "Test charge"
}, function(err, charge) {
console.log(err); // error message 400, missing parameter
console.log(charge); // still null
});
What am I doing wrong? As I said, when I did this using Python it worked fine.
Update: I've tried all solutions posted below and they all still return a error 400 code. If anyone has another solution it would be appreciated.
_____________________________________________________________________________
Update 2: For anyone looking for an answer, I figured it out and posted it below.
A few things:
stripe.tokens.create returns a Promise, not a value. You have to assign token to something in the right scope to use it elsewhere, or just pass it to a function that uses it:
stripe.tokens.create({
card: {
number: '<number>', // note, for now I'm just using the stripe test credentials
exp_month: <exp>,
exp_year: <year>,
cvc: '<cvc>'
}
}, function(err, token) {
console.log(err); // null
console.log(token); // token information (works fine)
// call a function which in turn calls stripe.charges.create
makeCharge(token);
});
You shouldn't be generating tokens on your backend, this subjects you to the widest scope of PCI compliance https://stripe.com/docs/security#validating-pci-compliance. Instead use Stripe Elements or legacy Checkout on your frontend to tokenize cards.
JavaScript is asynchronous rather than synchronous, look into using async/await if you want synchronous operations.
The create methods run asynchronously. If you want to use the token you just created, then you need to do so in the callback. To better understand this, check this code:
var stripe = require("stripe")(<key>);
var pay = stripe.tokens.create({
card: {
number: '<number>', // note, for now I'm just using the stripe test credentials
exp_month: <exp>,
exp_year: <year>,
cvc: '<cvc>'
}, function(err, token) {
console.log(err); // null
console.log(token); // token information (works fine)
return token;
});
console.log(pay); // This will not be what you expected.
pay is not going to be the value of token because the request hasn’t finished yet.
Instead, you need to create your charge inside the callback for the token. This callback function is executed once the web request for the token creation is finished.
var stripe = require("stripe")(<key>);
stripe.tokens.create({
card: {
number: '<number>', // note, for now I'm just using the stripe test credentials
exp_month: <exp>,
exp_year: <year>,
cvc: '<cvc>'
}, function(err, token) {
console.log(err); // null
console.log(token); // token information (works fine)
stripe.charges.create({
amount: 500,
currency: "usd",
source: token, // note I changed this to token
description: "Test charge"
}, function(err, charge) {
console.log(err); // hopefully null now
console.log(charge); // hopefully has charge info now
// add code to display a confirmation message or whatever you want to do with the successful charge here
});
});
Disclaimer: I’m not familiar with the Stripe code. I just understand how asynchronous JS works. Creating the token every time may or may not be best practice.
You can do one think just use the default source from the stripe customer id created by user.
return stripe.customers.retrieve(stripeCustomerId)
.then((customer) => customer.default_source)
You will get the customer default source if available and after that just create charge using this source.
const strpChrg = {
customer: stripeCustomerId,
amount: _.round(amount * 100), // convert to cents
currency: _.toLower(currency), // usd
source: sourceId
};
// create stripe charge using customer token
return stripe.charges.create(strpChrg).then((charge) => {
// add charge to data
return charge;
});
You should not create a token at the backend, use stripe default source added by the customer instead.
For anyone who wants to create charges this way, here is how i figured it out with Node.js (for people like me who came from python, this will be very helpful):
stripe.tokens.create({
card: {
number: '<card number>',
exp_month: <exp>,
exp_year: <year>,
cvc: '<cvc>'
}
}, function(err, token) {
console.log(token.id); // you can log the entire token, or you can just check for the piece you need
stripe.charges.create({
amount: 800,
currency: "usd",
source: token.id, // instead of in python where you can use a variable, in node you have to use specifically the id
description: "Test charge"
}, function(err, charge) {
console.log(err); // if it does not work, make sure to print the error
console.log(charge) // print the charge to make sure it went through
});
});
Hopefully this will help someone along the road!
Note: As others mentioned, for production this is probably not what you want to do, this solution would more be for getting to know the Stripe API or testing out quick charges.

Parse-server social login

I am developing application based on Parse-server and I want to offer social login. I found this guide in the documentation http://docs.parseplatform.org/js/guide/#linking-users.
I started to implement the social login by google. I did following steps:
1) I added following lines to the ParseServer settings
var api = new ParseServer({
...
auth:{
google: {}
},
...
});
2) I did the authentication by hello.js on the client side (call user._linkWith function on login)
hello.init({
google: 'My Google id'
});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('me').then(function(r) {
const user = new Parse.User();
user._linkWith(auth.network, auth.authResponse).then(function(user){
console.log('You are logged in successfully.');
});
});
});
When I debugged it, I found that it fails in _linkWith() function, when provider object is preparing. Object AuthProviders, which should store all providers, is empty. Because of it the statement provider = authProviders['google']; leads to undefined. Invoking provider.authenticate(...); leads to error "Cannot read property 'authenticate' of undefined"
What am I missing or what am I doing wrong?
Thanks for all your answers.
Honza
Did you register the authenticationProvider? You can find examples in our unit tests on how to do so:
https://github.com/parse-community/parse-server/blob/5813fd0bf8350a97d529e5e608e7620b2b65fd0c/spec/AuthenticationAdapters.spec.js#L139
I also got this error and looked at the _linkWith(provider, options) source code. It checks if options has an authData field (which in turn should contain id and credentials). If so, it uses options.authData. Otherwise it falls back on looking up a previously registered authentication provider mentioned in the previous answer.
This is a fragment of the code I'm using:
const authData = {
"id": profile.getId(),
"id_token": id_token
}
const options = {
"authData": authData
}
const user = new Parse.User();
user._linkWith('google', options).then(function(user) {
console.log('Successful user._linkWith(). returned user=' + JSON.stringify(user))
}, function(error) {
console.log('Error linking/creating user: ' + error)
alert('Error linking/creating user: ' + error)
// TODO handle error
})

Categories

Resources