🚀
Stellar Kickstart
  • 🏕️Welcome to the SCF Kickstart Week
    • 💰Funding Overview
    • ✍️Dear changemakers, visionaries, and problem solvers
    • ℹ️TL;DR: How to Maximize Your SCF Kickstart Week Experience
  • 📚Fundamentals of Integrating with Stellar
    • 🚀Stellar For
    • 🏗️Building with Stellar
    • 🔧Tools
    • 👷Resources
      • Fundamental Concepts
        • ⭐Introduction to the Stellar network
        • ⛓️Introduction to blockchain technology
        • 💵Introduction to payments in Stellar
        • 🧑Accounts
      • Core Features & Mechanisms
        • 🔐Assets: Powering Digital Value Exchange
        • Assets Issuance: Manage digital assets effortlessly on Stellar
        • 💸Transactions: At Stellar Core
        • 👮‍♂️Signatures in Stellar: Who, how much and to what is authorized
      • Payments & Transactions
        • 💰Payments: Simplifying Transactions with Stellar
        • ⛓️Path Payments: Convert Assets at Minimal Cost
        • ⛽Fee-Bump: How to pay for other people's transactions
      • Developer & Integration Tools
        • 👩‍🔬Stellar Laboratory: Stellar at hand for everyone
        • 🚪Faucet: Easy Access to Free Blockchain Assets
        • 🧰Stellar Wallets Kit: A kit to handle all Stellar Wallets at once with a simple API
        • ✍️Simple Signer: A wallet aggregator and transaction signer
      • Advanced Development & Testing
        • 🧪How to Create Integration Tests Using GitHub Actions and Stellar's Docker Image
  • 🎨Design Sprint
    • 🌅Introduction
    • 1️⃣Day 1 - Validate your problem and define your MVP's Scope
    • 2️⃣Day 2 - Build a prototype to validate with real users
    • 3️⃣Day 3 - Define the technical architecture
    • 4️⃣Day 4: Develop your Go To Market Strategy & Pitch Deck
    • 5️⃣Day 5: Compile all the information
    • 👀Sample Completed Design Sprint
Powered by GitBook
On this page
  • Revolutionizing Payments: Fast, Secure, and Accessible Transactions
  • Project Setup
  • Streaming Payments Across the Network
  • Retrieving a Defined Amount of Payments from the Network
  • Conclusion
  1. Fundamentals of Integrating with Stellar
  2. Resources
  3. Payments & Transactions

Payments: Simplifying Transactions with Stellar

PreviousPayments & TransactionsNextPath Payments: Convert Assets at Minimal Cost

Last updated 3 months ago

Revolutionizing Payments: Fast, Secure, and Accessible Transactions

In this article, we'll explore how to leverage our understanding of Stellar to make payments effortlessly, transforming the way we transfer value and connect financially across the globe.

Payments are essential for transferring value quickly and securely. They connect people and businesses worldwide, enabling peer-to-peer transactions, supporting business needs, and driving innovation. Digital payment solutions are reducing costs and improving accessibility, making financial services more inclusive and fostering economic growth.

Stellar emerges as a game-changer in this field, offering low-cost, fast, efficient, and secure transactions. It empowers cross-border payments by enabling seamless value transfer, connecting diverse financial ecosystems, and bridging gaps in global accessibility, all while fostering innovation and trust in financial operations.

Understand how payments drive real-world applications, enabling secure remittances to loved ones, seamless microtransactions for everyday needs, and instant settlements for businesses, all while promoting accessibility, efficiency, and global financial connectivity.

Through this understanding, we’ll dive into the methodology behind payments, exploring how you can easily harness these capabilities to send, receive, and manage value effectively in any context.

Project Setup

First of all, we need to start our setup to interact with the blockchain.

In your favorite work directory, create a folder named stellar-payments

mkdir stellar-payments
cd stellar-payments

Here, we are going to initialize the project.

npm init -y

To interact with the Stellar network, we'll need to install a dependency provided by Stellar called @stellar/stellar-sdk. This SDK will allow us to connect and perform transactions on the Stellar network.

Run the following command to install the package:

npm install @stellar/stellar-sdk

Now that we have our basic setup, we can start creating a payment transaction.

These accounts represent the user sending the payment and the recipient account.

------

Create an index.js file on your root directory, and let's start coding. This will be the entry point where we'll build the logic for the payment transaction.

touch index.js

Inside your index file, you should add the following code to set up a basic Stellar payment transaction:

import {
  Asset,
  BASE_FEE,
  Horizon,
  Keypair,
  Networks,
  Operation,
  TransactionBuilder,
} from "@stellar/stellar-sdk";

