Unable to load the payment options in paytm js checkout - javascript

I am working with Paytm gateway and I want to implement JS Checkout, but I'm unable to load the banks and options of payment.
Below is all the code that I'm using:
async function onScriptLoad(){
var data = await fetch(`http://localhost:5000/api/payment`,{
method:"GET",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
}).then(response=>response.json()).catch(err=>console.log(err));
var Jsondata = JSON.parse(data)
console.log(JSON.parse(data))
var token = await fetch(`https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=Muctvj23768431537109&orderId=${Jsondata.body.orderId}`,{
method:"POST",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
body:data
}).then(response=>response.json()).catch(err=>console.log(err));
console.log(token)
var config = {
"root": "",
"flow": "DEFAULT",
"data": {
"orderId": Jsondata.body.orderId, /* update order id */
"token": token, /* update token value */
"tokenType": "TXN_TOKEN",
"amount": "1.00" /* update amount */
},
"payMode": {
"order": ['CARD']
},
"handler": {
"notifyMerchant": function(eventName,data){
console.log("notifyMerchant handler function called");
console.log("eventName => ",eventName);
console.log("data => ",data);
}
}
};
if(window.Paytm && window.Paytm.CheckoutJS){
window.Paytm.CheckoutJS.onLoad(function excecuteAfterCompleteLoad() {
// initialze configuration using init method
window.Paytm.CheckoutJS.init(config).then(function onSuccess() {
// after successfully updating configuration, invoke JS Checkout
console.log("success")
window.Paytm.CheckoutJS.invoke();
}).catch(function onError(error){
console.log("error => ",error);
});
});
}
}
I am new to this; any assistance would be greatly appreciated.

Please check whether you are using the correct mid and other configurations or not. If details are correct please raise a query at Paytm Developers support

Related

I want to pass a dynamic json body to the cypress request() function & define payload values

