Implementation in PHP for uploading a file to AWS S3

Implementation in PHP for uploading a file to AWS S3
The need to store users’ files is a necessary part of maintaining a software application. These user files can be anything such as images, videos, or PDFs. App creators usually save such files on the server. But, at a certain point in time, the amount of data becomes massive or there might be a need to store very large files. Such scenarios can be effectively handled using AWS S3, a dedicated file-uploading service. It’s a web-based Cloud storage service by Amazon. It comes with web service interfaces based on REST and SOAP. With S3, the task of file uploading becomes easier and quicker.
This post provides you with step-by-step guidance on how to upload files to AWS S3 in PHP. Here, we’ve considered how to upload file to AWS S3 in Laravel and PHP. Laravel is a PHP web development framework.
Before we dive deeper into the topic, let me provide you with some insights on certain crucial aspects you need to know before commencing the actual process of uploading your files to AWS S3.

Reasons to upload files to AWS S3

So, why is it a best practice to upload files to AWS? This approach is one of the most viable solutions to store data securely in the Cloud and manage this data effectively. Take a look at the reasons:

Unlimited Storage

The Cloud storage service AWS S3 supports mass data storage in Cloud-native apps and solutions. It allows infinite storage for data and objects. Different data types and formats are supported. So, users do not require to add more storage volumes to their already existing file storage infrastructure. You can store any file sized between 0 bytes and 5 gigabytes. AWS S3 stores data in the form of objects in S3 Buckets.

Reliability & Scalability

The Cloud storage service AWS S3 is reliable and scalable. You can store huge chunks of data and retrieve this data very easily. Also, with AWS S3, it becomes easy to download and upload huge files without having to worry about network bandwidth problems or storage limitations. Besides data storage, it also provides data backup and recovery options.

Laravel Integration

Laravel Integration is a boon as this robust framework supports AWS S3 integration by default. Laravel comes with multiple built-in features that are compatible with AWS S3. The storage façade is an example. Laravel integration simplifies the tasks of file downloading, file uploading, and file management in your application, with the help of a simple & consistent API.

Versioning

AWS S3 supports versioning. This means the different variants of an object or a file can stay within the same bucket. And, if you remove an object or a file by mistake, there’s the option for recovery or rollback. With AWS S3, you can also manage an object’s non-current version, if you have implemented the expiration lifecycle policy for that object.

High-grade Security

High-grade security is one of the most desirable offerings. AWS S3 offers built-in security features such as access control, strong encryption, etc. It comes with multiple certifications for security and regulatory compliances. This way, your data is protected against security vulnerabilities. Also, you can comply with the regulatory protocols mandated in your area without much ado. Files uploaded to AWS S3 are fully secure and least likely to face security issues like unauthorized access.

Cost-efficiency

AWS S3 is one of the most cost-efficient ways of file storage and file management. Here, the user requires to pay only for storing and transferring the data they use. It’s way less expensive than configuring and managing in-house storage infrastructure.

We can use following way to implement AWS S3 upload in Laravel:

    • Install following package-
composer require aws/aws-sdk-php-laravel “~3.0”
composer require league/flysystem-aws-S3-v3l “^1.0”
composer require league/flysystem-cached-adapter “~1.0
    • Create new library for AWS connection.

\app\LibrariesAwsUtility.php

    • ENV variables-

#Client info

AWS_ACCESS_KEY_ID=AKIAQQP246GMXXHSNV5I

AWS_SECRET_ACCESS_KEY=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

AWS_DEFAULT_REGION=us-west-2

AWS_BUCKET=dynafios-development-app-storage

END_POINT=https://dynafios-development-app-storage.S3.us-west-2.amazonaws.com

AWS_USE_PATH_STYLE_ENDPOINT=false

    • To upload report –

//For AWS File Upload-need to include

use App\Libraries\AwsUtility;

//Start S3 bucket url change aws – nvn

$storage_path_file_path=$report_path.’/’.$report_filename;

$awsObj_result = AwsUtility::awsUploadSubmit($storage_path_file_path);

$effectiveUri=$awsObj_result->getData()->effectiveUri;

//End S3 bucket url change aws – nvn

//To save URL path in DB-

$hospital_report->awsfilename = $effectiveUri;

a- We have created temp folder in

storage\temp

b- When report is generated the name is saved in the database and file is saved in temp folder. Now for uploading to AWS bucket we use temp path and after uploading we remove the temp path.
As per requirement.
  • For download, we use function from LibrariesAwsUtility.php and download on the fly temporary url that does not exist after download.

