I have made a cloud function to create and complete a payment request to square connect API.
This is the function:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var SquareConnect = require("square-connect");
var defaultClient = SquareConnect.ApiClient.instance;
exports.sqProcessPayments = functions
.region("europe-west1")
.firestore.document("users/{userId}")
.onUpdate(async (change, context) => {
var accessToken = "access--token";
let previousData = change.before.data();
let updatedData = change.after.data();
let previousNonce = previousData["payment_nonce"];
let updatedNonce = updatedData["payment_nonce"];
if (previousNonce !== updatedNonce) {
var oauth2 = defaultClient.authentications["oauth2"];
oauth2.accessToken = accessToken;
var idempotencyKey = new Date();
var apiInstance = new SquareConnect.PaymentsApi();
var body = new SquareConnect.CreatePaymentRequest({
source_id: updatedNonce.toString(),
idempotency_key: idempotencyKey.toString(),
amount_money: {
amount: 10,
currency: "USD",
},
location_id: "location-id",
autocomplete: true,
});
apiInstance
.createPayment(body)
.then(
function (data) {
console.log(
"API called successfully. Returned data: " + data.payment.id
);
return data;
},
function (error) {
console.error(error);
}
)
.catch((error) => console.log(error));
}
});
But I am getting this error on running this function
'{"errors": [{"code": "EXPECTED_STRING","detail": "Expected a string value (line 1, character 14)","field": "source_id","category": "INVALID_REQUEST_ERROR"}]}\n'
I have checked the value of source_id
and it is a string. But the error says otherwise.
Please help me resolve this. Any help would be great.
Thanks for your time!
I have found this in CreatePaymentRequest code. This problem is related with creation of body
object.
I think proper syntax will be:
var body = SquareConnect.CreatePaymentRequest.constructFromObject({
source_id: updatedNonce.toString(),
idempotency_key: idempotencyKey.toString(),
amount_money: {
amount: 10,
currency: "USD",
},
location_id: "location-id",
autocomplete: true,
});
Or you can use:
var body = new SquareConnect.CreatePaymentRequest(
updatedNonce.toString(),
idempotencyKey.toString(),
amount_money: {
amount: 10,
currency: "USD",
}
)
but in this situation you can only add source_id
, idempotency_key
and amount_money
. Nothing more...