I'm new to cypress, so I apologize if I make no sense here.
i have a cypress script that does a POST request. My end goal is to check API validations. whether API responds with correct error messages for a given JSON body. for that, I want to pass the same JSON body with different values to the cypress request function.
I have my JSON object in a different js file. (channel_query.js)
export const CreateChannel = {
"name": "channe Name",
"tagline": "tasdsadsaest",
"date": "03 Mar 2021",
"time": "2.00 p.m",
"beginsOn": "2021-03-04T13:59:08.700",
"expiresOn": "2021-05-28T14:54:08.700",
"description": "sample Descritptin",
"url": "www.google.com"}
I have my cypress request in the integration folder (channel.js)
import { CreateChannel } from '../queries/channel_query';
it('Create a channel',function() {
cy.request({
method: 'POST',
url: '{my URL}',
body: CreateChannel ,
headers: headers
}).then((response) => {
expect(response.status).to.eq(201)
expect(response.body.name).to.eq(CreateChannel.name)
})
}) })
My question is,
How to make values in JSON object dynamic & then define them in the cypress request function? so I can pass the same JSON to check different validations.
#Mr. Gleb Bahmutov
Help is much appreciated guys!
The simplest way might be to place an array of channels in the JSON file and make the test data-driven.
export const channelData = [
{
"name": "channe Name",
... // plus other properties
},
{
"name": "name2",
... // plus other properties
},
]
The test
import { channelData } from '../queries/channel_query';
describe('Test all channels', () => {
channelData.forEach((channel, index) => {
it(`Testing channel "${channel.name}"`, function() {
cy.request({
method: 'POST',
url: '{my URL}',
body: channel,
headers: headers
}).then((response) => {
expect(response.status).to.eq(201)
expect(response.body.name).to.eq(channel.name)
})
})
})

Stripe php integration Error: ReferenceError: sessionId is not defined

I'm stuck at integrating stripe's prebuild payment gateway to my project.
I'm coding very simple Eshop (without login/registration and shopping cart) just a simple project with a form and stripe checkout as a way to pay...
I was following official stripe documentation but I struggle to find an answer how to implement their "simple prebuilt checkout page" to procedural PHP.
Currently I'm stuck on getting this error...the provided code is what I have used from their official documentation "still getting error ReferenceError: sessionId is not defined in the console in devtools ://
Also IDK how to configure endpoint on my server when coding it all without PHP framework such as Slim/Laravel...al examples provided by stripe use Slim framework when configuring endpoints....any ideas?
<?php
//config PHP
require_once("vendor/autoload.php");
// === SET UP STRIPE PAYMENT GATEWAY ===
$stripe = [
"secret_key" => "sk_test_4eC39HqLyjWDarjtT1zdp7dc",
"publishable_key" => "pk_test_TYooMQauvdEDq54NiTphI7jx",
];
\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>
<?php
//create-checkout-session.php
require_once '_includes/config.php';
// ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => 'http://localhost:8888/Avanza---Eshop/success.php?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'http://localhost:8888/Avanza---Eshop/canceled.php',
'payment_method_types' => ['card'], //, 'alipay'
'mode' => 'payment',
'line_items' => [[
'amount' => 2000,
'currency' => 'usd',
'name' => 'mikina',
'quantity' => 1,
]]
]);
header('Content-type: application/json');
echo json_encode(['sessionId' => $checkout_session['id']]);
<!--order.php actual page that will be displayed to users-->
<button style="width: 100px; height: 100px" id="checkout-button"></button>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe('pk_test_51HjoRfIaBaXJG6udQspXdLRNwMesCriMwZoR7nGCF0hZtu2Zp9FUxCFWwVpwwU4BZs7fTxJtYorVTuoK1vqXp2Uw002r6qvmO7'); // removed for Stackoverflow post
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function() {
// Create a new Checkout Session using the server-side endpoint you
// created in step 3.
fetch('create-checkout-session.php', {
method: 'POST',
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: sessionId});
})
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
</script>
I think you need to replace return stripe.redirectToCheckout({ sessionId: sessionId}); with return stripe.redirectToCheckout({ sessionId: session.sessionId});
It's worked for me. If you see more errors or face any problems, loot at the browser console Network tab.
$(function() {
var stripe = Stripe('<?= Config::STRIPE_PUB_KEY ?>'); // here write: pk_test_5...
$(document).on('click', '.buy_now_btn', function(e) {
let id = $(this).attr('id');
$(this).text('Please wait...');
$.ajax({
url: 'action.php',
method: 'post',
data: {
id: id,
stripe_payment_process: 1
},
dataType: 'json',
success: function(response) {
console.log(response);
return stripe.redirectToCheckout({
sessionId: response.id
});
},
})
})
});

how to do nativescript paytm integration

i have checked the native-script-paytm integration plugin. but both git-hub repository are not running instead it gives stack exception. so i created my own project and some how its doing something. but here i have lot of questions on how to get 'mid', 'order id' etc.
can anyone give step by step details for this.
const createViewModel = require("./main-view-model").createViewModel;
const Paytm = require("#nstudio/nativescript-paytm").Paytm;
const paytm = new Paytm();
exports.pageLoaded = function (args) {
const page = args.object;
page.bindingContext = createViewModel();
}
exports.onPayWithPaytm = function (args) {
console.log("Paying");
paytm.setIOSCallbacks({
didFinishedResponse: function (response) {
console.log("got response");
console.log(response);
},
didCancelTransaction: function () {
console.log("User cancelled transaction");
},
errorMissingParameterError: function (error) {
console.log(error);
}
});
const order = {
// This will fail saying duplicate order id
// generate your own order to test this.
MID: "Tomcas09769922377481",
ORDER_ID: "ORDER8874",
CUST_ID: "CUST6483",
INDUSTRY_TYPE_ID: "Retail",
CHANNEL_ID: "WAP",
TXN_AMOUNT: "10.00",
WEBSITE: "APP_STAGING",
CALLBACK_URL: "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp",
CHECKSUMHASH:
"NDspZhvSHbq44K3A9Y4daf9En3l2Ndu9fmOdLG+bIwugQ6682Q3JiNprqmhiWAgGUnNcxta3LT2Vtk3EPwDww8o87A8tyn7/jAS2UAS9m+c="
};
paytm.createOrder(order);
paytm.initialize("STAGING");
paytm.startPaymentTransaction({
someUIErrorOccurred: function (inErrorMessage) {
console.log(inErrorMessage);
},
onTransactionResponse: function (inResponse) {
console.log(inResponse);
},
networkNotAvailable: function () {
console.log("Network not available");
},
clientAuthenticationFailed: function (inErrorMessage) {
console.log(inErrorMessage);
},
onErrorLoadingWebPage: function (
iniErrorCode,
inErrorMessage,
inFailingUrl
) {
console.log(iniErrorCode, inErrorMessage, inFailingUrl);
},
onBackPressedCancelTransaction: function () {
console.log("User cancelled transaction by pressing back button");
},
onTransactionCancel: function (inErrorMessage, inResponse) {
console.log(inErrorMessage, inResponse);
}
});
}
For reference
As mentioned in the plugin's ReadMe file,
You will need a working backend server to generate paytm orders. Do not generate the order or checksum in the app.