//S3 file download from bucket–nvn

$awsObj_result_down = awsUtility::awsDownloadTempUrl($filename);

$effectiveUri_arr = $awsObj_result_down->getData()->effectiveUri;

$onlyfilename = $awsObj_result_down->getData()->onlyfilename;

if ($effectiveUri_arr == “Failed”) {

//In case URL not saved or link break

$S3fileDownlaod = “Failed”;

return Redirect::back()->with([

//”error” => Lang::get(“hospital.S3_filenot_found_uploaded”),

“error” => “File Not Found!!”,

]);

//REDIRECT WITH MESSAGE

}

$filename = $onlyfilename;

$tempfile = tempnam(sys_get_temp_dir(), $filename);

//COPY SIGNED URL TO TEMP FOLDER

copy($effectiveUri_arr, $tempfile);

return response()->download($tempfile, $filename);

  • For delete we use function from LibrariesAwsUtility.php which delete file from aws but not from db. As per requirment.

// aws S3 file delete

$awsObj_result_del = awsUtility::awsDeleteFile($filename);

if (isset($awsObj_result_del)) {

// Log::Info(‘Deleted S3 File!HospitalController-getDeleteReport() ‘);

return Redirect::back()->with([

“success” => Lang::get(“hospitals.delete_report_success”),

]);

} else {

return Redirect::back()->with([

“error” => Lang::get(“hospital.delete_report_error”),

]);

}

return Redirect::back()->with([

“success” => Lang::get(“hospitals.delete_report_success”),

]);

Alternatively you can use Laravel’s File System as well, to upload file to AWS S3.

File can be uploaded to AWS S3 in Core PHP as below:

    • Install AWS S3 PHP SDK
composer require aws/aws-sdk-php
    • Create File Upload Form
    • upload-to-S3.php file

require ‘vendor/autoload.php’;

use Aws\S3\S3Client;

// Instantiate an Amazon S3 client.

$S3Client = new S3Client([

‘version’ => ‘latest’,

‘region’ => ‘YOUR_AWS_REGION’,

‘credentials’ => [

‘key’ => ‘ACCESS_KEY_ID’,

‘secret’ => ‘SECRET_ACCESS_KEY’

]

]);

// Check whether file exists before uploading it

if(move_uploaded_file($_FILES[“anyfile”][“tmp_name”], “upload/” . $filename)){

$bucket = ‘YOUR_BUCKET_NAME’;

$file_Path = __DIR__ . ‘/upload/’. $filename;

$key = basename($file_Path);

try {

$result = $S3Client->putObject([

‘Bucket’ => $bucket,

‘Key’ => $key,

‘Body’ => fopen($file_Path, ‘r’),

‘ACL’ => ‘public-read’, // make file ‘public’

]);

echo “Image uploaded successfully. Image path is: “. $result->get(‘ObjectURL’);

} catch (Aws\S3\Exception\S3Exception $e) {

echo “There was an error uploading file.\n”;

echo $e->getMessage();

}

echo “Your file was uploaded successfully.”;

}else{

echo “File is not uploaded”;

}

In Conclusion

I hope you are now well-versed in uploading a file to AWS S3 using PHP or Laravel. However, if you lack the necessary technical expertise, you can seek professional help from an experienced Software development company for integrating PHP or Laravel code for uploading file using AWS S3.

ACH Payment Processing: All you Need to Know!

ACH Payment Processing: All you Need to Know!
ACH Payment Process
Consumers these days have multiple options to make the payments like cash, debit cards, checks, bill pay, prepaid cards, money orders, contactless purchase methods, wire transfers, credit cards, direct transfers, ACH, etc.
Now, let’s understand more about ACH payments. ACH transfers have gained traction in recent years. Statistics researched by the financial regulatory body nacha.org reveal that “7.3 billion payments were executed using the ACH network during the first quarter of 2022.”
This post provides all-inclusive information on ACH transfers. So, catch glimpses of what is an ACH transaction, how it functions, and why it proves beneficial to users. A quick read will give you an idea of how to set up an ACH payment processing mechanism for your business organization.

What is ACH Payment Processing?

