ios – methods to present label(textual content) within the viewcontroller in firestore in addition to stripe

0
10


I’ve a SignUpViewController which sifns up consumer into auth –

    import UIKit
    import FirebaseFirestore
    import FirebaseCore
    import FirebaseAuth
    import FirebaseAnalytics

     class SignUpViewController: UIViewController {
     @IBOutlet weak var electronic mail: UITextField!
     @IBOutlet weak var password: UITextField!
     @IBOutlet weak var passwordConfirm: UITextField!
     @IBAction func signUpAction(_ sender: Any) {
    if password.textual content != passwordConfirm.textual content {let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", type: .cancel, handler: nil)
           
alertController.addAction(defaultAction)
self.current(alertController, animated: true, completion: nil)
        }else{
Auth.auth().createUser(withEmail: electronic mail.textual content!, password: password.textual content!){ (consumer, error) in if error == nil {
   self.performSegue(withIdentifier: "signupToHome", sender: self)
                }
 else{
   let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
   let defaultAction = UIAlertAction(title: "OK", type: .cancel, handler: nil)
                   
    alertController.addAction(defaultAction)
    self.current(alertController, animated: true, completion: nil)
       }
            }
      }
}
}

It really works tremendous as you’ll be able to see in determine beneath:-

enter image description here

I even have “UserIdtoFirestoreViewController” which transfers electronic mail use id from auth to firestore:-

     import UIKit
    import Firebase
    import FirebaseFirestore
 class UserIdtoFirestoreViewController: UIViewController {
let db = Firestore.firestore()
var ref: DocumentReference? = nil
let electronic mail = Auth.auth().currentUser!.electronic mail
let id = Auth.auth().currentUser!.uid
let fullName = Auth.auth().currentUser!.displayName

    @IBAction func GetUserId(_ sender: UIButton) {
    db
        .assortment("customers")
        .doc(id)
        .setData([
                    "email":email])

    }
  }

enter image description here

As you’ll be able to see, my capabilities are additionally deployed:-

enter image description here

