fetch customerId for myApiClient - node.js

I am trying to fetch the customerId for myAPIClient using swift firebase and node.js. When I run my application it crashes and tells me that the customerId is nil. The reason that I am needing this customerId is in order to create the ephemeralKey.
The code that I use in node.js is,
exports.createEphemeralKey = functions.https.onRequest((req, res) => {
const stripe_version = req.body.api_version;
const customerId = req.body.customerId
if (!stripe_version) {
console.log('I did not see any api version')
res.status(400).end()
return;
}
stripe.ephemeralKeys.create(
{customer: customerId},
{stripe_version: apiVersion}
).then((key) => {
console.log("Ephemeral key: " + key)
res.status(200).json(key)
}).catch((err) => {
console.log('stripe version is ' + stripe_version + " and customer id is " + customerId + " for key: " + stripe_key + " and err is " + err.message )
res.status(500).json(err)
});
});
and the code that I am using inside of myApiClient is.
func createCustomerKey(withAPIVersion apiVersion: String, completion: #escaping STPJSONResponseCompletionBlock) {
let url = self.baseURL.appendingPathComponent("ephemeral_keys")
let defaults = UserDefaults.standard
let customerId = defaults.string(forKey: "customerId")
AF.request(url, method: .post, parameters: [
"api_version": apiVersion, "customer_id": customerId!
])
.validate(statusCode: 200..<300)
.responseJSON { responseJSON in
switch responseJSON.result {
case .success(let json):
completion(json as? [String: AnyObject], nil)
case .failure(let error):
completion(nil, error)
}
}
}
I have been stuck on creating this ephemeralKey for a while now and have asked other questions but have not gotten a real answer. Is there anything that I am missing? How can I actually access the customersId from stripe inside of my ios project.

You should first check that let customerId = defaults.string(forKey: "customerId") provides a valid customerId. You can do so by debugging your app and inspecting the value of customerId. Assuming that it is valid, I see a couple of things that may be causing issues for you:
The Alamofire library that you are using has 2 Parameter Encoders with different properties and options. You can see them here.
My hypothesis is that you are nor passing the customerId correclty to the body of the request. I suggest you start by trying the JSONParameterEncoder. Your request would be somehting like this:
AF.request(url, method: .post, parameters: [
"api_version": apiVersion, "customer_id": customerId!
],
encoder: JSONParameterEncoder.default)
It is possible that you also have to tweak the way your retrieve the customerID from the Cloud Function according to how you pass the info from the swift app. This docs may provide some insights on how to parse HTTP request info

Related

Could not parse the ephemeral key response following protocol

I am trying to create an ephemeral key in my IOS app. I can successfully create a stripe customer that saves in my firebase console and on my stripe dashboard. However, when I try to create the ephemeral key, I am receiving the error in my ios console after trying to view the checkout controller.
'Could not parse the ephemeral key response following protocol STPCustomerEphemeralKeyProvider. Make sure your backend is sending the unmodified JSON of the ephemeral key to your app.
and on my firebase function logs I am seeing,
createEphemeralKey
Request has incorrect Content-Type.
createEphemeralKey
Invalid request, unable to process.
in my index.js file, the code that I am using is
exports.createEphemeralKey = functions.https.onCall(async(data, context) => {
var stripeVersion = data.api_version;
const customerId = data.customer_id;
return stripe.ephemeralKeys.create(
{customer: customerId},
{stripe_version: stripeVersion}
).then((key) => {
return key
}).catch((err) => {
console.log(err)
})
})
Below is how I create my stripe customer.
exports.createStripeCustomer = functions.auth.user().onCreate((user) => {
return stripe.customers.create({
email: user.email,
}).then((customer) => {
return admin.database().ref(`/stripe_customers/${user.uid}/customer_id`).set(customer.id);
});
});
and then myAPIClient looks like.
enum APIError: Error {
case unknown
var localizedDescription: String {
switch self {
case .unknown:
return "Unknown error"
}
}
}
static let sharedClient = MyAPIClient()
var baseURLString: String? = "https://myProject.cloudfunctions.net/"
var baseURL: URL {
if let urlString = self.baseURLString, let url = URL(string: urlString) {
return url
} else {
fatalError()
}
}
func createCustomerKey(withAPIVersion apiVersion: String, completion: #escaping STPJSONResponseCompletionBlock) {
let url = self.baseURL.appendingPathComponent("ephemeral_keys")
Alamofire.request(url, method: .post, parameters: [
"api_version": apiVersion,
])
.validate(statusCode: 200..<300)
.responseJSON { responseJSON in
switch responseJSON.result {
case .success(let json):
completion(json as? [String: AnyObject], nil)
case .failure(let error):
completion(nil, error)
}
}
}
On my checkOutVC, I have
var stripePublishableKey = "pk_test_testProjectKey"
var backendBaseURL: String? = "https://myProject.cloudfunctions.net"
let customerContext = STPCustomerContext(keyProvider: MyAPIClient())
init(price: Int, settings: Settings) {
if let stripePublishableKey = UserDefaults.standard.string(forKey: "StripePublishableKey") {
self.stripePublishableKey = stripePublishableKey
}
if let backendBaseURL = UserDefaults.standard.string(forKey: "StripeBackendBaseURL") {
self.backendBaseURL = backendBaseURL
}
let stripePublishableKey = self.stripePublishableKey
let backendBaseURL = self.backendBaseURL
assert(stripePublishableKey.hasPrefix("pk_"), "You must set your Stripe publishable key at the top of acceptWorker.swift to run this app.")
assert(backendBaseURL != nil, "You must set your backend base url at the top of acceptWorker.swift to run this app.")
Stripe.setDefaultPublishableKey(self.stripePublishableKey)
let config = STPPaymentConfiguration.shared()
config.appleMerchantIdentifier = self.appleMerchantID
config.companyName = self.companyName
config.requiredBillingAddressFields = settings.requiredBillingAddressFields
config.requiredShippingAddressFields = settings.requiredShippingAddressFields
config.shippingType = settings.shippingType
config.additionalPaymentOptions = settings.additionalPaymentOptions
config.cardScanningEnabled = true
self.country = settings.country
self.paymentCurrency = settings.currency
self.theme = settings.theme
MyAPIClient.sharedClient.baseURLString = self.backendBaseURL
let paymentContext = STPPaymentContext(customerContext: customerContext, configuration: config, theme: settings.theme)
self.paymentContext = STPPaymentContext(customerContext: customerContext)
super.init(nibName: nil, bundle: nil)
self.paymentContext.delegate = self
self.paymentContext.hostViewController = self
self.paymentContext.paymentAmount = 5000 // This is in cents, i.e. $50 USD
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
I apologize for the long lines of code but I am really running into a brick wall. Why isnt the backend creating the ephemeralKey for customers?
Two things are jumping out at me:
You’ve written a callable type function (using onCall) but you’re
trying to call it with a normal HTTP request. These functions need to
be called with Firebase’s client library
(https://firebase.google.com/docs/functions/callable#call_the_function).
This stack overflow answer provides some great links about this:
Firebase Cloud Function to delete user.
Your firebase function is parsing stripe_version and customer_id from
data, but your request is only sending api_version. Where in your
code are you sending stripe_version and customer_id?

How to add IBM API authentication to my code?

Watson Assistant only supports one Webhook url. The issue is I have multiple nodes in Assistant that need to call different "Actions" I have hosted in IBM Cloud Functions. How can I do that? I tried to code and "Action" that uses the NPM Axios to call the other "Actions" but it fails as it lacks authentication.
Can someone tell me how to do it? I need the BASE URL to be athenticated via my IBM Cloud user API to grant access to my namespace.
this is the action I created that acts as a "Dispatch" for webhooks for Watson Assistant.
/**
*
* main() will be run when you invoke this action
*
* #param Cloud Functions actions accept a single parameter, which must be a JSON object.
*
* #return The output of this action, which must be a JSON object.
*
*
* Version: 1.5 beta (API HUB)
* Date: 24/04/2020
*
*/
const axios = require("axios");
// Change to your "BASE_URL". Type in the "Web Action" url without the name of it at the end. (must NOT contains the end '/')
// All "Actions" must be within the same namespace.
const BASE_URL = "https://jp-tok.functions.cloud.ibm.com/api/v1/web/
const POST = "post";
const GET = "get";
const ANY = "any";
const ALL = "all";
/* List all your API methods
1. method - API Name (This is the "Actions" name at the end of the Web Action URL or just the name)
2. attr - Attributes that should be available in the params object
3. rule - Currently supports 2 rules;
a) any - params is valid if "any" of the attributes are present
b) all - params is valid only if all attributes are present
4. httpmethod -Supports "POST" and "GET"
5. contains - Use for validating GET URL parameters
*/
const API_METHODS = [{
method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
attr: ["client_email", "department_email"],
rule: ANY,
httpmethod: POST,
contains: null
},
{
method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
attr: [],
rule: ALL,
httpmethod: GET,
contains: "?ID="
},
]
// Returns true if the "params" is valid for the given API method
function isValidParam(method, params = {}) {
var attributes = [];
attributes = method.attr;
var isAny = method.rule === ANY;
for (let index = 0; index < attributes.length; index++) {
const attr = attributes[index];
if (isAny) {
if (Object.hasOwnProperty.call(params, attr)) {
return true;
}
} else {
if (!Object.hasOwnProperty.call(params, attr)) {
return false;
}
}
}
if (attributes.length === 0 && method.contains) {
return (JSON.stringify(params).indexOf(method.contains) > -1)
}
// if the code reaches this position, inverse of "isAny" should return the actual validation status.
return !isAny;
}
async function main(params) {
var result = [];
// Stop on first failure
// We iterate through all API methods. Because there can be more than one matching API for the given param type
for (let index = 0; index < API_METHODS.length; index++) {
const apiMethod = API_METHODS[index];
const url = BASE_URL + '/' + apiMethod.method;
if (isValidParam(apiMethod, params)) {
let response = apiMethod.httpmethod === POST ?
await axios.post(url, params) :
await axios.get(url + params); // Expects the parameter to be a string in this case like '?id=345343'
console.log(response);
result.push({
sent: true,
url: url,
request: params,
});
}
}
return {
sent: true,
details: result
};
}
// THe part of the code that needs to be copied to call other functions within the namespace.
/* const API_METHODS = [{
method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
* attr: ["bamboo_email", "latitude_email", "latest_r_email", "department_email"],
rule: ANY,
httpmethod: POST,
contains: null
},
{
method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
attr: [],
rule: ALL,
httpmethod: GET,
contains: "?ID="
},
] */
When I run it in Watson Assistant I get the following error:
Webhook call response body exceeded [1050000] byte limit.response code: 200, request duration: 591, workspace_id: 150088ee-4e86-48f5-afd5-5b4e99d171f8, transaction_id: a8fca023d456d1113e05aaf1f59b1b2b, url_called: https://watson-url-fetch.watson-url-fetcher:443/post?url=https%3A%2F%2Fjp-tok.functions.cloud.ibm.com%2Fapi%2Fv1%2Fweb%2F23d61581-fa68-4979-afa2-0216c17c1b29%2FWatson+Assistant%2FAssistant+Dispatch.json (and there is 1 more error in the log)

What are the use of Transaction ID respond in invoke-transaction.js of Balance Transfer sample?

I am currently learning how to develop client app using Hyperledger Fabric Node SDK. To do so, I'm now trying to understand the Node JS code of balance-transfer sample in fabric-samples.
In the balance-transfer/app/invoke-transaction.js file, invokeChaincode function returns Transaction ID. And that returned value is the res parameter of app.js invoke post function.
My question is, what can be done with Transaction ID alone? What if I, say, want to know the block # of my invocation? Is it just a response with no further use?
Please bear with me if this is a stupid question, I'm new to this.
Thanks!
Here's the code snippet of stated app.js
// Invoke transaction on chaincode on target peers
app.post('/channels/:channelName/chaincodes/:chaincodeName', function(req, res) {
logger.debug('==================== INVOKE ON CHAINCODE ==================');
var peers = req.body.peers;
var chaincodeName = req.params.chaincodeName;
var channelName = req.params.channelName;
var fcn = req.body.fcn;
var args = req.body.args;
logger.debug('channelName : ' + channelName);
logger.debug('chaincodeName : ' + chaincodeName);
logger.debug('fcn : ' + fcn);
logger.debug('args : ' + args);
if (!chaincodeName) {
res.json(getErrorMessage('\'chaincodeName\''));
return;
}
if (!channelName) {
res.json(getErrorMessage('\'channelName\''));
return;
}
if (!fcn) {
res.json(getErrorMessage('\'fcn\''));
return;
}
if (!args) {
res.json(getErrorMessage('\'args\''));
return;
}
invoke.invokeChaincode(peers, channelName, chaincodeName, fcn, args, req.username, req.orgname)
.then(function(message) {
res.send(message);
});
});
You can use the transaction ID to listen for any events or query the ledger for the transaction later.
Listen for events: https://github.com/hyperledger/fabric-samples/blob/release/balance-transfer/app/invoke-transaction.js#L101
Query Transactions: https://github.com/hyperledger/fabric-samples/blob/release/balance-transfer/app/query.js#L100
It depends on how you can put it to use.
Refer to the SDK docs for more information: https://fabric-sdk-node.github.io/index.html

How to get the time zone or local time of Alexa device

I want to get the "time zone" set in the settings or local date time of the Alexa device. Is there any API available for it? Or is there any option to get the date-time of the user using his postal code?
Any help will be highly appreciable?
It is now possible to get a user's timezone and other related data using the Alexa Settings API. Also see the related blogpost for more information on this API release.
The endpoint you'll be interested in is the following:
GET /v2/devices/{deviceId}/settings/System.timeZone
You simply need to provide the user's device ID, which is part of the received intent. The response will contain a timezone name, for instance "Europe/London".
Yes, there is a native Alexa API that you can use. Here is a perfect solution for what you're looking for. What you will need is a device ID and an API access token. Also, few tools like axios ( npm i axios) and zip-to-country-code (npm i zipcode-to-timezone) more info here Enhance Your Skill With Address Information Also, before you implement this code make sure to go to Alexa dev portal and turn on permissions See image below. Cheers!
const apiAccessToken = this.event.context.System.apiAccessToken;
const deviceId = this.event.context.System.device.deviceId;
let countryCode = '';
let postalCode = '';
axios.get(`https://api.amazonalexa.com/v1/devices/${deviceId}/settings/address/countryAndPostalCode`, {
headers: { 'Authorization': `Bearer ${apiAccessToken}` }
})
.then((response) => {
countryCode = response.data.countryCode;
postalCode = response.data.postalCode;
const tz = ziptz.lookup( postalCode );
const currDate = new moment();
const userDatetime = currDate.tz(tz).format('YYYY-MM-DD HH:mm');
console.log('Local Timezone Date/Time::::::: ', userDatetime);
})
If you are using ASK sdk v2. There's a better way to get the timezone.
const getCurrentDate = async (handlerInput) => {
const serviceClientFactory = handlerInput.serviceClientFactory;
const deviceId = handlerInput.requestEnvelope.context.System.device.deviceId;
try {
const upsServiceClient = serviceClientFactory.getUpsServiceClient();
return userTimeZone = await upsServiceClient.getSystemTimeZone(deviceId);
} catch (error) {
if (error.name !== 'ServiceError') {
return handlerInput.responseBuilder.speak("There was a problem connecting to the service.").getResponse();
}
console.log('error', error.message);
}
}

I'm trying to send emails using sendgrid in nodejs.But am getting "TypeError: object is not a function" error

Here is my code snippet
var sendgrid = require('sendgrid')('xxxxxx', 'xxxxxx');
var email = new sendgrid.Email();
email.addTo('xyz#gmail.com');
email.setFrom('xyz#gmail.com');
email.setSubject('welcome to send grid');
email.setHtml('<html><body>HELLO evryone ...,</body></html>');
sendgrid.send(email, function(err, json) {
if(!err)
{
console.log("mail sent successssss");
res.send({"status":0,"msg":"failure","result":"Mail sent successfully"});
}
else
{
console.log("error while sending mail")
res.send({"status":1,"msg":"failure","result":"Error while sending mail."});
}
});
Installed sendgrid throgh npm also.am getting "TypeError: object is not a function" error.MAy i know why.??
Version:--
sendgrid#3.0.8 node_modules\sendgrid
└── sendgrid-rest#2.2.1
It looks like you're using sendgrid#3.0.8 but trying to call on the sendgrid#2.* api.
v2 implementation: https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/nodejs.html
v3 implementation:
https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/nodejs.html
Give the v3 a go.
As for the type error:
v2
var sendgrid = require("sendgrid")("SENDGRID_APIKEY");
you're invoking a function
however you have v3 installed
require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
and it's now an object
REQUESTED UPDATE:
I don't know too much about the keys given, but since they have tons of different supported libraries, it's completely possible that some of them use both while others use only one. If you really only have a USER_API_KEY nad PASSWORD_API_KEY, just use the user_api_key
Here is their source for the nodejs implementation module SendGrid:
function SendGrid (apiKey, host, globalHeaders) {
var Client = require('sendgrid-rest').Client
var globalRequest = JSON.parse(JSON.stringify(require('sendgrid-rest').emptyRequest));
globalRequest.host = host || "api.sendgrid.com";
globalRequest.headers['Authorization'] = 'Bearer '.concat(apiKey)
globalRequest.headers['User-Agent'] = 'sendgrid/' + package_json.version + ';nodejs'
globalRequest.headers['Accept'] = 'application/json'
if (globalHeaders) {
for (var obj in globalHeaders) {
for (var key in globalHeaders[obj] ) {
globalRequest.headers[key] = globalHeaders[obj][key]
}
}
}
The apiKey is attached to the header as an auth, and it looks like that's all you need.
Try following their install steps, without your own implementation,
1) (OPTIONAL) Update the development environment with your SENDGRID_API_KEY, for example:
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
========
2) Make this class and if you did the above use process.env.SENDGRID_API_KEY else put your USER_API_KEY
var helper = require('sendgrid').mail
from_email = new helper.Email("test#example.com")
to_email = new helper.Email("test#example.com")
subject = "Hello World from the SendGrid Node.js Library!"
content = new helper.Content("text/plain", "Hello, Email!")
mail = new helper.Mail(from_email, subject, to_email, content)
//process.env.SENDGRID_API_KEY if above is done
//else just use USER_API_KEY as is
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
var requestBody = mail.toJSON()
var request = sg.emptyRequest()
request.method = 'POST'
request.path = '/v3/mail/send'
request.body = requestBody
sg.API(request, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})

Resources