ACH transactions are electronic money transfers from one bank to the other that are processed through the ACH network. ACH or “Automated Clearing House” is a US-based financial network that is used for carrying out money transfers and electronic payment transactions in the USA. ACH payments, also known as “direct payments,” make transfers between bank accounts without cash, wire transfers, paper checks, or credit card networks.
The ACH network is actually a batch processing system as payment transactions are processed in batches. Banks and other financial entities employ this system to aggregate the transactions that need to be processed. This centralized clearing system tracks the transactions happening between different banks and at the end of the day calculates how much money each bank owes to the other. Based on this data, funds are transferred to the respective banks, only once, instead of executing multiple transfers throughout the day.
Such payments are processed as credit or as debit. For credit payments, the payer initiates the transaction and the money gets deposited in the payee’s bank account. For debit transactions, money gets withdrawn from the payer’s bank account. The consumers who sign themselves up for automatic bill payment/pre-authorized debit instead of credit/debit cards are actually using the ACH model of payment transaction methodology.
The entire payment processing system is managed by NACHA (National Automated Clearing House Association). NACHA is a self-regulatory non-profit organization that supervises these payment transactions and devises rules for this payment model. NACHA is funded by financial institutions in the US.

What are the different types of ACH transactions?

  • Direct payments & IRS payments
  • eCheque transactions
  • One-time or recurring payments into an IRA (Individual Retirement Account), savings account, taxable brokerage account, etc.
  • Funds transfer between banks using payment gateways like PayPal, Venmo, etc.
  • Businesses paying vendors and suppliers for products/services
  • Businesses receiving payments from customers/clients
  • Online bill payment through bank accounts
  • Employees receiving direct salary deposits from employers

How do ACH Transfers differ from Wire Transfers?

Many confuse ACH transfers with Wire transfers as Wire transfers are also electronic payments that take place between banks. But, ACH transfers are quite different from wire transfers. Let’s explore!
For wire transfers, both the sender and the receiver have to pay money transfer charges; the average fees are up to $14 for domestic transactions and up to $75 for international transfers. ACH transfers, on the contrary, do not charge fees from the receiver and the sender has to pay minimal charges, approximately $1. Wire transfers are processed in real-time by the bank staff and so money transactions take place instantly. Contrarily, ACH transfers are processed in batches and as such, may take a few business days to execute. However, ACH transactions do not require any human intervention. Wire transfers cannot be canceled or disputed once they get initiated while ACH transfers can be disputed if the relevant conditions are fulfilled.
Therefore, the ACH model is more profitable and productive unless you need to transfer money immediately. Nevertheless, same-day or next-day ACH money transfer services are also available in exchange for a minimal processing fee.

How to implement the ACH Payment Model via the ACH Network?

To implement the ACH model, you will need to use the Automated Clearing House (ACH) network, which is a network that facilitates the electronic transfer of funds between banks.
Here are the steps to implement this payment model:
Obtain a merchant account with a bank or payment processor that offers an ACH model of payment processing.
Set up your business’s bank account to receive the payments.
Provide your customers with the necessary information to add ACH to your business’s bank account. This may include your bank account number and routing number, as well as the name and address of your bank.
When a customer wants to make a payment to your business using the ACH model, they will need to provide their bank account information and the amount of the payment.
You will then process the payment through the ACH network by providing the customer’s bank account information and the amount of the payment. The ACH network will verify the customer’s bank account and transfer the funds from their account to your business’s account.
Once the payment has been processed, you will receive a notification and the funds will be deposited into your business’s bank account.

How to integrate ACH Payment Processing?

Below is the example code for payment processing following the ACH model:

# Importing the essential libraries

import requests

import json

# Configuringthe endpoint URL

ENDPOINT_URL = https://api.example.com/ach/payments

#Setting up the API key

API_KEY = “your_api_key_here”

# Configuring the bank account information of the sender and the recipient

sender_account = {

“account_number”: “1234567890”,

“routing_number”: “123456789”,

“account_type”: “checking”

}

recipient_account = {

“account_number”: “0987654321”,

“routing_number”: “987654321”,

“account_type”: “savings”

}

# Configuring the amount to be paid

amount = 100.00

# Generating the payload for executing the API request

payload = {

“sender_account”: sender_account,

“recipient_account”: recipient_account,

“amount”: amount

}

# Configuring the API request headers

headers = {

“Content-Type”: “application/json”,

“Authorization”: f”Bearer {API_KEY}”

}

# Sending the API request for payment processing

response = requests.post(ENDPOINT_URL, json=payload, headers=headers)

# Verifying the status code of the response

if response.status_code == 200:

