Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2025
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 4.08 KB | Source Code | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_dotenv/flutter_dotenv.dart';
  3. import 'package:http/http.dart' as http;
  4. import 'package:provider/provider.dart';
  5. import 'package:shopping_app/models/cart_model.dart';
  6. import 'dart:convert';
  7. import 'package:khalti_checkout_flutter/khalti_checkout_flutter.dart';
  8. import 'package:shopping_app/pages/order_placed_page.dart';
  9.  
  10. class KhaltiServiceCustom {
  11.   KhaltiServiceCustom._();
  12.  
  13.   static final KhaltiServiceCustom khaltiInstance = KhaltiServiceCustom._();
  14.  
  15.   final String END_POINT = 'https://dev.khalti.com/api/v2/epayment/initiate/';
  16.  
  17.   Future<String> getPidX(
  18.     BuildContext context,
  19.     double amount, {
  20.     String returnUrl = 'https://example.com/payment/',
  21.     String websiteUrl = 'https://example.com/',
  22.   }) async {
  23.     final CartModel cart = Provider.of<CartModel>(context, listen: false);
  24.  
  25.     String pidX = '';
  26.  
  27.     Map<String, String> headers = {
  28.       'Authorization': 'Key ${dotenv.env['SECRET_KEY_KHALTI']!}',
  29.       'Content-Type': 'application/json',
  30.     };
  31.  
  32.     final String payloadEncoded = jsonEncode(<String, dynamic>{
  33.       'return_url': 'https://example.com/',
  34.       'website_url': 'https://example.com/',
  35.       'amount': convertRupeesToPaisa(amount),
  36.       'purchase_order_id': cart.getID(),
  37.       'purchase_order_name': cart.getName(),
  38.     });
  39.  
  40.     http.Response response = await http.post(
  41.       Uri.parse(END_POINT),
  42.       headers: headers,
  43.       body: payloadEncoded,
  44.     );
  45.     print(response.statusCode);
  46.     print(response.body);
  47.     if (response.statusCode == 200) {
  48.       print('code 200');
  49.       final Map<String, dynamic> data = jsonDecode(response.body);
  50.       pidX = data['pidx'];
  51.       print(pidX);
  52.       return pidX;
  53.     }
  54.     return pidX;
  55.   }
  56.  
  57.   int convertRupeesToPaisa(double rupees) {
  58.     return (rupees * 100).toInt();
  59.   }
  60.  
  61.   Future<void> khaltiPayment(BuildContext context, double amount) async {
  62.     String pidx = await getPidX(context, amount);
  63.     print('called khalti func');
  64.  
  65.     final KhaltiPayConfig payConfig = KhaltiPayConfig(
  66.       publicKey:
  67.           'live_public_public_key_979320ffda734d8e9f7758ac39ec775f', // This is a dummy public key for example purpose
  68.       pidx: pidx,
  69.       environment: Environment.test,
  70.     );
  71.  
  72.     final Khalti? instance = await Khalti.init(
  73.       payConfig: payConfig,
  74.       onPaymentResult: (PaymentResult result, Khalti khalti) {
  75.         print('PaymentResult payload: ${result.payload}');
  76.         if (result.payload?.status!.toLowerCase() == 'completed') {
  77.           Navigator.pushAndRemoveUntil(
  78.             context,
  79.             MaterialPageRoute<Widget>(
  80.               builder: (BuildContext context) => const OrderPlacedPage(),
  81.             ),
  82.             (Route<dynamic> route) => false,
  83.           );
  84.         } else {
  85.           showDialog(
  86.             context: context,
  87.             builder: (BuildContext context) {
  88.               return AlertDialog(
  89.                 title: Text(
  90.                   'Paymemt Failed!',
  91.                   style: TextStyle(
  92.                     color: Theme.of(context).colorScheme.inversePrimary,
  93.                   ),
  94.                 ),
  95.                 content: Text('Status: ${result.payload?.status ?? 'Unknown'}'),
  96.                 contentTextStyle: TextStyle(
  97.                   color: Theme.of(context).colorScheme.inversePrimary,
  98.                 ),
  99.                 contentPadding: const EdgeInsets.all(8),
  100.               );
  101.             },
  102.           );
  103.         }
  104.         khalti.close(context);
  105.       },
  106.       onMessage:
  107.           (
  108.             Khalti khalti, {
  109.             Object? description,
  110.             int? statusCode,
  111.             KhaltiEvent? event,
  112.             bool? needsPaymentConfirmation,
  113.           }) {
  114.             print('Khalti Message: $description');
  115.             // khalti.close(context);
  116.           },
  117.       onReturn: () async {
  118.         print('Returned from Khalti');
  119.       },
  120.     );
  121.  
  122.     if (instance != null) {
  123.       if (context.mounted) {
  124.         instance.open(context);
  125.       }
  126.     } else {
  127.       print('Failed to init Khalti');
  128.     }
  129.   }
  130. }
  131.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement