You will discover how to incorporate UPI Payment Gateway into your Flutter app in this article.
Payment gateways are now an essential component of mobile applications due to the increase in online transactions. Customers can instantly transfer money between bank accounts in India using the UPI (Unified Payment Interface) payment gateway without any hassle. A great way to give your users a safe and practical payment option is by integrating UPI payment gateway in a Flutter app. We will go over the exact steps for integrating a UPI payment gateway in a Flutter app in this blog post.
Requirements for UPI payments gateway 👍 in flutter
Make sure you have the following prerequisites before we begin:
Setup of the Flutter development environment on your computer
A tool or emulator to test the application
having a functional UPI payment gateway account
Step to Implement UPI Payment in Flutter App
Step 1) : project with the plugin upi_india add this dependency in pubspec.yaml file
upi_india: ^any
Step2) :Run the flutter pub get command to install the plugin after adding the dependency.
Step 3) : import the package named upi_India
We must import the upi_india package in our Dart file after adding the upi_india plugin to the project.
import 'package:upi_india/upi_india.dart';
Step 4) : Initialize UpiIndia
The UpiIndia object needs to be initialized with the necessary configuration information after the upi_india package has been imported. The amount to be transferred, the recipient’s UPI ID, the transaction note, and the payment app the user will use to complete the transaction are all included in the configuration information. An illustration of how to initialize UpiIndia is given below:
The UpiIndia object is initialized in the code above with a payment of 10 INR to be sent to example@upi. The payment will be made using the Amazon Pay app, and the transaction note is set to “Test Transaction”.
Step 5) : Handle the UPI payment response
The user will be redirected to the UPI payment gateway app to complete the transaction after the payment has been started. The user will be directed back to our app once the transaction has been completed. To ascertain whether the transaction was successful or not, we must manage the UPI payment response. The onTransactionResponse and onTransactionError listeners of the UpiIndia object can be used to handle the payment response. An example of how to handle the payment response is given below:
upi.onTransactionResponse.listen((transactionDetails) {
print("Transaction done successfully :: ${transactionDetails.toString()}");
});
upi.onTransactionError.listen((error) {
print("Transaction failed with this error :: ${error.toString()}");
});
In the code above, we are watching for the UpiIndia object’s onTransactionResponse and onTransactionError events. The onTransactionResponse event is triggered if the transaction is successful.
Finally, call the initiateTransaction method when the user clicks on the payment button:
onPressed: () {
initiateTransaction();
},
child: Text("Pay with UPI"),
That’s it! You have successfully integrated the UPI payment gateway in your Flutter app using the upi_india plugin.
Additionally, the upi_india plugin offers a getAllUpiApps method that can be used to obtain a list of all UPI apps that are currently installed on the user’s device. This method is helpful for showing the user a list of UPI apps and allowing them to select their preferred app for the transaction.
It is more assential part of flutter application to integratr UPI payment gateway in online mode.
The upi_india plugin handles UPI transactions and provides callbacks for transaction success and failure, making it simple to integrate the UPI payment gateway in a Flutter app.
Hi Guys, Welcome to Proto Coders Point, In this short article let’s checkout how to generate a random number between 1 and 10 or between any range you want iun javascript.
In JavaScript, To generate a random number between 1 and 10, we can make use of Math.random() function and by applying a bit of math operation.
Basically ‘Math.random()’ function will generate a random decimal floating number range from 0.0 to 1.0 and thus we need to multiple the generate number by 10 and round it to the nearst integer number by using Math.floor() function.
Here is a example
var rand = Math.random();
console.log(rand); //0.7520321036592579
let random_number = Math.floor(rand * 10) + 1;
console.log(random_number); // 8
In above code, Math.random() function will generate random number from 0.0 to 1.0 [ 0.7520… is the generated number], then to make it range between 1 – 10 I am multiply it with 10 and add 1 to it because math.floor will round to 1 – 9.
Javascript random number between 1 and 100
Now say you want to generate a number between 1 to 100, so can we acheived by just modifying the scaling and shift value i.e just be multiplying the random number generated by 100 and adding 1 to it . For example:
let randomNumber = Math.floor(Math.random() * 100) + 1;
console.log(randomNumber);
Hi Guys, Welcome to Proto Coders Point, This short article on “Python random between 0 and 1”.
In Computer Science, Random Number Generation is key concept. While building any kind of application there is a need somewhere of random number between 0 and 1 python, might be for simulate events, encrypt data, statistical analysis.
In Python to generate a random number between 0 and 1, we can make use of python ‘random’ module
The `random` module in python is a built-in library that provide a functionality like generating random number. To generate a random number between 0 and 1, we can use random() function, which will return a decimal point number range from 0.0 to 1.0.
random number between 0 and 1 python example
import random
random_number = random.random()
print(random_number) // 0.8046595183024017
As you can see, In above code I have firstly imported random module then used to generate a random number from 0.0 to 1.0 and thus the random number is printed in console using print().
Hi Guys, Welcome to Proto Coders Point, In this Flutter Article let’s checkout how to generate a random word in flutter dart. first by picking a randon word from a given list and second exampe by using a word_generator flutter library.
Generate random nouns example in flutter dart
Below is an dart program example to generate random nouns:
In above Program we have a list of noun words created, Then we make use of Random class from math package that will generate a random number from 0 to the length of the list, and thus us use this random number and retrieve a noun list index and print it on console.
Flutter dart program to generate a random word
In above program we saw that we created a list of word and randomly pick a word from the list, but suppose you want to generate a random word without predefined list of words.
Here is one way by by which we can generate random nouns or words without using pre-defined words list is by using flutter word generator library.
First add the dependency in your flutter project
open pubspec.yaml file and under dependencies section add:
The below Code will generate a random name using word generator package, We need to make the username in such a ways that it dont contain space and should be in lowercase.
Hi Guys, Welcome to Proto Coders Point, In this article let’s checkout how to convert celsius to fahrenheit in all programming languages.
Here is a formula to convert a temperature from Celsius to Fahrenheit:
°F = (°C x 1.8) + 32
The temperature is expressed in degrees Celsius and degrees Fahrenheit in the equations above, respectively.
We have Temperature in form of Celsius, By using above formula, first simple multiple the Celsius temperature by 1.8 & then add 32. The Total we get is the temperature in Fahrenheit unit.
Example
To convert a temperature of 31 degrees Celsius to Fahrenheit, the formula used is as follows:
°F = (31 x 1.8) + 32 °F = 55.8 + 32 °F = 87.8
Therefore, we get result after converting 30 degrees Celsius is equivalent to 87.8 degrees in Fahrenheit.
C Program to convert a temperature in Celsius to Fahrenheit
#include <stdio.h>
int main() {
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 1.8) + 32;
printf("%.2f Celsius is equivalent to %.2f Fahrenheit", celsius, fahrenheit);
return 0;
}
C++ Program to convert a temperature in Celsius to Fahrenheit
#include <iostream>
using namespace std;
int main() {
float celsius, fahrenheit;
cout << "Enter temperature in Celsius: ";
cin >> celsius;
fahrenheit = (celsius * 1.8) + 32;
cout << celsius << " Celsius is equivalent to " << fahrenheit << " Fahrenheit" << endl;
return 0;
}
Java Program to convert a temperature in Celsius to Fahrenheit
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
float celsius, fahrenheit;
Scanner input = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
celsius = input.nextFloat();
fahrenheit = (celsius * 1.8f) + 32;
System.out.printf("%.2f Celsius is equivalent to %.2f Fahrenheit", celsius, fahrenheit);
}
}
Python Program to convert a temperature in Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 1.8) + 32
print("{:.2f} Celsius is equivalent to {:.2f} Fahrenheit".format(celsius, fahrenheit))
Javascript Program to convert a temperature in Celsius to Fahrenheit
let celsius = parseFloat(prompt("Enter temperature in Celsius: "));
let fahrenheit = (celsius * 1.8) + 32;
console.log(celsius + " Celsius is equivalent to " + fahrenheit.toFixed(2) + " Fahrenheit");
Dart Program to convert a temperature in Celsius to Fahrenheit
import 'dart:io';
void main() {
stdout.write('Enter temperature in Celsius: ');
double celsius = double.parse(stdin.readLineSync()!);
double fahrenheit = (celsius * 1.8) + 32;
print('$celsius Celsius is equivalent to ${fahrenheit.toStringAsFixed(2)} Fahrenheit');
}
GO Language Program to convert a temperature in Celsius to Fahrenheit
package main
import (
"fmt"
)
func main() {
var celsius float64
fmt.Print("Enter temperature in Celsius: ")
fmt.Scanln(&celsius)
fahrenheit := (celsius * 1.8) + 32
fmt.Printf("%.2f Celsius is equivalent to %.2f Fahrenheit", celsius, fahrenheit)
}
Kotlin Program to convert a temperature in Celsius to Fahrenheit
fun main() {
print("Enter temperature in Celsius: ")
val celsius = readLine()!!.toFloat()
val fahrenheit = (celsius * 1.8) + 32
println("%.2f Celsius is equivalent to %.2f Fahrenheit".format(celsius, fahrenheit))
}
NodeJS - AWS S3 Bucket Like Service without using AWS
Now a days Cloud Storage has became an essential part of a modern world in software development, There are various third party service that provide cloud storage like AWS S3, Google Cloud Storage, Microsoft Azure Blob Storage, OpenStack Swift and more. But what if you want to build your own cloud storage system that can be crucial to make sure that the cloud storage service application runs smoothly and efficiently. In this Article we will learn how to build a scalable cloud storage system using NODEJS.
How to build cloud storage using NodeJS at backend
Building a fresh new cloud storage backend application using NodeJS is an challenging task, but no worry it’s possible to create our own NodeJS AWS S3 bucket like service without using any third party services.
Here are step to be follow:
System Requirement: Start planning a system configuration that is need to work the cloud storage service smoothly, you need to configure system or Cloud Instance like RAM, Storage(amount of storage), Server speed, bandwidth and type of data user can store.
Project Architecture: Based on the System Requirement, you can design the architecture on your cloud storage system project, Like you must decide on type of servers & where you are going to store the data(storage space), the mechanism to retrieval of data and a API for accessing system.
Database: Select a database so that you can store metadata of files and folders that will get uploaded by the user. In our project we are using MongoDB a NoSQL database to store the record of upload files.
Implement Features: Implement features such as creating a folder/bucket, getting list of all the folders, getting a list of files in a folder, downloading uploaded files from a folder using an API, and deleting a file from a given folder.
Test and deployment: Test the cloud storage system to ensure it works as expected and deploy it to a server or cloud platform server instance.
Note: Building a secured cloud storage system from scratch is a complex process and you may need a complete dedicated team to make it secured. This project is for learning purpose only.
Creating a Cloud Storage Service Similar to AWS S3 Bucket using NodeJS
How to create node js project
Create a folder & open it in visual studio code, then to make it a NodeJS project run below command:
node init-y
the above command will convert a normal folder into nodejs project where it will create a file by name name “package.json”.
Installing node libraries
Below are list to nodejs libraries/module that are required to build cloud storage system:
Express: Express is basically used in Node.js for creating application at backend and is used to created API’s.
fs(file system): The fs (file system) module used to interact with file system like accessing file, reading content of file and writing to a file, FS library is an in-build NodeJS library to interact with system files.
body-parser: The body-parser is middleware functionality used in Node.js applications usually used to parse incoming request bodies in a middleware before your handlers, and then allowing you to access request data in a more convenient way.
crypto-js: Crypto-js is a node.js library basically used for data encryption and hashing technique it support algorithms such as AES,MD5-SHA-1, SHA-256 and more.
path: The path module is used to get the file & directory paths in nodeJS.
mongoose: Mongoose is a NodeJS Mongodb library that helps in communication with MongoDB database, it’s helps in creating schema model and to interact with MongoDB database server. Used to perform CRUD operation with mongodb database.
multer: Multer is used to handle all the incoming file uploads, Multer is an middleware using which we can upload single and multiples files.
run below command to install all the above libraries into your nodejs project:
NodeJS Project Structure for build cloud storage system
Here in my node.js project I have create folder to give a proper structure to node project:
model: Here we have 2 database schema model i.e. user model & upload model.
middleware: In middleware folder will have functionality like user authentication using APIKEY & multer middleware that will help you in uploading files.
config: In this folder will have database connectivity configuration.
bucketFolder: is a root folder where user can create folders and upload files
routes: In router we will make use of express to create API routers that can perform event like Create a Bucket/Folder, Getting List of Bucket/Folder, Get list of files from particular bucket, upload file, download files and delete files.
API Routers created using Express routers
Below are the api route that will help user in performing event like:
Creating a Bucket / Folder.
Getting list of all bucket / Folder.
Uploading Files to a Bucker / Folder.
Getting list of Files from a particular bucket / Folder.
Downloading Files from a Bucket.
Deleting a file from a bucketing
Deleting a bucket / Folder.
1. NodeJS API to Create a Folder
Video Tutorial
The below code will create a user desired folder. To achieve this we will make use of fs library with fs.mkdirSync(<folderName>) to create a folder. In below code first I am checking if folder exist with same name or no using fs.existsSync(), if not then use fs.mkdirSync then create.
The below code will give us list of all folder, For this we will make use of fs.readdir() function to read files & folder exist within a given path and then we need to filter out and check if the file is directory or a file by using fs.statSync(filePath).isDirectory();.
3. Node.JS API to Upload Any kind of file/document into a folder
Video Tutorial
The below api router has a ability to upload any kind of file into a folder, Here to upload a file we have made use of multer middleware that will upload a single file to a desired bucket/folder and the same uploaded file details(metadata) record is been stored into mongodb database.
const fs = require('fs');
const { upload } = require('../config/multerConfig')
const UploadModel = require('../model/uploads.model');
//Upload Files to a Bucket and store same to Mongo DB
router.post("/uploadFileInBucket", Auth.userAuthMiddleWare, upload().single("myFile"), async (req, res) => {
if (req.file) {
const filefullPath = req.file.destination + req.file.filename;
const uploaded = new UploadModel({ userId: req.user._id, filename: req.file.filename, mimeType: req.file.mimetype, path: filefullPath });
await uploaded.save();
res.json({ status: true, success: "File Uploaded Successfully" });
}
});
4. Getting list of all Files from a particular bucket / Folder.
Video Tutorial
The below code will give us list of all the files that exist in a folder, For this we will make use of fs.readdir() function to read files & folder exist within a given path and then we need to filter out the files by check if the file is a directory or a file by using fs.statSync(filePath).isFile().
// get list of all files from a Particular bucket
router.get("/getAllFilesFromParticularBucket", Auth.userAuthMiddleWare, async (req, res) => {
try {
const bucketName = req.body.bucketName;
const directoryPath = path.join(`bucketFolder/${bucketName}`);
fs.readdir(directoryPath, (err, files) => {
if (err) {
return res.json({ status: false, message: `${bucketName}, No Such Bucket Found` });
}
const allfiles = files.filter(file => {
const filePath = path.join(directoryPath, file);
return fs.statSync(filePath).isFile();
});
console.log(allfiles);
return res.json({ status: true, filesList: allfiles });
});
} catch (error) {
console.log("error------->>", error);
}
});
5. Node.JS API to download a file from a bucket
Video Tutorial
The below API is but different, user can pass the folderName and fileName in API URL itself, and then the file will get downloaded from a directory by using fs.createReadStream with pipe response function.
//download a Files from a Bucket
router.get('/downloadFile/:filename/:folderName', Auth.userAuthMiddleWare, (req, res) => {
const { filename, folderName } = req.params;
const filePath = `bucketFolder/${folderName}/${filename}`;
if (!fs.existsSync(filePath)) {
return res.status(404).json({ message: 'File not found' });
}
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
const fileStream = fs.createReadStream(filePath);
fileStream.pipe(res);
});
6. Node.JS API to delete a file from a folder
Video Tutorial
To delete any file from a folder in nodejs we make use of fs library unlink() function, that will simple delete a files.
// This will delete Files from a given Bucket/folder
router.post("/deleteFileBucket", async (req, res) => {
const folderName = req.body.folderName;
const fileName = req.body.fileName;
if (!folderName) {
return res.json({ status: false, message: "Folder Name is Mandatory" });
}
if (!fileName) {
return res.json({ status: false, message: "File Name is Mandatory" });
}
const rootFolder = "bucketFolder";
const folderpath = `${rootFolder}/${folderName}/${fileName}`;
try {
fs.unlink(folderpath, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File deleted successfully');
});
return res.json({ status: true, success: "File deleted successfully" });
} catch (error) {
return res.json({ status: false, success: error });
}
});
7. Nodejs API to delete a folder
Video Tutorial
Note: the below api can only delete a folder is if it’s empty, if the folder is no empty then you need to first make it empty and then delete the folder.
To delete a folder we can make use of fs.rmdirSync() function, here you just need to pass folder path.
// Delete Folder/Bucket only if it Empty
router.post("/deleteFolderBucket", async (req, res) => {
const folderName = req.body.folderName;
if (!folderName) {
return res.json({ status: false, message: "Folder Name is Mandatory" });
}
const rootFolder = "bucketFolder";
const folderpath = `${rootFolder}/${folderName}`;
try {
if (fs.existsSync(rootFolder)) {
if (fs.existsSync(folderpath)) {
fs.rmdirSync(folderpath);
return res.json({ status: true, success: "Directory Deleted" });
}
}
return res.json({ status: false, success: "Directory Not Found" });
} catch (error) {
return res.json({ status: true, success: "Directory can't be deleted because it Not Empty" });
}
});
Complete Source Code – Build cloud storage system like AWS using NodeJS
Clone the complete project from my github repository for free, please give a star for the repo.