How do I make an M-Pesa Callback URL using Firebase Cloud Firestore? - firebase

I'm trying to make an app that can send payments to PayBill numbers with Safaricom's "Lipa Na M-Pesa" (a Kenyan thing). The call is a POST request to URL:
https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest
with header:
{
'Host': 'sandbox.safaricom.co.ke',
'Authorization': 'Bearer ${await mpesaAccessToken}',
'Content-Type': 'application/json',
}
and body:
{
"BusinessShortCode": "$businessShortCode",
"Password": "${generateLnmPassword(timeStamp)}",
"Timestamp": "$timeStamp",
"TransactionType": "CustomerPayBillOnline",
"Amount": "10",
"PartyA": "$userPhoneNumber",
"PartyB": "$businessShortCode",
"PhoneNumber": "$userPhoneNumber",
"CallBackURL": "?????????????????????????????",
"AccountReference": "account",
"TransactionDesc": "test",
}
I've received an access token, generated a password and made the call successfully, except for that CallBackURL thing... The M-Pesa docs describe their callback like this:
CallBackURL
This is the endpoint where you want the results of the transaction delivered. Same rules for Register URL API callbacks apply.
all API callbacks from transactional requests are POST requests, do not expect GET requests for callbacks. Also, the data is not formatted into application/x-www-form-urlencoded format, it is application/json, so do not expect the data in the usual POST fields/variables of your language, read the results directly from the incoming input stream.
(More info here, but you may need to be logged in: https://developer.safaricom.co.ke/get-started see "Lipa na M-Pesa")
My app is hosted on Firebase Cloud Firestore. Is there any way I can create a callback URL with them that will receive their callback as a document in a Firestore collection?...
Or would this be impossible, given that they would need authorization tokens and stuff to do so... and I can't influence what headers and body M-Pesa will send?
(PS Btw, I code in Flutter/Dart so plz don't answer in Javascript or anything! I'll be clueless... :p Flutter/Dart or just plain text will be fine. Thanks!)

Is there any way I can create a callback URL with them that will
receive their callback as a document in a Firestore collection?...
The most common way to do that in the Firebase ecosystem is to write an HTTPS Cloud Function that will be called by the Safaricom service.
Within the Cloud Function you will be able to update the Firestore document, based on the content of the POST request.
Something like:
exports.safaricom = functions.https.onRequest((req, res) => {
// Get the header and body through the req variable
// See https://firebase.google.com/docs/functions/http-events#read_values_from_the_request
return admin.firestore().collection('...').doc('...').update({ foo: bar })
.then(() => {
res.status(200).send("OK");
})
.catch(error => {
// ...
// See https://www.youtube.com/watch?v=7IkUgCLr5oA&t=1s&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=3
})
});
I did note that you ask us to not "answer in Javascript or anything" but in Flutter/Dart, but I don't think you will able to implement that in Flutter: you need to implement this webhook in an environment that you fully control and that exposes an API endpoint, like your own server or a Cloud Function.
Cloud Functions may seem complex at first sight, but implementing an HTTPS Cloud Functions is not that complicated. I suggest you read the Get Started documentation and watch the three videos about "JavaScript Promises" from the Firebase video series, and if you encounter any problem, ask a new question on SO.

Cloud functions are not Dart-based.
See below solution;
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const parse = require("./parse");
admin.initializeApp();
exports.lmno_callback_url = functions.https.onRequest(async (req, res) => {
const callbackData = req.body.Body.stkCallback;
const parsedData = parse(callbackData);
let lmnoResponse = admin.firestore().collection('lmno_responses').doc('/' + parsedData.checkoutRequestID + '/');
let transaction = admin.firestore().collection('transactions').doc('/' + parsedData.checkoutRequestID + '/');
let wallets = admin.firestore().collection('wallets');
if ((await lmnoResponse.get()).exists) {
await lmnoResponse.update(parsedData);
} else {
await lmnoResponse.set(parsedData);
}
if ((await transaction.get()).exists) {
await transaction.update({
'amount': parsedData.amount,
'confirmed': true
});
} else {
await transaction.set({
'moneyType': 'money',
'type': 'deposit',
'amount': parsedData.amount,
'confirmed': true
});
}
let walletId = await transaction.get().then(value => value.data().toUserId);
let wallet = wallets.doc('/' + walletId + '/');
if ((await wallet.get()).exists) {
let balance = await wallet.get().then(value => value.data().moneyBalance);
await wallet.update({
'moneyBalance': parsedData.amount + balance
})
} else {
await wallet.set({
'moneyBalance': parsedData.amount
})
}
res.send("Completed");
});
Parse function.
const moment = require("moment");
function parse(responseData) {
const parsedData = {};
parsedData.merchantRequestID = responseData.MerchantRequestID;
parsedData.checkoutRequestID = responseData.CheckoutRequestID;
parsedData.resultDesc = responseData.ResultDesc;
parsedData.resultCode = responseData.ResultCode;
if (parsedData.resultCode === 0) {
responseData.CallbackMetadata.Item.forEach(element => {
switch (element.Name) {
case "Amount":
parsedData.amount = element.Value;
break;
case "MpesaReceiptNumber":
parsedData.mpesaReceiptNumber = element.Value;
break;
case "TransactionDate":
parsedData.transactionDate = moment(
element.Value,
"YYYYMMDDhhmmss"
).unix();
break;
case "PhoneNumber":
parsedData.phoneNumber = element.Value;
break;
}
});
}
return parsedData;
}
module.exports = parse;

Related

Trying to implement shopify webhooks but getting 'InternalServerError: stream is not readable'

I'm building an app for shopify and need to add the GDPR webhooks. My back end is handled using next.js and I'm writing a webhook handler to verify them. The docs havent been very helpful because they dont show how to do it with node. This is my verification function.
export function verifiedShopifyWebhookHandler(
next: (req, res, body) => Promise
): NextApiHandler {
return async (req, res) => {
const hmacHeader = req.headers['x-shopify-hmac-sha256'];
const rawBody = await getRawBody(req);
const digest = crypto.createHmac('sha256', process.env.SHOPIFY_API_SECRET).update(rawBody).digest('base64');
if (digest === hmacHeader) {
return next(req, res, rawBody);
}
const webhookId = req.headers['x-shopify-webhook-id'];
return res.status(401).end();
};
}
But I get this Error: error - InternalServerError: stream is not readable
I think it has to do with now Next.js parses the incoming requests before they are sent to my api. Any ideas?
I discovered the answer. Next.js was pre parsing the body in the context which made it so that I couldn't use the raw body parser to parse it. By setting this:
export const config = {
api: {
bodyParser: false
}
};
above the api function in the api file it prevented next from parsing it and causing the issue. I found the answer because people had the same issue integrating swipe and using the bodyParser.

403 The caller does not have permission for Firebase Management API addFirebase

I want to add Firebase project through Firebase Management Api. So for that. I made project on Google Cloud Platform console. And created service account with permission as a owner.
I tried to read and create project throw google api explorer for addFirebase and it works. But when i try to do the same through my code it read availableProject successfully and give output as
{
"projectInfo": [
{
"project": "projects/firebase-api-238012",
"displayName": "Firebase-Api"
}
]
}
but when i try to add project it give me this error
{
"error": {
"code": 403,
"message": "The caller does not have permission",
"status": "PERMISSION_DENIED"
}
}
I don't know why its is not creating project. What other permission it needs. And why it allowed to me read available projects first.
here is how i am trying to add my project.
jwt.js
const { google } = require('googleapis');
var serviceAccountJwt = require('./Firebase-Api-b0e41b85ad44.json');
exports.connect = async () => {
return new Promise((resolve, reject) => {
// scope is based on what is needed in our api
const scope = ['https://www.googleapis.com/auth/firebase', 'https://www.googleapis.com/auth/cloud-platform'];
// create our client with the service account JWT
const { client_email, private_key } = serviceAccountJwt;
const client = new google.auth.JWT(client_email, null, private_key, scope, null);
// perform authorization and resolve with the client
return client.authorize((err) => {
if (err) { reject(err) }
else {
resolve(client)
};
});
});
}
index.js file
const { google } = require('googleapis');
const request = require('request');
const { connect } = require('./jwt');
const availableProjects = 'https://firebase.googleapis.com/v1beta1/availableProjects';
async function getAccessToken() {
let client = await connect();
let accessToken = await client.getAccessToken();
let res = await getProjects(accessToken.token)
}
getAccessToken().catch(err => {
console.log(JSON.stringify(err))
})
const bodys = {
"timeZone": "America/Los_Angeles",
"locationId": "asia-south1",
"regionCode": "US"
}
async function getProjects(accesstoken) {
let options = {
url: availableProjects,
headers: {
'Authorization': 'Bearer ' + accesstoken,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
return request(options, async function (err, res) {
if (err) {
console.error(err + " error");
} else {
//here it gives successful output
console.log("response")
console.log(res.body);
let bodyJson = JSON.parse(res.body);
let projectName = bodyJson.projectInfo[0].project;
console.log(projectName)
await addProject(accesstoken, projectName)
return res.body;
}
});
}
async function addProject(accesstoken, projecctID) {
fbUrl = getAddFBUrl(projecctID);
let options = {
url: fbUrl,
headers: {
'Authorization': 'Bearer ' + accesstoken,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body:JSON.stringify(bodys)
}
return request.post(options, function (err, res) {
if (err) {
console.error(err + " error");
} else {
//here in response out put as permission denied 403
console.log("response")
console.log(res.body);
console.log(JSON.stringify(res));
return res.body;
}
});
}
function getAddFBUrl(projectId) {
return 'https://firebase.googleapis.com/v1beta1/' + projectId +
':addFirebase';
}
i found one similar question to this. But it didn't helped me to resolve my issue which is here
AskFirebase
From the Firebase REST reference: Method: projects.addFirebase
To call projects.addFirebase, a member must be an Editor or Owner for
the existing GCP Project. Service accounts cannot call
projects.addFirebase.
Update:
To call projects.addFirebase, a project member or service account must have the following permissions (the IAM roles of Editor and Owner contain these permissions): firebase.projects.update, resourcemanager.projects.get, serviceusage.services.enable, and serviceusage.services.get.
https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects/addFirebase
I'm not sure if my answer will be helpful for author of this question, but this if first two things all should check when facing 403 Error with Google Cloud APIs
0) Check configuration with gcloud
1) As mentioned before the first thing is to check the role of service account. You need Editor/Owner usually.
https://cloud.google.com/iam/docs/understanding-roles
https://console.cloud.google.com/iam-admin
2) The second one is to check if API enabled for project at all.
Also when creating a key check it for correct service account.
For someone who's just get started like me, this thing maybe helpful. When I seted up database, I choose Start in locked mode instead of Start in test mode. Therefore, I can't read or write :((. For beginner, just set everything in test mode. Hope it helpful.
https://i.stack.imgur.com/nVxjk.png
Your problem means that your project is not linked with your firebase account which means you have to login with your firebase account. Than you will have the permission
type cd functions in your firebase project directory
type firebase login
login with the Gmail which is connected with your firebase account
It'll work

How to use Google AutoML on web app?

I have a Google Cloud AutoML NL model ready to use. I wish to link this with my web app with Firebase backend. Following is my code to call. There is authorization issue. I want to understand how to authorize the app to help the client apps get access to AutoML model.
async add(data){
var headers = new Headers();
headers.append('Content-Type:application/json')
var options = {
method: 'POST',
headers,
body: JSON.stringify(data)
}
var request = new Request('https://automl.googleapis.com/v1beta1/projects/project1/locations/us-central1/models/TCN5678:predict', options )
var response = await fetch(request)
var status = await response.status
console.log(status)}
After struggling for hours, finally I could resolve this. I am not sure how it can work for, other than Firebase (and NL AutoML). I used Firebase Cloud Function to work around and used a hidden doc which gives access to AutoML npm. The given code require some changes. Firebase CF is able to authenticate without explicitly authorizing. Following is a suggested code and I am able to get the classification of prediction with AutoML. Hope it helps others too. Lastly, it seems Google docs is a way of testing searching skills and patience, not sure how it helps them:
const automl = require('#google-cloud/automl');
exports.sendToAML = functions.database.ref('/path/to/text').onWrite((snapshot, context) =>{
var client = new automl.PredictionServiceClient({
// optional auth parameters.
});
var formattedName = client.modelPath('bucketId', 'us-central1', 'TCN****3567595');
var payload = {
"textSnippet": {
"content": snapshot.after._data.text,
"mime_type": "text/plain"
},
};
var request = {
name: formattedName,
payload: payload,
};
client.predict(request)
.then(responses => {
var response = responses[0];
return console.log(response.payload[0].classification.score)
})
.catch(err => {
console.error(err);
});
});
`
You should either use service accounts or OAuth 2.0 as the authentication method. Try to avoid the use of API keys as your credentials could be exposed and misused, generating undesired charges.

HTTP request to a google service returns Error: read ECONNRESET firebase cloud functions

I am trying to translate the name of a user from english to an indian language using google translate api and storing the data back in realtime database with a cloud function.
This function is invoked by a write to the database, and I am using a HTTP POST request to send a request to the cloud translate api and the response is stored back to the database. My code for the translate request is this.
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'key goes here',
},
form: {
q: fullData.name,
target: "te"
},
};
request(translate_options, function (error, translate_response, translate_body) {
if (error){
console.log("In translating, got an error");
console.log(error);
}
// Query to the database goes here.
});
This code, if tried in my laptop, gives me the correct translation, but if I deploy it as a cloud function, it gives me an error. Very specifically
{ Error: read ECONNRESET
at exports._errnoException (util.js:1020:11)
at TLSWrap.onread (net.js:568:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
I am on firebase blaze plan, and I am able to sent POST request to my other services, but not a google service.
Can anybody help me with this issue. Thanks in advance.
Edit :
The full code is
var functions = require('firebase-functions');
var admin = require('firebase-admin');
var request = require("request");
admin.initializeApp(functions.config().firebase);
exports.whenUserIsAdded = functions.database.ref('users/{companyId}/{uid}').onCreate(event => {
var fullData = event.data.val();
var lang_code = {
"bengali": "bn",
"telugu": "te",
"english": "en"
}
var lang_var = lang_code[fullData['edition']];
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'Key goes here',
},
form: {
q: fullData.name,
target: lang_var
},
};
request(translate_options, function (error, translate_response, translate_body) {
var farmer_name = "";
if(error){
console.log("There is an error in translation");
console.log(error);
}
translate_body = JSON.parse(translate_body);
if(translate_body.data.translations){
farmer_name = translate_body.data.translations[0].translatedText;
console.log("The farmer name is " + fullData.name +" : " + farmer_name);
// Code to write to the database;
} else{
console.log("The translation failed");
farmer_name = fullData.name;
console.log("The famrer name is " + farmer_name);
}
})
});
You're not returning a promise that's resolved when all the work of your function is complete. If the work was completing in the past, that possibly just means you were lucky. Without returning a promise, Cloud Functions may terminate and clean up any work that wasn't complete when the function returns. Properly returning a promise will prevent Cloud Functions from cleaning up before the work is done.
Please consider reading my blog post about this. There is a section special just for ECONNRESET.

Github OAuth using Firebase - how to get user's username

I followed the Firebase's guide on how to authenticate with Github. https://firebase.google.com/docs/auth/web/github-auth
The return result from Firebase's signInWithRedirect method contains the user's displayName and email, etc. However, it doesn't seem to contain user's 'login' username which is the key for invoking most of Github's API calls.
I am sure there is a way to get it, but I just can't seem to find any documentation. Does anyone happen to know how to solve it?
I ended up using Github's API to get user's username with accessToken.
You should be able to get the user's GitHub username through a parameter called "username" (see more here: https://github.com/firebase/firebase-simple-login/blob/master/docs/v1/providers/github.md)
Note: firebase-simple-login was deprecated on October 3th, 2014
You can use get the authenticated user from this GitHub's api
Or if you use octokit javascript rest api client, you can do something like this
octokit = new Octokit({auth: userAccessToken })
octokit.users.getAuthenticated()
.then(result => {
console.log(result.data.login) // this is the username
})
Note: you'll get accessToken after GitHub <-> firebase login
Hope this is helpful!
You can get the username in additionalUserInfo:
const githubProvider = new firebaseClient.auth.GithubAuthProvider();
githubProvider.addScope('read:user');
githubProvider.setCustomParameters({
allow_signup: false,
});
firebaseClient.initializeApp(clientConfig);
async function submit() {
try {
const response = await firebaseClient
.auth()
.signInWithPopup(githubProvider);
console.log(response.additionalUserInfo);
} catch (error) {
alert(error);
}
}
You Can use email to do authorized requests insted username:
Username: mayGitHubEmail#mail.com
Password: accessToken
like this with Postman
body sent
Here is a sample using class func in Swift using Alamofire and SwiftyJSON pods:
import Alamofire
import SwiftyJSON
enum NetworkError: Error {
case url
case server
case auth
}
class GistServices {
class func makePostApiCall(toUrl path: String, withBody parameters: JSON, usingCredentials: Bool = false) -> Result<Data?, NetworkError> {
guard let url = URL(string: path) else {
return .failure(.url)
}
if let email = UserAuthSingleton.shared.get(), let password = UserAuthSingleton.shared.getUserToken() {
var result: Result<Data?, NetworkError>!
var request = AF.request(url, method: .post, parameters: parameters)
if(usingCredentials){
let credentialData = "\(email):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers = [HTTPHeader(name: "Authorization", value: "Basic \(base64Credentials)"),
HTTPHeader(name: "Accept", value: "application/json"),
HTTPHeader(name: "Content-Type", value: "application/json")]
request = AF.request(url, method: .post, parameters: parameters.dictionaryValue, encoder: JSONParameterEncoder.default, headers: HTTPHeaders(headers))
}
request
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { (response) in
switch response.result {
case .failure(_):
result = .failure(.server)
case .success(let value):
result = .success(value)
}
}
return result
}
return .failure(.auth)
}
}

Resources