Additionally, that is my index.js code:-

 const capabilities = require('firebase-functions');
 const admin = require('firebase-admin');

 const stripe = require('stripe')        ('sk_test_51HmAsMFzRM1fSBZ2CkBBjW5a3sEpxEQLGT7OkGxa8BZMMfgzT1Jeqs7dq63AlPRLIJmzHFC0HHAmKHDazcpriuh9001IWIVmw1');
 // initialize admin SDK with defaults
   admin.initializeApp();


   /**
  * When a consumer is created, create a Stripe buyer object for them.
  */
   exports.createStripeCustomer = capabilities.auth.consumer().onCreate(async (consumer) => {
  const buyer = await stripe.clients.create({
   electronic mail: consumer.electronic mail,
    metadata: { firebaseUID: consumer.uid },
   });

   await admin.firestore().assortment('stripe_customers').doc(consumer.uid).set({
    customer_id: buyer.id,
    });
    return;
    });

   /**
    * Arrange an ephemeral key.
   *
    * @see https://stripe.com/docs/cell/android/primary#set-up-ephemeral-key
    * @see https://stripe.com/docs/cell/ios/primary#ephemeral-key
   */
   exports.createEphemeralKey = capabilities.https.onCall(async (knowledge, context) => {
     // Checking that the consumer is authenticated.
   if (!context.auth) {
    // Throwing an HttpsError in order that the shopper will get the error particulars.
     throw new capabilities.https.HttpsError(
    'failed-precondition',
     'The perform should be known as whereas authenticated!'
     );
      }
     const uid = context.auth.uid;
    strive {
     if (!uid) throw new Error('Not authenticated!');
     // Get stripe buyer id
     const buyer = (
      await admin.firestore().assortment('stripe_customers').doc(uid).get()
      ).knowledge().customer_id;
      const key = await stripe.ephemeralKeys.create(
        { buyer },
       { apiVersion: knowledge.api_version }
      );
       return key;
     } catch (error) {
       throw new capabilities.https.HttpsError('inside', error.message);
      }
      });

     /**
    * When a fee doc is written on the shopper,
    * this perform is triggered to create the PaymentIntent in Stripe.
     *
   * @see https://stripe.com/docs/cell/android/primary#complete-the-payment
    */
    exports.createStripePayment = capabilities.firestore
    .doc('stripe_customers/{userId}/funds/{pushId}')
   .onCreate(async (snap, context) => {
    const { quantity, forex } = snap.knowledge();
    strive {
      // Lookup the Stripe buyer id.
     const buyer = (await snap.ref.guardian.guardian.get()).knowledge().customer_id;
       const ephemeralKey = await stripe.ephemeralKeys.create(
       { buyer },
       { apiVersion: '2020-08-27' }
       );
       // Create a cost utilizing the pushId because the idempotency key
      // to guard in opposition to double fees.
       const idempotencyKey = context.params.pushId;
       const fee = await stripe.paymentIntents.create(
           {
           quantity,
          forex,
           buyer,
            },
         { idempotencyKey }
             );
         fee.ephemeralKey = ephemeralKey.secret;
         // If the result's profitable, write it again to the database.
         await snap.ref.set(fee);
       } catch (error) {
       // We need to seize errors and render them in a user-friendly method, whereas
       // nonetheless logging an exception with StackDriver
      console.log(error);
       await snap.ref.set({ error: userFacingMessage(error) }, { merge: true });
       await reportError(error, { consumer: context.params.userId });
       }
      });

      /**
      * Helper perform to replace a fee report in Cloud Firestore.
       */
     const updatePaymentRecord = async (id) => {
     // Retrieve the fee object to ensure we now have an updated standing.
     const fee = await stripe.paymentIntents.retrieve(id);
    const customerId = fee.buyer;
   // Get buyer's doc in Firestore.
    const customersSnap = await admin
       .firestore()
      .assortment('stripe_customers')
       .the place('customer_id', '==', customerId)
         .get();
      if (customersSnap.measurement !== 1) throw new Error('Consumer not discovered!');
     // Replace report in Firestore
     const paymentsSnap = await customersSnap.docs[0].ref
      .assortment('funds')
     .the place('id', '==', fee.id)
      .get();
        if (paymentsSnap.measurement !== 1) throw new Error('Fee not discovered!');
      await paymentsSnap.docs[0].ref.set(fee);
      };

     /**
     * A webhook handler perform for the related Stripe occasions.
    * @see https://stripe.com/docs/funds/handling-payment-events?lang=node#build-   your-own-webhook
       */
      exports.handleWebhookEvents = capabilities.https.onRequest(async (req, resp) => {
     const relevantEvents = new Set([
    'payment_intent.succeeded',
     'payment_intent.processing',
    'payment_intent.payment_failed',
      'payment_intent.canceled',
         ]);

     let occasion;

     // As a substitute of getting the `Stripe.Occasion`
     // object immediately from `req.physique`,
    // use the Stripe webhooks API to ensure
      // this webhook name got here from a trusted supply
     strive {
          occasion = stripe.webhooks.constructEvent(
       req.rawBody,
  req.headers['stripe-signature'],
  capabilities.config().stripe.webhooksecret
      );
      } catch (error) {
       console.error('❗️ Webhook Error: Invalid Secret');
       resp.standing(401).ship('Webhook Error: Invalid Secret');
      return;
       }

      if (relevantEvents.has(occasion.kind)) {
       strive {
       swap (occasion.kind) {
        case 'payment_intent.succeeded':
        case 'payment_intent.processing':
         case 'payment_intent.payment_failed':
         case 'payment_intent.canceled':
          const id = occasion.knowledge.object.id;
           await updatePaymentRecord(id);
          break;
          default:
            throw new Error('Unhandled related occasion!');
         }
         } catch (error) {
        console.error(
         `❗️ Webhook error for [${event.data.object.id}]`,
         error.message
          );
        resp.standing(400).ship('Webhook handler failed. View Operate logs.');
        return;
        }
       }

     // Return a response to Stripe to acknowledge receipt of the occasion.
       resp.json({ acquired: true });
        });

       /**
     * When a consumer deletes their account, clear up after them.
       */
     exports.cleanupUser = capabilities.auth.consumer().onDelete(async (consumer) => {
    const dbRef = admin.firestore().assortment('stripe_customers');
    const buyer = (await dbRef.doc(consumer.uid).get()).knowledge();
    await stripe.clients.del(buyer.customer_id);
     // Delete the shoppers funds & fee strategies in firestore.
     const snapshot = await dbRef
     .doc(consumer.uid)
    .assortment('payment_methods')
     .get();
     snapshot.forEach((snap) => snap.ref.delete());
     await dbRef.doc(consumer.uid).delete();
     return;
     });

    /**
        * To maintain on high of errors, we should always elevate a verbose error report with Stackdriver moderately
     * than merely counting on console.error. It will calculate customers affected + ship    you electronic mail
      * alerts, should you've opted into receiving them.
       */

     // [START reporterror]

           perform reportError(err, context = {}) {
      // That is the title of the StackDriver log stream that can obtain the log
     // entry. This title may be any legitimate log stream title, however should include "err"
     // to ensure that the error to be picked up by StackDriver Error Reporting.
     const logName="errors";
    const log = logging.log(logName);

      // https://cloud.google.com/logging/docs/api/ref_v2beta1/relaxation/v2beta1/MonitoredResource
      const metadata = {
       useful resource: {
           kind: 'cloud_function',
          labels: { function_name: course of.env.FUNCTION_NAME },
        },
         };

       // https://cloud.google.com/error-reporting/reference/relaxation/v1beta1/ErrorEvent
      const errorEvent = {
     message: err.stack,
      serviceContext: {
      service: course of.env.FUNCTION_NAME,
        resourceType: 'cloud_function',
       },
        context: context,
      };

        // Write the error log entry
        return new Promise((resolve, reject) => {
        log.write(log.entry(metadata, errorEvent), (error) => {
         if (error) {
    return reject(error);
     }
    return resolve();
    });
    });
    }

   // [END reporterror]

    /**
     * Sanitize the error message for the consumer.
       */
        perform userFacingMessage(error) {
      return error.kind
      ? error.message
      : 'An error occurred, builders have been alerted';
       }

All of the above together with webhooks work tremendous,

Now, I do know that is an excessive amount of to ask for, however I’m caught for a very long time –

what ought to be the viewcontroller code in order that buyer product and value within the type of a label or textual content will get added to firestore in addition to stripe if I click on a button on viewcontroller ? I’m caught for a loing time, so I desparately want your assist guys.

LEAVE A REPLY

Please enter your comment!
Please enter your name here