<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eyuelhaile on Medium]]></title>
        <description><![CDATA[Stories by Eyuelhaile on Medium]]></description>
        <link>https://medium.com/@eyuelhaile29?source=rss-ad9b12bd0403------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m7Ej-tEywza8wLC0LZsfdw.jpeg</url>
            <title>Stories by Eyuelhaile on Medium</title>
            <link>https://medium.com/@eyuelhaile29?source=rss-ad9b12bd0403------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:51:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eyuelhaile29/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Integrate Chapa Payment Gateway to your Reactjs/Nextjs App]]></title>
            <link>https://medium.com/@eyuelhaile29/how-to-integrate-chapa-payment-gateway-to-your-reactjs-nextjs-app-81cfd6ac54a1?source=rss-ad9b12bd0403------2</link>
            <guid isPermaLink="false">https://medium.com/p/81cfd6ac54a1</guid>
            <dc:creator><![CDATA[Eyuelhaile]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 10:59:06 GMT</pubDate>
            <atom:updated>2023-10-20T10:59:06.756Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to Integrate Chapa Payment Gateway to your Reactjs/Nextjs App</strong></p><p>My name is Eyuel Haile</p><ul><li>A Full-stack Web Developer</li><li>Microsoft Certified</li><li>Developed more than 10 commercial web and mobile applications</li></ul><p>I’ll walk you through the entire process of using <a href="https://chapa.co/">Chapa Checkout</a> with <a href="https://nextjs.org/">Next.js</a> in this article.</p><h3>Introduction</h3><p>Chapa is an easy-to-integrate Payment Processing Platform for <strong>Ethiopian Businesses</strong>. Chapa is a secure and user-friendly payment platform that allows you to easily send and receive money electronically. With Chapa, you can make fast and convenient transactions using your mobile device or computer. Whether it’s for personal or business purposes, Chapa ensures that your payments are processed securely and efficiently.</p><h3><strong>Let’s Start Building</strong></h3><p><strong>Installation</strong></p><p>To install Next.js, follow these steps:</p><ol><li>Ensure you have Node.js installed on your system. You can check by running node -v in your command line. If Node.js is not installed, download and install it from the official <a href="https://nodejs.org/en">Node.js website</a>.</li><li>Navigate to your project directory by running cd projectFolderin your command line.</li><li>Now, create a new Next.js app using npx or yarn.</li></ol><pre>npx create-next-app@latest checkout --use-npm --example &quot;https://github.com/vercel/next-learn/tree/main/basics/learn-starter&quot;<br><br>yarn create next-app checkout --use-npm --example &quot;https://github.com/vercel/next-learn/tree/main/basics/learn-starter&quot;</pre><p>After you have finished creating the project, you can open it in Visual Code by running the command “code .” in your command line. Additionally, you can install the default dependency packages by executing the provided command.</p><pre>npm install</pre><p>To install the necessary packages for this project, execute the following commands either on your command line or in the Visual Studio terminal:</p><ol><li>Use Axios to send and receive requests to and from the server.</li><li>Use uuid and uuid-validate to generate random strings that act as reference numbers for the Chapa payment gateway. A new reference number should be created for each request.</li></ol><pre>npm install axios<br><br>npm install uuid<br><br>npm install uuid-validate</pre><p>Now You have successfully installed all the required dependencies. To proceed, please navigate to Chapa&#39;s Official website h<a href="https://chapa.co/">ttps://chapa.co/</a>, and create a new account by providing the necessary information in the designated fields.</p><p>Upon signing up, you will be provided with access to the test mode environment. To gain access to the production mode, you will need to submit your business information and undergo the verification process.</p><p>After successfully creating the account, go to the settings page and access the API tab. Here, you will find your <strong>Secret Key,</strong> <strong>Public Key</strong>, and <strong>Encryption Key</strong>. <em>It is essential that you do not disclose this information to anyone else</em>.</p><p>Next, proceed to create a new file named “.env.local” within the root folder of your project, Please add the following line of code inside .env.local, ensuring to replace both keys with the ones you obtained from the Chapa Settings page API tab.</p><pre>CHAPA_SECRET_KEY=CHASECK_TEST-fxyBJbwndsfhlnbladffkdfhdghfkfhd<br>CHAPA_PUBLIC_KEY=CHAPUBK_TEST-CyTYSNjgfdhgGGHGfgfgGFGFHGjfgfGG</pre><p>To create the checkout page, replace the pre-existing code in the <strong><em>pages/index.js</em></strong> file with the provided code below. Doing so will enable you to create the checkout page. Keep in mind that you also have the option to design your own custom checkout page if desired.</p><pre>import Head from &#39;next/head&#39;;<br>import styles from &#39;../styles/Home.module.css&#39;;<br>import { v4 as uuidv4 } from &#39;uuid&#39;;<br>import axios from &#39;axios&#39;;<br><br>export default function Home() {<br>  const cart  = [{<br>    id : 1,<br>    title : &quot;Mens Black SHoes&quot;,<br>    price : 1200<br>    <br>  },{<br>    id : 2,<br>    title : &quot;Womens red dress&quot;,<br>    price : 3000<br>    <br>  },{<br>    id : 3,<br>    title : &quot;Mens Watches&quot;,<br>    price : 5000<br>    <br>  }]<br>  const handleChapa = async () =&gt; {<br>    const referenceNumber = uuidv4();<br>    const header = {<br>        headers: { <br>            &quot;Content-Type&quot;: &quot;application/json&quot;<br>         },     <br>    };<br>    <br>    const body = {<br>       amount: cart.reduce((total, item) =&gt; total + item.price, 0), //Amount should be integer<br>       currency: &quot;ETB&quot;,<br>       email: &quot;test@gmail.com&quot;,<br>       first_name: &quot;Eyuel&quot;,<br>       last_name: &quot;Haile&quot;,<br>       phone_number: &quot;0917000000&quot;, //the phone number must not include +251<br>       tx_ref: referenceNumber,<br>       callback_url: &quot;http://localhost:3000/success&quot;,<br>       return_url: &quot;http://localhost:3000/varifyChapa?tnx_ref=&quot;+referenceNumber,<br>       customization: {<br>        title: &quot;Item Payment&quot;,<br>        description: &quot;Paying for item in the cart&quot;<br>       }<br>    }<br>    let response = await axios.post(`http://localhost:3000/api/chapa`, body, header);<br>    //console.log(response.data.data.checkout_url);<br>    window.location.href = response.data.data.checkout_url;<br> }<br>  return (<br>    &lt;div className={styles.container}&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Create Next App&lt;/title&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br><br>      &lt;main&gt;<br><br>        &lt;div className={styles.grid}&gt;<br>          &lt;div className={styles.card}&gt;<br>            &lt;h3&gt;Checkout Page &lt;/h3&gt;<br>            {cart.map((item) =&gt;  (<br>              &lt;div className={styles.title} style={{justifyContent:&quot;space-between&quot;}}&gt;<br>                &lt;span style={{float:&quot;left&quot;}}&gt;{item.title}&lt;/span&gt;<br>                &lt;span style={{float:&quot;right&quot;}}&gt;{item.price} ETB&lt;/span&gt;<br>              &lt;/div&gt;<br>            ))}<br>            &lt;div className={styles.title} style={{justifyContent:&quot;space-between&quot;}}&gt;<br>                &lt;span style={{float:&quot;left&quot;}}&gt;Total&lt;/span&gt;<br>                &lt;span style={{float:&quot;right&quot;}}&gt;{cart.reduce((total, item) =&gt; total + item.price, 0)} ETB&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;button<br>              type=&quot;button&quot;<br>              className={styles.btn}<br>              onClick={handleChapa}<br>            &gt;<br>              Pay with <br>              &lt;img<br>                  src=&quot;/images/chapa.svg&quot;<br>                  alt=&quot;chapa image&quot;<br>                  style={{<br>                    width: &quot;100px&quot;,<br>                    paddingLeft: &quot;15px&quot;,<br>                    paddingTop: &quot;5px&quot;<br>                  }}<br>                /&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The <strong>cart array</strong> consists of a sample list of items along with their respective prices and titles. The <strong>handleChapa</strong> function is utilized to send a request to our backend API, which will be created inside the <strong>pages/api/chapa.js</strong> file. This is essential because Chapa does not permit sending requests directly from the frontend. Therefore, we need to employ backend languages like Node.js, PHP, or other suitable languages. Thankfully, Next.js provides the capability to create backend APIs using nodejs within the pages/api folder.</p><p>Navigate to the <strong>styles/Home.module.css</strong> file and include the following CSS code to style the checkout page.</p><pre>.container {<br>  min-height: 100vh;<br>  padding: 0 0.5rem;<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: center;<br>  align-items: center;<br>}<br><br>.title a {<br>  color: #0070f3;<br>  text-decoration: none;<br> <br>}<br><br>.title a:hover,<br>.title a:focus,<br>.title a:active {<br>  text-decoration: underline;<br>}<br><br>.title {<br>  margin: 0 0 1rem;<br>  line-height: 1.15;<br>  font-size: 15px;<br>  display: block;<br>  height: 30px;<br>}<br><br>.title {<br>  text-align: center;<br>}<br><br>.title,<br>.description {<br>  text-align: center;<br>}<br><br>.description {<br>  line-height: 1.5;<br>  font-size: 1.5rem;<br>}<br><br>.grid {<br>  display: flex;<br>  align-items: center;<br>  justify-content: center;<br>  flex-wrap: wrap;<br><br>  max-width: 800px;<br>  margin-top: 3rem;<br>}<br><br>.card {<br>  margin: 1rem;<br>  flex-basis: 100%;<br>  padding: 1.5rem;<br>  text-align: left;<br>  color: inherit;<br>  text-decoration: none;<br>  border: 1px solid #eaeaea;<br>  border-radius: 10px;<br>  min-width: 500px;<br>  transition:<br>    color 0.15s ease,<br>    border-color 0.15s ease;<br>}<br><br>.card:hover,<br>.card:focus,<br>.card:active {<br>  color: #0070f3;<br>  border-color: #0070f3;<br>}<br><br>.card h3 {<br>  margin: 0 0 1rem 0;<br>  font-size: 1.5rem;<br>}<br><br>.card p {<br>  margin: 0;<br>  font-size: 1.25rem;<br>  line-height: 1.5;<br>}<br><br>.logo {<br>  height: 1em;<br>}<br>.btn {<br>  background-color: #087EEA;<br>  color: white;<br>  padding: 12px;<br>  margin: 10px 0;<br>  border: none;<br>  width: 100%;<br>  border-radius: 3px;<br>  cursor: pointer;<br>  font-size: 17px;<br>}<br><br>.btn:hover {<br>  background-color: #45a049;<br>}<br><br>@media (max-width: 600px) {<br>  .grid {<br>    width: 100%;<br>    flex-direction: column;<br>  }<br>}</pre><p>To proceed, create a new folder named <strong>api</strong> inside the <strong>pages </strong>folder. Then Inside the <strong>api </strong>folder, create two files named <strong>chapa.js</strong> and <strong>verify.js</strong> Please copy and paste the provided code into these respective files.</p><p>chapa.js</p><pre>import axios from &quot;axios&quot;;<br>export default async function handler(req, res) {<br> const { amount, currency, email, first_name, last_name, phone_number, tx_ref, callback_url, return_url, customization } = req.body;<br> try {<br><br>        const header = {<br>            headers: { <br>                Authorization: `Bearer ${process.env.CHAPA_SECRET_KEY}`,<br>                &quot;Content-Type&quot;: &quot;application/json&quot;<br>             },<br>            <br>        };<br>  const body = {<br>   amount: amount,<br>   currency: currency,<br>   email: email,<br>   first_name: first_name,<br>   last_name: last_name,<br>   phone_number: phone_number,<br>   tx_ref: tx_ref,<br>   callback_url: callback_url,<br>   return_url: return_url,<br>            &quot;customization[title]&quot; : customization.title,<br>            &quot;customization[description]&quot; : customization.description<br>  }<br>  let resp = &quot;&quot;;<br>  await axios.post(&quot;https://api.chapa.co/v1/transaction/initialize&quot;, body, header).then(response =&gt; {<br>    resp = response;<br>  })<br>  .catch(error =&gt; {<br>   console.log(error.response.data); // Prints the error response data<br>   console.log(error.response.status); // Prints the status code of the error response<br>   console.log(error.response.headers); // Prints the headers of the error response<br>   res.status(400).json({<br>    message: error,<br>   });<br>  });<br>        res.status(200).json(resp.data);<br>        <br> } catch (e) {<br>  res.status(400).json({<br>   error_code: e.code,<br>   message: e.message,<br>  });<br> }<br>}</pre><p>verify.js</p><pre><br>import axios from &quot;axios&quot;;<br>export default async function handler(req, res) {<br> const { tnx_ref } = req.body;<br> try {<br><br>        const header = {<br>            headers: { <br>                Authorization: `Bearer ${process.env.CHAPA_SECRET_KEY}`,<br>                &quot;Content-Type&quot;: &quot;application/json&quot;<br>             },         <br>        };<br>        let response = await axios.get(&quot;https://api.chapa.co/v1/transaction/verify/&quot; + tnx_ref, header)<br>        <br>        let resp = await response.data;<br>        res.status(200).json({<br>            message : &quot;Payment successfull&quot;,<br>            status : &quot;success&quot; <br>        });<br> } catch (e) {<br>  res.status(400).json({<br>   error_code: e.code,<br>   message: e.message,<br>  });<br> }<br>}</pre><p>Lastly, create a new file inside the <strong>pages</strong> folder named <strong>verifyChapa.js</strong>. This file will serve as the confirmation page that checks if the payment was successful or not. It will display a success or error message accordingly. Make sure to set the name of this page as the value of the “return_url” parameter in your Chapa payment request.</p><p>verifyChapa.js</p><pre>import { useEffect, useState } from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br><br>const VarifyChapa = ({user}) =&gt; {<br> const router = useRouter();<br>    const [data, setData] = useState({})<br><br> useEffect(() =&gt; {<br>  const confirmPayment = async () =&gt; {<br>   try {<br>    const { tnx_ref } = router.query;<br>    const url = `http://localhost:3000/api/varify`;<br>                const header = {<br>                    headers: {  &quot;Content-Type&quot;: &quot;application/json&quot; },                   <br>                };<br>    const data = { tnx_ref : tnx_ref };<br>    let response = await axios.post(url, data, header);<br>                setData(response.data);<br>   } catch (error) {<br>    console.log(error);<br>   }<br>  };<br><br>  confirmPayment();<br> }, [router.query]);<br><br> return (<br>  &lt;&gt;   <br>     &lt;div className=&quot;row align-items-center&quot; &gt;<br>      &lt;div className=&quot;col-lg-12 col-md-12&quot;&gt;<br>          &lt;h3&gt;{data &amp;&amp; data.message }&lt;/h3&gt;                          <br>      &lt;/div&gt;<br>     &lt;/div&gt;   <br>  &lt;/&gt;<br> );<br>};<br><br>export default VarifyChapa;</pre><p><strong>Congrats </strong>you have completed all the necessary steps. Now, you just need to run the project by executing the “<strong>npm run dev</strong>” command in the VS Code terminal. After that, click on the “<strong>Pay with Chapa</strong>” button, which will redirect you to the Chapa checkout page. You can use this <a href="https://developer.chapa.co/docs/testing-mobile/">link</a> to access test cards and phone numbers for testing payment transactions. Once the payment is successfully processed, Chapa will redirect you to your designated return URL, which in this case is “<strong>verifyChapa</strong>”. On the “verifyChapa” page, the payment success will be checked, and a corresponding success message will be displayed.</p><p>You can access the project we worked on by following the GitHub URL provided below.</p><h3>Conclusion</h3><p>So, we have come to an end. Hope you like this article. Please consider giving feedback on my writing.</p><h3>Important Links</h3><ul><li><a href="https://developer.chapa.co/docs/">Chapa Docs</a></li><li><a href="https://github.com/eyuelhaile/Chapa-Checkout">Github Sample Projec</a>t</li><li>Preview</li></ul><h3>Credits</h3><ul><li><a href="https://chapa.co/">Chapa Payment Gateway</a></li></ul><p><strong>Connect with me:</strong></p><ul><li><a href="https://github.com/eyuelhaile">Github</a></li><li><a href="https://www.linkedin.com/in/eyuel-haile-416bab99/">Linkedin</a></li><li><a href="https://www.upwork.com/freelancers/~013375c88312d565b5?viewMode=1">Upwork</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81cfd6ac54a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>