Write Form Data from my Chrome Extension to Google Sheets

Updated with snippets and today's progress:
I am writing a Chrome Extension that is essentially a popup with a form, and I would like to write data entered into that form into Google Sheets. Currently, my extension consists of a manifest.json and a popup script, and a background script.
manifest.json (relevant pieces):
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{ "js": ["content.js"], "matches": ["<all_urls>"] }],
"permissions": [
"tabs",
"storage",
"<all_urls>",
"identity",
"https://*.googleapis.com/*"
]
popup.js (note: this is an extension to track MS symptoms)
const app = {
symptoms: [],
init: function () {
//cache some element references
let formEl = document.getElementById("symptoms-form");
let fatigue = document.getElementById("fatigue");
let tingling = document.getElementById("tingling");
let weakness = document.getElementById("weakness");
let vision = document.getElementById("vision");
let dizzy = document.getElementById("dizzy");
let cognition = document.getElementById("cognition");
let depression = document.getElementById("depression");
let balance = document.getElementById("balance");
//upon submit, update symptoms obj and send to background
formEl.addEventListener("submit", ev => {
ev.preventDefault();
console.log('button click')
this.symptoms.push({fatigue: fatigue.value})
this.symptoms.push({tingling: tingling.value})
this.symptoms.push({weakness: weakness.value})
this.symptoms.push({vision: vision.value})
this.symptoms.push({dizzy: dizzy.value})
this.symptoms.push({cognition: cognition.value})
this.symptoms.push({depression: depression.value})
this.symptoms.push({balance: balance.value})
// chrome.runtime.sendMessage({fn: 'getSymptoms'}, function(response) {
// console.log('popup got response', response)
// })
chrome.runtime.sendMessage({fn: 'setSymptoms', symptoms: this.symptoms})
});
}
}
document.addEventListener('DOMContentLoaded', () => {
app.init();
})
background.js - note: my current workaround is to load the data into Firebase, which you will see below:
console.log("Background running");
const background = {
symptoms: [],
init: function() {
//listen for any messages and route them to functions
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.fn in background) {
background[request.fn](request, sender, sendResponse);
}
const jsonObj = {}
jsonObj['symptoms'] = request.symptoms
console.log("message received", jsonObj);
this.postSymptoms(jsonObj)
});
},
postSymptoms: function(msg) {
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://ms-mysymptoms-1541705437963.firebaseio.com/symptoms.json", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(msg);
}
};
background.init();
I have set up a new project in the Google Developers console, enabled the Google Sheets API, and set up my credentials and API token. I tested in the Google API explorer that the authentication is set up properly and I can, indeed, write a row to my sheet. This is great news!
I am blocked right now on how to do this (write the data), directly from my Chrome extension. So far, I have saved all my credentials, set up a config file, and wrote my append method in a separate file locally.
sheets.js:
const {authorize, google} = require('./config')
const fs = require('fs')
const spreadsheetId = '---removed for this post--'
const append = (range, values) => {
fs.readFile('client_secret.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), (auth) => {
const sheets = google.sheets({
version: 'v4',
auth
});
const valueInputOption = 'USER_ENTERED';
const resource = {
values
};
sheets.spreadsheets.values.append({
spreadsheetId,
range,
valueInputOption,
resource
}, (err, result) => {
if (err) {
console.log(err);
} else {
console.log("Success!");
}
});
});
});
}
// module.exports = {
// append
// };
When I try to integrate this code into my popup script, however, I encounter an error because in order to reference that config data and that append method, I have to use require in my popup script. Since the popup script is running in the browser, I can't use require (without webpack, that is).
I'm sure I'm going about this all wrong, so I could use a push in the right direction as to how to authenticate and append to Sheets from the browser if my configuration and authentication are stored in local files on my computer.
Solutions I've considered:
1 - spin up a REST API, post the data from the form to that endpoint, and have it act as a proxy to the Google Sheets API - this is not ideal.
2 - use webpack so that I can use require in my popup file
What would be the recommended way to do this? How should I integrate authentication and working with the Google Sheet into this extension?
Writing to a spreadsheet with Google's API is a PUT not a POST.
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update
I had success with this using chrome.identity.getAuthToken, then running a fetch with the following:
chrome.identity.getAuthToken({interactive: true}, function(token) {
var params = {
'values': [
['Row 1 Col A','Row 1 Col B'],
['Row 2 Col A','Row 2 Col B'],
]
};
let init = {
method: 'PUT',
async: true,
body: JSON.stringify(params),
headers: {
Authorization: 'Bearer ' + token,
Content-Type': 'application/json'
},
contentType: 'json',
};
fetch('https://sheets.googleapis.com/v4/spreadsheets/***YOUR SHEET ID****/values/****YOUR RANGE*****?valueInputOption=USER_ENTERED&key=***YOUR API KEY***', init)
.then((response) => response.json())
.then(function(data) {
//console.log(data);
//Returns spreadsheet ID, update tange, cols and rows
});
})
});
That's all in the background script, where I've put Row 1 Col A etc as the values, that'll be the first cell of your range.
Hope that helps.
Careful! If you want to append data, the ? query parameter comes after the :append.
fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${range}:append?valueInputOption=${valueInputOption}`, init)

Parse Cloud Code - Add To Array

Tried loads of different variations with my cloud code and I can't get it to work. Basically I've got a push notification function, and in this function I want to add an object to a PFUser's array, but you can't use a master key in Xcode so here's what I have:
Parse.Cloud.define("iOSPush", function (request, response) {
console.log("Inside iOSPush");
var data = request.params.data;
var not_class = request.params.not_class;
var not_objectid = request.params.not_objectid;
var not_date = request.params.not_date;
var userid = request.params.userid;
var recipientUser = new Parse.Query(Parse.User);
recipientUser.equalTo("objectId", userid);
// set installation query:
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo('deviceType', 'ios');
pushQuery.matchesQuery('user', recipientUser);
pushQuery.find({ useMasterKey: true }).then(function(object) {
response.success(object);
console.log("pushQuery got " + object.length);
}, function(error) {
response.error(error);
console.error("pushQuery find failed. error = " + error.message);
});
// send push notification query:
Parse.Push.send({
where: pushQuery,
data: data
}, { useMasterKey: true }).then(function() {
console.log("### push sent!");
// create notification:
var notification = {
"title": not_class,
"body": request.params.data.alert,
"class": not_class,
"objectId": not_objectid,
"date": not_date
};
// get notifications:
var tmp_notifications = recipientUser.get("notifications");
// add notification:
tmp_notifications.push(notification);
// update with notifications:
recipientUser.set("notifications", tmp_notifications);
recipientUser.save();
}, function(error) {
console.error("### push error" + error.message);
});
response.success('success. end of iospush');
});
The Xcode cloud function I have provides the correct information, the function gets to the end.. just the function is not setting the notifications for some reason
I ended up figuring out the answer to this post myself. The reason this didn't work is because I needed to first fetch the user object in a separate query, then save it using the master key. I also found out that there's a function for appending data onto an existing array without having to create another one (parseObject.add()):
var userQ = new Parse.Query(Parse.User);
userQ.get(userid, {
success: function(theuser) {
console.log("### got userrrrrrrrrr!");
theuser.add("notifications", n_object);
theuser.save(null, {useMasterKey:true});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
This set of code was executed just before:
response.success('success. end of iospush');

Categories

Resources