skip to Main Content

I am trying to set up payments into Flutter via Strap, but I am having an issue when I click on the button ‘checkout’, which will refer to the payment page.
Once clicked, a error message shows up, that says ‘Error: FormatException: Unexpected character (at line 2, character 1)’.

I think this can be related to the jsonResponse, that does not refer a JSON object?
Does anyone has an idea?
Thank you so much for your help SEE IMAGE HERE

`[tag:import 'dart:convert';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:http/http.dart' as http;

import '../models/product.dart';

class PaymentHandler {
  final String? payIntentId;
  final bool isError;
  final String message;

  PaymentHandler({
    this.payIntentId,
    required this.isError,
    required this.message,
  });
}

class PaymentService {
  PaymentService();

  Future<PaymentHandler> initPaymentSheet(User user, double totalAmount) async {
    try {
      // 1. create payment intent on the server
      final response = await http.post(
          Uri.parse(
              'http://us-central1-ecommerceapp-34d7f.cloudfunctions.net/stripePaymentIntentRequest'),
          body: {
            'email': user.email,
            'amount': (totalAmount * 100).toString(),
          });

      final jsonResponse = jsonDecode(response.body);

      //2. initialize the payment sheet
      await Stripe.instance.initPaymentSheet(
        paymentSheetParameters: SetupPaymentSheetParameters(
          paymentIntentClientSecret: jsonResponse['paymentIntent'],
          merchantDisplayName: 'Flutter Stripe Store Demo',
          customerId: jsonResponse['customer'],
          customerEphemeralKeySecret: jsonResponse['ephemeralKey'],
          style: ThemeMode.light,
          testEnv: true,
          merchantCountryCode: 'US',
        ),
      );
      // 3. Present to the user and await the result
      await Stripe.instance.presentPaymentSheet();
      return PaymentHandler(
          isError: false,
          message: "Success",
          payIntentId: jsonResponse['paymentIntent']);
      // Note: This is better done through our cloud functions

    } catch (e) {
      if (e is StripeException) {
        return PaymentHandler(
            isError: true,
            message: 'Error from Stripe: ${e.error.localizedMessage}');
      } else {
        return PaymentHandler(isError: true, message: 'Error: ${e}');
      }
    }
  }
}]`

I tried to flutter upgrade, re authenticate my firebase account, change the variables…

2

Answers


  1. Chosen as BEST ANSWER
     Future<PaymentHandler> initPaymentSheet(User user, double totalAmount) async {
        
        try {
         // 1. create payment intent on the server
         final response = await http.post(
             Uri.parse(
                 'http://us-central1-ecommerceapp-34d7f.cloudfunctions.net/stripePaymentIntentRequest'),
             body: json.encode({
               'email': user.email,
               'amount': (totalAmount * 100).toString(),
             }), 
            headers: {
              "Authorization": 'Bearer <private_key>',
              "Content-Type" : 'application/json',
              "Accept": 'application/json'}
           );
         
           final jsonResponse = jsonDecode(response.body) ;
    

  2. You are getting a web page instead of JSON from your API call.
    It can happen because one of the two reason:

    1. The API needs to be authenticated. In that case you need to add authentication/authorization header on your request like:

      var headers = {  'Authorization': 'Bearer <your_token>' }
      
    2. The API requires to define content type and or accept header like:

      var headers = {   
                  'Content-Type': 'application/json',
                  'Accept': 'application/json'
                 }
      

    Or combination of both:

                 { 
                   'Authorization': 'Bearer <your_token>',
                   'Content-Type': 'application/json',
                   'Accept': 'application/json'
                  }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search