Paytm Payment Gateway Integration with Symfony : Step by Step
In this tutorial we have explained Paytm Payment Gateway Integration in symfony. Paytm is the good choice for accepting payment online. It is safe, secure, and easy to integrate into website and mobile applications. Nowadays paytm is most popular and famous mobile wallet system. As per the company, over 7 million merchants across India use their QR code payment system to accept payments directly into their bank account.
Nowadays many ecommerce or other service websites start using Paytm payment gateway. Its also reduce the risk to exposing credit card details or banking password. Just send or receive payment via your Mobile Phone. So, no doubt Paytm is better service for online payment for your Website.
Benefits of using Paytm Payment Gateway
- Paytm accepts every mode of payment
- Paytm Wallet
- Bank account via UPI
- Debit or Credit cards
- Net Banking
- EMI Option on cards
- Paytm Postpaid
- Secure Payments
- Industry high success rate
- Checkout with saved cards
- Real-time bank settlements
- Business growth insights on Paytm Merchant Dashboard
Steps to Integrate Paytm Payment Gateway in PHP
Lets start the process of Paytm Payment Gateway Integration. Follow the below steps:
Step 1 : Register for Paytm Account
Sign Up for Paytm bussiness account from here :
https://paytm.com/business/payments/online
Step 2 : Configure Paytm Credential
Add following code in config.yml file.
parameters:
paytm_marchent_id: "YOUR_MERCHANT_ID" paytm_marchent_key: "YOUR_MERCHANT_KEY"
Step 3 : Create Paytm Integration Helper
Create helper into AppBundle->Helper->PaytmHelper.php
Add following code into PaytmHelper.php
<?php namespace AppBundle\Helper; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\JsonResponse; use AppBundle\Entity\User; class PaytmHelper { private $entityManager; private $container; public function __construct(EntityManager $entityManager, ContainerInterface $container, Session $session) { $this->container = $container; $this->entityManager = $entityManager; $this->session = $session; } //All Functions of Paytm Integration public function encrypt_e($input, $ky) { $key = html_entity_decode($ky); $iv = "@@@@&&&&####$$$$"; $data = openssl_encrypt ( $input , "AES-128-CBC" , $key, 0, $iv ); return $data; } public function decrypt_e($crypt, $ky) { $key = html_entity_decode($ky); $iv = "@@@@&&&&####$$$$"; $data = openssl_decrypt ( $crypt , "AES-128-CBC" , $key, 0, $iv ); return $data; } public function generateSalt_e($length) { $random = ""; srand((double) microtime() * 1000000); $data = "AbcDE123IJKLMN67QRSTUVWXYZ"; $data .= "aBCdefghijklmn123opq45rs67tuv89wxyz"; $data .= "0FGH45OP89"; for ($i = 0; $i < $length; $i++) { $random .= substr($data, (rand() % (strlen($data))), 1); } return $random; } public function checkString_e($value) { if ($value == 'null') $value = ''; return $value; } public function getChecksumFromArray($arrayList, $key, $sort=1) { if ($sort != 0) { ksort($arrayList); } $str = $this->getArray2Str($arrayList); $salt = $this->generateSalt_e(4); $finalString = $str . "|" . $salt; $hash = hash("sha256", $finalString); $hashString = $hash . $salt; $checksum = $this->encrypt_e($hashString, $key); return $checksum; } public function verifychecksum_e($arrayList, $key, $checksumvalue) { $arrayList = $this->removeCheckSumParam($arrayList); ksort($arrayList); $str = $this->getArray2StrForVerify($arrayList); $paytm_hash = $this->decrypt_e($checksumvalue, $key); $salt = substr($paytm_hash, -4); $finalString = $str . "|" . $salt; $website_hash = hash("sha256", $finalString); $website_hash .= $salt; $validFlag = "FALSE"; if ($website_hash == $paytm_hash) { $validFlag = "TRUE"; } else { $validFlag = "FALSE"; } return $validFlag; } public function getArray2Str($arrayList) { $findme = 'REFUND'; $findmepipe = '|'; $paramStr = ""; $flag = 1; foreach ($arrayList as $value) { $pos = strpos($value, $findme); $pospipe = strpos($value, $findmepipe); if ($pos !== false || $pospipe !== false) { continue; } if ($flag) { $paramStr .= $this->checkString_e($value); $flag = 0; } else { $paramStr .= "|" . $this->checkString_e($value); } } return $paramStr; } public function getArray2StrForVerify($arrayList) { $paramStr = ""; $flag = 1; foreach ($arrayList as $key => $value) { if ($flag) { $paramStr .= $this->checkString_e($value); $flag = 0; } else { $paramStr .= "|" . $this->checkString_e($value); } } return $paramStr; } public function removeCheckSumParam($arrayList) { if (isset($arrayList["CHECKSUMHASH"])) { unset($arrayList["CHECKSUMHASH"]); } return $arrayList; } public function VerifierChecksum($request){ $data = $request->request->all(); $JsonData =json_encode($data); $paytmChecksum = isset($data["CHECKSUMHASH"]) ? $data["CHECKSUMHASH"] : ""; $isValidChecksum = $this->verifychecksum_e($data, "&".$this->container->getParameter('paytm_marchent_key'), $paytmChecksum); return $isValidChecksum; } }
Step 4 : Create Paytm Entity
AppBundle->Entity->PaytmPayment.php
</pre> <?php namespace DirectoryPlatform\AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * PaytmPayment * * @ORM\Table(name="directory_platform_paytm_payment") * @ORM\Entity(repositoryClass="DirectoryPlatform\AppBundle\Repository\PaytmPaymentRepository") */ class PaytmPayment { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var int * * @ORM\Column(name="orderId", type="integer", length=255) */ private $orderId; /** * @var int * * @ORM\Column(name="userId", type="integer", length=255) */ private $userId; /** * @var int * * @ORM\Column(name="totalAmount", type="integer") */ private $totalAmount; /** * @var string * * @ORM\Column(name="currencyCode", type="string", length=255) */ private $currencyCode; /** * @var string * * @ORM\Column(name="clientEmail", type="string", length=255) */ private $clientEmail; /** * @var array * * @ORM\Column(name="description", type="json_array", length=255) */ private $description; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set orderId * * @param string $orderId * * @return PaytmPayment */ public function setOrderId($orderId) { $this->orderId = $orderId; return $this; } /** * Get orderId * * @return string */ public function getOrderId() { return $this->orderId; } /** * Set userId * * @param string $userId * * @return PaytmPayment */ public function setUserId($userId) { $this->userId = $userId; return $this; } /** * Get userId * * @return string */ public function getUserId() { return $this->userId; } /** * Set totalAmount * * @param integer $totalAmount * * @return PaytmPayment */ public function setTotalAmount($totalAmount) { $this->totalAmount = $totalAmount; return $this; } /** * Get totalAmount * * @return integer */ public function getTotalAmount() { return $this->totalAmount; } /** * Set currencyCode * * @param string $currencyCode * * @return PaytmPayment */ public function setCurrencyCode($currencyCode) { $this->currencyCode = $currencyCode; return $this; } /** * Get currencyCode * * @return string */ public function getCurrencyCode() { return $this->currencyCode; } /** * Set clientEmail * * @param string $clientEmail * * @return PaytmPayment */ public function setClientEmail($clientEmail) { $this->clientEmail = $clientEmail; return $this; } /** * {@inheritDoc} */ public function getClientEmail() { return $this->clientEmail; } /** * {@inheritDoc} * * @param array|\Traversable $description */ public function setDescription($description) { if ($description instanceof \Traversable) { $description = iterator_to_array($description); } $this->description = $description; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } } <pre>?>
Step 5 : Configure Order controller code
</pre> /** * @Route("/accounts/checkout", name="checkout") */ public function checkoutAction(Request $request) { $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath(); // Calculate total price $products = $request->getSession()->get('products'); if (!$products) { $this->addFlash('danger', $this->get('translator')->trans('Cart is empty. Not able to proceed checkout.')); return $this->redirectToRoute('cart'); } $price = 0; foreach ($products as $product) { $price += $product['price']; } // Save order if ($orderForm->isSubmitted() && $orderForm->isValid()) { $order = $orderForm->getData(); $order->setStatus(Order::STATUS_NEW); $order->setUser($this->getUser()); $order->setCurrency($this->getParameter('app.currency')); $order->setPrice($price); try { $em = $this->getDoctrine()->getManager(); $em->persist($order); $em->flush(); } catch (\Exception $e) { $this->addFlash('danger', $this->get('translator')->trans('An error occurred whe saving order.')); } // Save order items foreach ($products as $product) { $listing = $this->getDoctrine()->getRepository('AppBundle:Listing')->findOneBy(['id' => $product['listing_id']]); $orderItem = new OrderItem(); $orderItem->setOrder($order); $orderItem->setPrice($product['price']); $orderItem->setType($product['type']); $orderItem->setListing($listing); $orderItem->setDuration($product['duration']); try { $em = $this->getDoctrine()->getManager(); $em->persist($orderItem); $em->flush(); } catch (\Exception $e) { $this->addFlash('danger', $this->get('translator')->trans('An error occurred whe saving order item.')); } } $request->getSession()->remove('products'); $this->addFlash('success', $this->get('translator')->trans('Order has been successfully saved.')); $gatewayName = 'paytm_standard_checkout'; $storage = $this->get('payum')->getStorage(Payment::class); $payment = $storage->create(); $payment->setNumber(uniqid()); $payment->setCurrencyCode($this->getParameter('app.currency')); $payment->setTotalAmount($price * 100); $payment->setDescription('A description'); $payment->setClientId($order->getUser()->getId()); $payment->setClientEmail($order->getUser()->getEmail()); $payment->setOrder($order); $storage->update($payment); $captureToken = $this->get('payum')->getTokenFactory()->createCaptureToken($gatewayName, $payment, 'paytmcheckout'); $paytmParams = array( "MID" => $this->container->getParameter('paytm_marchent_id'), "WEBSITE" => "WEBSTAGING", "INDUSTRY_TYPE_ID" => "Retail", "CHANNEL_ID" => "WEB", "ORDER_ID" => ($order->getId()), "CUST_ID" => ($order->getUser()->getId()), "EMAIL" => ($order->getUser()->getEmail()), "TXN_AMOUNT" => ($price * 100), "CALLBACK_URL" => $baseurl.$this->generateUrl('paytmcheckout'), ); $checksum = $this->get('app.helper.paytm')->getChecksumFromArray($paytmParams, "&".$this->container->getParameter('paytm_marchent_key')); return $this->render('FrontBundle::Paytm/index.html.twig', ['paytmParams' => $paytmParams, 'checksum' => $checksum, ]); } return $this->render('FrontBundle::Order/checkout.html.twig', ['order' => $orderForm->createView()]); } /** * @Route("/accounts/paytmcheckout", name="paytmcheckout") */ //Paytm payment Response function and also use for databse entry. public function paytmcheckoutAction(Request $request) { $token = $this->get('app.helper.paytm')->VerifierChecksum($request); $status = $request->request->get('STATUS'); $orderId = $request->request->get('ORDERID'); $order = $this->getDoctrine()->getRepository('AppBundle:Order')->findOneBy(array('id' => $orderId)); if($token == "TRUE") { if ($status == "TXN_SUCCESS") { $order->setStatus(Order::STATUS_COMPLETED); $this->addFlash('success', $this->get('translator')->trans('Payment has been successful.')); }else{ $order->setStatus(Order::STATUS_CANCELED); $this->addFlash('danger', $this->get('translator')->trans('Payment has been Failed.')); } }else { $order->setStatus(Order::STATUS_CANCELED); $this->addFlash('danger', $this->get('translator')->trans('Payment has been Failed.')); } try { $em = $this->getDoctrine()->getManager(); $em->persist($order); $em->flush(); } catch (\Exception $e) { $this->addFlash('danger', $this->get('translator')->trans('An error occurred when saving object.')); } return $this->redirectToRoute('order'); } <pre>
Step 6 : Create twig file
</pre> {% extends 'FrontBundle::Layout/base.html.twig' %} {% block content %} <body> <form method="post" action="https://securegw-stage.paytm.in/order/process" name="f1"> <table border="1"> <tbody> {% for keyVal, paytmParam in paytmParams %} <input type="hidden" name="{{ keyVal }}" value="{{ paytmParam }}"> {% endfor %} <input type="hidden" name="CHECKSUMHASH" value="{{ checksum }}"> </tbody> </table> <script type="text/javascript"> document.f1.submit(); </script> </form> </body> {% endblock %} <pre>
Conclusion: I hope this tutorial helpful for you, if you have any issue with integration, please comment below.
Thank You!
38 thoughts
Hi! I just want to give you a huge thumbs up for your great info you have right here on this post.
I am coming back to your blog for more soon.
Review my web page – weed gummies (http://www.peninsuladailynews.com)
For most up-to-date information you have to pay a quick visit world wide web and
on web I found this web site as a best web site for most recent updates.
my web blog: delta 8 CBD
I like what you guys are up too. This type of clever
work and reporting! Keep up the amazing works guys I’ve
incorporated you guys to my own blogroll.
Look at my webpage delta 8 CBD (http://www.thedailyworld.com)
Hi there I am so thrilled I found your website, I really found
you by mistake, while I was searching on Askjeeve for something else, Nonetheless I am here now
and would just like to say many thanks for a marvelous post and
a all round exciting blog (I also love the theme/design), I don’t have time to read it all at
the moment but I have book-marked it and also added in your RSS feeds, so when I have time I will
be back to read much more, Please do keep up the superb work.
Feel free to surf to my homepage … delta 8 gummies;
Eliza,
I love looking through an article that can make men and women think.
Also, thanks for permitting me to comment!
Feel free to visit my blog post delta 8 CBD
You really make it seem so easy with your presentation but I find this topic to
be actually something that I think I would never understand.
It seems too complex and very broad for me. I am looking forward for your next post,
I will try to get the hang of it!
My site delta 8 gummies
I’m no longer certain where you’re getting your info, however good
topic. I must spend some time finding out more or working out more.
Thank you for magnificent information I used to be on the lookout for this
info for my mission.
Feel free to surf to my page – THC Gummies
Hey there! Do you know if they make any plugins to safeguard against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
my site; delta 8 THC (https://bit.ly/)
You ought to be a part of a contest for one of the most useful blogs on the internet.
I’m going to highly recommend this web site!
My web page; THC Gummies
Very nice post. I simply stumbled upon your blog and wanted to mention that I’ve
really loved surfing around your weblog posts.
After all I’ll be subscribing to your rss feed and
I’m hoping you write again soon!
my blog post … Best THC Gummies
Thanks for one’s marvelous posting! I really enjoyed reading it, you could be a great author.
I will be sure to bookmark your blog and will eventually
come back sometime soon. I want to encourage continue your great work, have a nice weekend!
My web blog: Best THC Gummies [Margot]
Link exchange is nothing else but it is simply
placing the other person’s weblog link on your page at suitable place and other person will also do same in favor of
you.
Also visit my homepage – buy weed near me
Greetings! This is my first visit to your blog! We are
a group of volunteers and starting a new initiative in a community in the
same niche. Your blog provided us beneficial information to work on. You have done a marvellous
job!
Also visit my web site: delta 8 THC
Wonderful work! That is the type of information that are supposed to
be shared around the internet. Disgrace on the seek engines for now not positioning this post upper!
Come on over and seek advice from my site . Thanks =)
Here is my blog :: Best delta 8 gummies Observer; bit.ly,
Good day! I just wish to give you a big thumbs up for your excellent information you have right here on this post.
I will be coming back to your site for more soon.
Here is my blog post buy weed online
I think this is among the most significant info for me.
And i’m glad reading your article. But should remark on some general things,
The site style is great, the articles is really
excellent : D. Good job, cheers
my blog post THC Gummies
Hi! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly?
My website looks weird when viewing from my iphone4.
I’m trying to find a template or plugin that might be able to resolve this issue.
If you have any recommendations, please share.
Appreciate it!
my webpage – Observer [bit.ly]
I like the helpful information you provide in your articles.
I’ll bookmark your weblog and check again here frequently.
I’m quite certain I’ll learn plenty of new stuff right here!
Good luck for the next!
Visit my webpage: US Magazine
Usually I don’t read article on blogs, but I wish to say that this write-up very pressured me to check out and do it!
Your writing taste has been surprised me. Thanks, quite great article.
My webpage :: weed near me
It’s amazing in favor of me to have a site, which is beneficial in favor of my knowledge.
thanks admin
My site; dispensaries near me
Excellent post but I was wondering if you could write a litte more on this
topic? I’d be very grateful if you could elaborate a little bit further.
Thank you!
Feel free to visit my webpage – buy Instagram followers; radaronline.com,
Usually I do not learn post on blogs, but I would like to say that this write-up very forced me to try and do so!
Your writing taste has been amazed me. Thank you, quite
nice article.
Also visit my page best delta 8 gummies
It’s actually a cool and useful piece of information.
I am happy that you simply shared this useful info with us.
Please stay us informed like this. Thanks for sharing.
Here is my website: buy weed
Excellent web site. A lot of useful information here. I’m sending
it to several pals ans additionally sharing in delicious.
And naturally, thanks for your sweat!
Also visit my page buy weed
A person essentially assist to make critically articles I’d state.
This is the first time I frequented your website page and so far?
I surprised with the analysis you made to make this particular post extraordinary.
Wonderful activity!
Here is my web blog :: best cbd gummies for pain
Hi there, just became alert to your blog through Google, and found that it is really
informative. I’m gonna watch out for brussels. I will be grateful if you continue this in future.
A lot of people will be benefited from your writing.
Cheers!
my website: where to buy pure cannabis oil
It’s truly a great and useful piece of info.
I’m happy that you simply shared this useful information with us.
Please stay us up to date like this. Thanks for sharing.
Feel free to visit my webpage – best kratom
Thanks in support of sharing such a fastidious idea, article is pleasant, thats why i have read it entirely
Feel free to surf to my web site :: cbd for sale
If you desire to grow your experience simply keep visiting
this website and be updated with the most up-to-date gossip posted here.
my site – cannabis oil cancer where to buy
This is a topic that’s near to my heart… Best wishes!
Exactly where are your contact details though?
Also visit my web site – cbd oil for anxiety near me
My brother suggested I might like this website. He was entirely right.
This post actually made my day. You cann’t imagine just
how much time I had spent for this info! Thanks!
Here is my web-site … best kratom
I have read some excellent stuff here. Certainly worth bookmarking
for revisiting. I wonder how so much effort you set to create one of these excellent
informative web site.
Also visit my page … Herald Net
This is very interesting, You’re a very skilled blogger.
I’ve joined your feed and look forward to seeking more of your magnificent post.
Also, I’ve shared your website in my social networks!
my blog post … cbd capsules For pain
I’m gone to tell my little brother, that he should also visit this blog on regular basis to take updated
from latest information.
Feel free to visit my web page … kush burst delta 8 500mg
I’m extremely pleased to find this website. I wanted to thank you for your time for this fantastic read!!
I definitely liked every part of it and i also have
you book marked to check out new things on your blog.
My website :: Delta 8 Thc Carts
Hey there, You’ve done a great job. I’ll definitely digg it and personally recommend to my friends.
I’m confident they will be benefited from this web site.
Have a look at my page :: bellevue reporter
Wow! This blog looks exactly like my old one! It’s on a completely different topic but it has pretty much the same layout
and design. Outstanding choice of colors!
My web-site: area52
I really enjoy the blog article.Really thank you! Really Cool.