# Generating the transaction ID if the payment processing gets successfully executed

transaction_id = response.json()[“transaction_id”]

print(f”Payment processed successfully. Transaction ID: {transaction_id}”)

else:

# Generating the error message, if the payment processing fails

error_message = response.json()[“error”]

print(f”Payment failed. Error: {error_message}”)

ACH Payment: Benefits for Businesses & Consumers

Cost-Savings

Payment processing through paper cheques, debit/credit cards, etc. involves high processing fees; it’s more so with debit & credit cards as a certain percentage of the transaction amount is charged as a fee. As a result, businesses incur huge expenses during high-value transactions. The ACH model, on the other hand, involves much lower processing charges. In the case of paper cheques, although the processing fee is less, labor charges add up to the total expenses. Hence for businesses, specifically those that involve high-amount transactions, payment processing using ACH turns out to be the most profitable option.

Speedy, Hassle-free, & Accurate Payment Processing

Businesses that use paper cheques must consider the ACH model of payment transactions owing to its speed of transaction, ease of usage, and accuracy as compared to paper-based cheques. The usage of ACH cheques saves time wasted on bank trips and involves a speedier processing time than traditional bank cheques. Also, paper checks involve lengthy processing times that may result in delayed payments.
Besides, electronic cheques are easier to handle as they do not have to be entered manually and cannot get lost. ACH cheques resolve another bottleneck associated with paper-based cheques: chances of human errors. And, human errors cost businesses money as well as their precious time. Automatic funds processing without human intervention zeros down any chances of errors and hence, no time has to be devoted to fixing errors.

Automates Recurring Transactions

Recurring billing is an integral part of business enterprises that operate on the subscription model, as consumers have to pay bills regularly. Recurring billing involves several challenges. To begin with, businesses have to incur high fund processing expenses due to the frequency of transactions. Moreover, consumers are likely to forget to pay their bills at times, leading to unpaid invoices as well as irregular cash inflow.
Well, the ACH model is the ideal solution for both of these aforesaid woes. As already discussed, entrepreneurs save on transaction charges with the ACH methodology because of lower fund processing fees. Furthermore, as ACH is an automated process, customers need not remember to pay their bills or initiate payment processing. Once they sign themselves up for automatic bill payment, the bill amount gets debited from their bank account whenever the payment is due. As such, consumers benefit from this payment model.
ACH saves merchants the hassles of repeatedly reminding consumers for paying bills or charging extra for late payments. Moreover, there are hardly any chances of friction between businesses and their consumers. These result in improved relationships, increased customer satisfaction, and more conversions in the long run.

High-end Security

The financial information of consumers and online monetary transaction data is a soft target of cyber attackers for carrying out fraudulent practices. Therefore, minimizing the chances of payment fraud should be the key priority of businesses these days.
Cheque payments are not recommended due to the high possibility of data leaks, forgery, etc. Moreover, cheques reveal additional client information besides their bank account number; like names and addresses. Today, virtual cards, credit cards, and ACH payments are considered secure. However, several customers are reluctant to share their credit card information owing to safety issues. Nevertheless, with ACH, transactions are executed remotely without any need for giving out the financial information of customers.
ACH is the most secure payment option available as it offers high-grade security practices. ACH transactions pass through a clearinghouse that ensures the confidentiality of the bank account numbers of consumers. The clearinghouse also provides a recovery period of 60 days if there is any incident of fraudulent or erratic transactions.

Hassle-free Payment Transaction Management

The payment model streamlines payment transaction functions. Since banks are synced with the system, transaction record data gets automatically fed into the system without any need for human intervention. An electronic record gets created for each transaction made and the transaction history can be accessed at a later date using software tools for accounting, and financial management. This way, tracking expenses, and income become a breeze. Automation outshines manual data entry tasks as businesses can avoid involving extra resources and rule out chances of costly manual errors.

Bottomline:

ACH payment processing brings a lot to the table for business enterprises. It caters to all kinds of payment transactions including payroll deposits, bill payments, tax refunds, and retirement distributions. Any type of business, whether big or small, profits from the ACH model of payment processing. Moreover, if you are associated with a SaaS business model, there can be no better option than the ACH model of payment.
Remember to implement the ACH model as per the mandated standards and follow all security practices. Would you like to create a payment processing app but lack the necessary technical expertise or software resources? Well, it’s advisable to seek assistance from an experienced web and mobile app development company for establishing the ACH infrastructure and maintaining it.