async function main() {
  const userSecret = "SDTS6KWIMTHAQTO6...";
  const destinationAccount = "GDVZB3TDOPTTQFYSUX65PLQBUYBXCEPB6F24GA6CCPZ6DBQ6MM2VTUWU";

  const server = new Horizon.Server("https://horizon-testnet.stellar.org");

  const asset = Asset.native();

  const userKeypair = Keypair.fromSecret(userSecret);

  const paymentOperation = Operation.payment({
    amount: "100",
    destination: destinationAccount,
    asset,
    source: userKeypair.publicKey(),
  });

  const accountInfo = await server.loadAccount(userKeypair.publicKey());

  const transaction = new TransactionBuilder(accountInfo, {
    fee: BASE_FEE,
    networkPassphrase: Networks.TESTNET,
  })
    .addOperation(paymentOperation)
    .setTimeout(30)
    .build();

  // Every Stellar transaction must be signed by the user's keypair, ensuring 
  // proper authorization. Alternatively, if you're using an external wallet 
  // connector, such as Bigger Simple Signer, the transaction will be signed 
  // by the wallet provider, keeping the user's private key secure and allowing 
  // for a seamless user experience.
  transaction.sign(userKeypair);

  try {
    const transactionResult = await server.submitTransaction(transaction);

    console.log(transactionResult.hash);
  } catch (error) {
    console.log(error);
  }
}

main();

To run this file you can use the following command:

node index.js

Streaming Payments Across the Network

Payments are commonly used to send assets or representations of FIAT currency across the network. To ensure recipients receive these payments in real time, the SDK provides a powerful method for streaming payments. This eliminates the need for repeated requests or manual UI updates after a few seconds, enabling a seamless and instant experience.

To stream payments from a transaction, you can either update the current file you're working on or create a new file called paymentStream

mkdir src
touch ./src/paymentStream.js

Once you have this file, paste the code inside and test it before making a payment.

import { Horizon } from "@stellar/stellar-sdk";

// This target wallet should be the wallet that is receiving the asset
const targetWallet = "GDVZB3TDOPTTQFYSUX65PLQBUYBXCEPB6F24GA6CCPZ6DBQ6MM2VTUWU";
const server = new Horizon.Server("https://horizon-testnet.stellar.org");
const serverPayments = server.payments().forAccount(targetWallet);

const payments = [];

serverPayments
  .cursor("now")
  .limit(1)
  .stream({
    onmessage: async (payment) => {
      if (payment.type !== "payment") {
        return;
      }

      payments.unshift(payment);

      const account = await server.loadAccount(targetWallet);

      console.log(account.balances);
    },
    onerror: (err) => {
      console.error(err);
    },
  });

This will ensure that whenever the server detects a payment operation on this wallet, the event will be streamed.

To run this file you can use the following command:

node ./src/paymentStream.js

Retrieving a Defined Amount of Payments from the Network

In some scenarios, instead of streaming payments in real time, you may want to retrieve a specific number of recent payments from the network. This allows you to track and analyze payment history based on your needs without continuously monitoring incoming transactions. With the Stellar SDK, you can easily query and fetch a set number of past transactions, providing a more controlled approach to managing payment data.

Create a file named lastPayments

touch ./src/lastPayments.js

And paste this code:

import { Horizon } from "@stellar/stellar-sdk";

// This target wallet should be the wallet that is receiving the token
const targetWallet = "GDVZB3TDOPTTQFYSUX65PLQBUYBXCEPB6F24GA6CCPZ6DBQ6MM2VTUWU";
const server = new Horizon.Server("https://horizon-testnet.stellar.org");
const serverPayments = server.payments().forAccount(targetWallet);

async function main() {
  const { records } = await serverPayments.order('desc').limit(5).call();

  console.log(records);
}

main();

This fetches the most recent 5 payments, sorted in descending order.

Run this by using:

node ./src/lastPayments.js

This will display the expected result in the console, and now we have access to this information to update the UI and enhance the user experience.

Conclusion

In this article, we’ve explored how Stellar is revolutionizing payments by providing a fast, secure, and low-cost method to transfer value across the globe. By leveraging the Stellar SDK, we've shown how easy it is to create and stream payment transactions, enabling real-time updates and seamless integration into your applications.

From setting up accounts on the Stellar testnet to making cross-border payments, and even streaming payments in real-time, we've covered the essential steps to harness Stellar’s capabilities in your projects. Whether for peer-to-peer transfers, microtransactions, or large-scale business settlements, Stellar simplifies financial interactions, making them more efficient and accessible for everyone.

As the world continues to shift towards digital financial solutions, Stellar’s infrastructure ensures that payments are not only faster and more secure but also more inclusive, bridging gaps in global financial accessibility. Now that you have the tools to build and streamline payments, you can start implementing this transformative technology in your own applications. Happy coding!

Resources:

For this, we’ll need two accounts funded on the Stellar testnet. You can create these accounts using the . If you're using Docker, you can fund your accounts by calling your local friendbot.

Now you're ready to make a payment across the network. Once the transaction is complete, you can check the updated balances for both the sender and receiver using the

📚
👷
💰
Stellar Laboratory
Laboratory
Github repository