Hi I'm just confused that how to transact BEP-20 Token(e.g: Binance-Peg BUSD-T). I have simply transact bnb in Binance Smart Chain with this code:
const tx = await web3.eth.accounts.signTransaction({
to: '0xB1455f4721b32390f4b65F86D2Cd50e74FaD7A99',
value: '500000000000000',
gas: 2000000
}, 'SENDER_PRIVATE_KEY');
const transaction = await web3.eth.sendSignedTransaction(tx.rawTransaction);
And it work perfectly fine. But I just do absolutely anything to transact a token, for example I used web3.eth.Contract(abi, contract_addr) and then
await contract.methods.transfer(toAddress, '500000000000000000').send({
from: '0xF9FF794700224fc9a1D6a30eb2A90d11eA1D82D1'
});
or with ethereumjs-tx package and ..., but none of them transact the token. I just need a sample code example or a well documented blog to tell me what should I do. Can anyone help me with that ?!!
In order to use the .send({from: ...}) method, you need to
Have the from account unlocked on your provider.
OR
Add its private key to the web3 account wallet (docs)
Ulocked provider account
This approach is mostly used on local providers (e.g. Ganache) that fund and unlock some accounts by default.
Keeping an unlocked account on a production provider is unwise, because anyone who queries the provider can send transactions.
Web3 account wallet
You need to pass the private key that generates the from address.
web3.eth.accounts.wallet.add(privateKey);
And then you can use the .send({from: ...}) method
await contract.methods.transfer(toAddress, '500000000000000000').send({
from: '0xF9FF794700224fc9a1D6a30eb2A90d11eA1D82D1'
});
Related
I'm trying to get a list of reviews of my Google business through the API to display them on my website. But I can't figure out how to authenticate the API server side. The documentation only mentions OAuth2.0 authentication from the client side with redirect URLs, but there won't be a client going to a confirmation page in this case.
I just want to be able to perform this request in Node.js:
GET https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}/reviews
I've already submitted the application and been approved for a Business API and enabled the various APIs in my account. I have created OAuth2.0 credentials. I'm just not sure how to move forward from here.
How can I authenticate Google Business API requests on the server?
I ended up putting together an answer through lots of searching. Google documentation is all over the place.
A basic example of getting reviews is below. But to get it to work there are a few steps first.
You'll need to add a Service Account in your API credentials page
The name, ID, and description aren't particularly important. Just something that makes sense to you
Go to the service account details -> keys -> add key -> create new key -> JSON
This will download a key file to your computer. Keep it private.
Grant domain wide delegation for your service account
To do this, you'll need to be an admin of the account if you're part of an organisation
It will ask for a Client ID, but it is called Unique ID in the service account details. They're the same thing.
Add whatever scopes you need for the services you want to access. For reviews, the scope listed in the example below is enough.
The subject field in google.auth.JWT needs to be an admin of the account. I used my own email.
That should be it! You should now be able to fill out the values in the example below and access the API from a server. Other services may require different scopes.
You can get account and location info from the API docs. The endpoints and data formats are fairly well documented. Just authentication isn't very well explained it seems.
import axios from 'axios';
import {google} from 'googleapis';
import key from './key.json' assert {type: 'json'};
main();
async function main(){
const reviews=await getReviews();
}
async function getReviews(){
const token=await authenticate();
const accountId='YOUR ACCOUNT ID';
const locationId='YOUR LOCATION ID';
const url=`https://mybusiness.googleapis.com/v4/accounts/`+
`${accountId}/locations/${locationId}/reviews`;
const resp=await axios.get(url, {
headers: {
authorization: `Bearer ${token}`
}
});
return resp.data.reviews;
}
async function authenticate(){
const scopes=[
'https://www.googleapis.com/auth/business.manage'
];
const jwt=new google.auth.JWT({
email: key.client_email,
key: key.private_key,
subject: 'ADMIN EMAIL',
scopes
});
const resp=await jwt.authorize();
return resp.access_token.replace(/\.{2,}/g, '');
}
When trying to test Stripe Connect Api, I get the following error:
'StripeInvalidRequestError: You can only create new accounts if you've
signed up for Connect'
I have signed up for an account and I use my personal Secret Key so i don't know why its not letting me test this feature. Below is the code for the post request.
router.post('/api/post/create-stripe-account', async (req,res) => {
const data = req.body;
try{
var account = await stripe.accounts.create({
country: 'US',
type: 'custom',
requested_capabilities: ['card_payments', 'transfers'],
});
res.json(account)
}catch(error){
console.log(error)
}
})
Link to documentation that I followed: Using Connect with Custom Accounts
Any thoughts why stripe doesn't think I have signed up? I have used this secret key successfully with sending payments by card but stripe connect doesn't seem to like it. Thanks!
I followed these steps from stripe docs and it works.
https://stripe.com/docs/connect/collect-then-transfer-guide
You should be able to create new accounts in test mode using your test API key (starting with sk_test_). Can you confirm that's the key you're using on your server?
The error you're getting usually indicates your Connect platform application is not complete and you're trying to create an account in live mode (using your sk_live_ key). In order to create accounts in live mode you need to complete your platform profile in the Stripe Dashboard.
I resolved the issue based on Justin Michael's comment
Do you have Connect enabled in test mode here? dashboard.stripe.com/test/connect/accounts/overview Does anything seem amiss in your Connect settings here? dashboard.stripe.com/test/settings/applications –
Justin Michael
Jul 9, 2020 at 23:31
Click on get started only then you can get access to create function of stripe.
I have been trying to get emails from another user in my domail in order to migrate it, using the google nodejs library. My account is superadmin and my API has wide-domain delegation permission enable with the following scopes:
"https://www.googleapis.com/auth/apps.groups.migration",
"https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.settings.sharing"
I have logged into the API usin an impersonate access
async function initializeGmail(emailToImpersonate) {
const auth = await getAuth(emailToImpersonate);
return google.gmail({
version: 'v1',
auth
});
}
async function getAuth(emailToImpersonate) {
const jwtClient = new google.auth.JWT(
client_email,
null,
private_key,
SCOPES,
emailToImpersonate
);
await jwtClient.authorize();
return jwtClient;
}
I have added delegation permitions in the account I want to migrate so I can access its emails from my main account
const requestBody = {
delegateEmail: user.email,
verificationStatus: 'accepted'
}
await gmail.users.settings.delegates.create({userId, requestBody})
I request the emails of the account to migrate and I get the following error
const gmail = await initializeGmail(userEmail);
const messages = (await gmail.users.messages.list({auth, userId:userEmail})).data.messages;
code: 403,
errors: [
{
domain: 'global',
reason: 'forbidden',
message: 'Delegation denied for sysadmin#boatjump.com'
}
]
Any help or ideas will be highly appreciated
1st step - Create a delegate
To create a delegate, the parameter delegateEmail must specify the primary email of the delegate, that is your main account, I assume sysadmin#boatjump.com
As specified in the documentation, the delegate creation must performed by a service account that impersonates the delegator (your secondary account, I assume user.email)
2nd step - list the delegator's emails
Authenticate as sysadmin#boatjump.co' (no need for service account)
Specify as userId user.email
The reason you obtained a 403 error is the fact you specified
user.email instead of sysadmin#boatjump.com as the delegate and
thus did not pass to sysadmin#boatjump.com the authority to list
user.email's emails.
UPDATE:
If after a correct set-up of a delegate you continue experiencing issues with retrieving the delegator's emails, this issue is likely related to this behavior already reported on Google's Issue Tracker.
I recommend you to give it a "star" to increase visibility and the chances that it will be fixed in the future.
Workaround for the meantime:
When using the service account with domain-wide delegation, authenticate as the delegator and retrieve the emails on his behalf (userId:"me").
I have added google cloud service account in a project and its working. But the problem is that after an hour(i think), I get this error:
The API returned an error: TypeError: source.hasOwnProperty is not a function
Internal Server Error
and I need to restart the application to make it work.
Here in this StackOverflow post, I found this:
Once you get an access token it is treated in the same way - and is
expected to expire after 1 hour, at which time a new access token will
need to be requested, which for a service account means creating and
signing a new assertion.
but didn't help.
I'm using Node js and amazon secret service:
the code I have used to authorize:
const jwtClient = new google.auth.JWT(
client_email,
null,
private_key,
scopes
);
jwtClient.authorize((authErr) =>{
if(authErr){
const deferred = q.defer();
deferred.reject(new Error('Google drive authentication error, !'));
}
});
Any idea?
hint: Is there any policy in AWS secret to access a secret or in google cloud to access a service account? for example access in local or online?
[NOTE: You are using a service account to access Google Drive. A service account will have its own Google Drive. Is this your intention or is your goal to share your Google Drive with the service account?]
Is there any policy in AWS secret to access a secret or in google
cloud to access a service account? for example access in local or
online?
I am not sure what you are asking. AWS has IAM policies to control secret management. Since you are able to create a Signed JWT from stored secrets, I will assume that this is not an issue. Google does not have policies regarding accessing service accounts - if you have the service account JSON key material, you can do whatever the service account is authorized to do until the service account is deleted, modified, etc.
Now on to the real issue.
Your Signed JWT has expired and you need to create a new one. You need to track the lifetime of tokens that you create and recreate/refresh the tokens before they expire. The default expiration in Google's world is 3,600 seconds. Since you are creating your own token, there is no "wrapper" code around your token to handle expiration.
The error that you are getting is caused by a code crash. Since you did not include your code, I cannot tell you where. However, the solution is to catch errors so that expiration exceptions can be managed.
I recommend instead of creating the Google Drive Client using a Signed JWT that you create the client with a service account. Token expiration and refresh will be managed for you.
Very few Google services still support Signed JWTs (which your code is using). You should switch to using service accounts, which start off with a Signed JWT and then exchange that for an OAuth 2.0 Access Token internally.
There are several libraries that you can use. Either of the following will provide the features that you should be using instead of crafting your own Signed JWTs.
https://github.com/googleapis/google-auth-library-nodejs
https://github.com/googleapis/google-api-nodejs-client
The following code is an "example" and is not meant to be tested and debugged. Change the scopes in this example to match what you require. Remove the section where I load a service-account.json file and replace with your AWS Secrets code. Fill out the code with your required functionality. If you have a problem, create a new question with the code that you wrote and detailed error messages.
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');
const key = require('service-account.json');
/**
* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc)
* this library will automatically choose the right client based on the environment.
*/
async function main() {
const auth = new GoogleAuth({
credentials: {
client_email: key.client_email,
private_key: key.private_key,
},
scopes: 'https://www.googleapis.com/auth/drive.metadata.readonly'
});
const drive = google.drive('v3');
// List Drive files.
drive.files.list({ auth: auth }, (listErr, resp) => {
if (listErr) {
console.log(listErr);
return;
}
resp.data.files.forEach((file) => {
console.log(`${file.name} (${file.mimeType})`);
});
});
}
main()
I am saving customers and their sources on my platform, and trying to create charges for my connected accounts. I am able to successfully create destination charges, but I'm having trouble with creating direct charges.
I've tried creating a token per: https://stripe.com/docs/connect/shared-customers
If I create a token using just the customer the example, the error is:
'You provided a customer without specifying a source. The default source of the customer is a source and cannot be shared from existing customers.'
Even though the documentation says that you need "The card or bank account ID for that customer, if you want to charge a specific card or bank account rather than the default".
I cannot find a parameter that lets me specify a source as well or instead of a customer.
I've tried sharing the customer's chosen source with the connected account per: https://stripe.com/docs/sources/connect#shared-card-sources
which results in the error:
'Sending credit card numbers directly to the Stripe API is generally unsafe. We suggest you use test tokens that map to the test card you are using, see https://stripe.com/docs/testing.'
I tried attaching a test token (tok_visa) to my customer, and creating a charge with that, but that had the same result.
Every time I have some success I end up with the error about sending numbers being unsafe even though I'm only ever sending Stripe's provided token or source ID's.
I've tried this:
const newToken = await stripe.tokens.create({
customer: customerId,
}, {
stripe_account: stripeAccountId,
}).catch((e) => {
console.log(e);
});
and this:
const newToken = await stripe.sources.create({
customer: customerId,
usage: 'single_use',
original_source: sourceId,
}, {
stripe_account: stripeAccountId,
}).catch((e) => {
console.log(e);
});
The only success I've had is creating the direct charge with a test token (tok_visa), completely bypassing the sharing of tokens/sources. No other combination seems to work. But that leaves me at a loss as to how to get a real shared token when I need it.
I found out I should be using sources, not tokens. And it turns out I was accidentally using the whole newToken as the source for the charge. It's working now that I'm passing the newToken.id to the charge.