플레이 리스트 : https://www.youtube.com/playlist?list=PLl-K7zZEsYLmnJ_FpMOZgyg6XcIGBu2OX


주요 동영상 : https://youtu.be/LOeioOKUKI8

위) firebase-tools 글로벌로 설치

image
image
image
image

위) firebase.json 수정을 통해 header를 넣을수도 있고 reroute도 할수있다.

image

위) timestamp로 접속하는 경우 firebase functions app으로 reroute하는 경우

image

위) firebase functions https 모든 요청을 express app이 처리하게 만든 경우

image

위) localhost로 확인

image

위) cache를 이용 사용속도를 올리는 방법

image

위) 모든 http 접근을 firebase functions app이 처리하게 하는 경우

image

위) cache를 설정한경우

image

위) firebase cloud functions에 deploy하는 경우

image

위) html template 화일은 functions folder내의 views안에 한다.

image
image

위) template hbs를 사용하는 경우

image

위) statics화일의 경우 public에 넣어놓으면 html에서는 화일명 만으로도 접근 가능하게 된다.

image

.

.

.

.

참고사항)

예제코드 : https://github.com/firebase/functions-samples

original source : https://youtu.be/RYiscsdICrs

node js를 기반으로 한 server를 이용한 연동 

위에서 body-parser는 post되어 들어온 데이터를 req.body를 통해 접근가능하게 한다.

위에서 env는 .env 화일에 저장되어 있는 여러 stripe key에 접근하기 위해 사용한다.(환경변수로저장한것에 접근하는걸로 이해)

위) 사용자를 stripe에 연결하려는 경우 사용자는 개발자가 제공한 ui (예를 들어 button)클릭해서 server에 접근하게 한다. 그러면  account , accountLink를 만들고 이른 사용자에게 되돌려 주는데 이안에는 링크주소, 유효기간이 들어가 데이터를 되돌려 준다. 그럼 사용자는 링크주소를 통해 stripe가 제공한 flow process를 거쳐 필요한 정보를 넣게 되고 마무리되면 success_url, failure_url로 사용자를 redirect하게 된다.

위) 미국 회사 사용자 가입시 입력해야 하는 기본 정보들이다. 이를 개발자가 미리 가지고 있다고 한다면 아래와 같이 prefill할수 있다.

original source : https://stackoverflow.com/a/49950920

Package Control has a couple of packages, EJS and EJS 2 (and maybe also Hyperloop EJS, if that’s a thing; I’m unfamiliar with EJS).

Just at first blush it seems like EJS 2 might be the better first bet; it’s been more recently updated and is using the newer sublime-syntax syntax format and seems to support more things. Take that with a grain of salt though, since I have no experience with either one.

You can select the command Package Control: Install Package from the command palette and then select one of those packages to install it. If you’re going to try them both, do it one at a time and use Package Control: Remove Package before installing the next one so that they don’t compete with each other.

If those commands aren’t in your command palette, you don’t have Package Control installed yet. In that case you can select Install Package Control from the command palette to install PC first. If that doesn’t work there are also instructions on how to install it manually.

Once you have a package installed, you can close and reopen the file to apply the correct syntax, or use the menu as you mention in your question.

================

wasent firebase node 사용하면서 ejs화일 editing하는데 불편함이 있었음. 그래서 찾아보게 된 자료

original source : https://youtu.be/fqNPSSoMO9Y

.

.

요소를 포함하는 엘레먼트에 display속성에 flex로 지정해 준다.

.

.

flex 는 기본으로 no wrap

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

original source : https://medium.com/@GaryHarrower/working-with-stripe-webhooks-firebase-cloud-functions-5366c206c6c

firebase functions 와 stripe webhook연결

Now lets head over to our terminal and create a new directory for our project.

$ mkdir stripe-webhooks
$ cd stripe-webhooks

We then need to install the firebase-tools package globally using NPM.

(아래는 firebase-tool설치)

$ npm install -g firebase-tools

Now we have firebase-tools installed, we should login to our firebase account and initiate a new project in our project directory. You will get a choice of which services you would like to use — you only need to select ‘Functions’ here for now.

(아래는 firebase 사용전 초기 작업)

$ firebase login
$ firebase init

Let’s move into the functions folder (created with firebase init) and make sure we have the latest version of firebase-functions and firebase-admin installed. firebase-functions is used for running the actual cloud functions and firebase-admin is used to access the Realtime Database.

$ cd functions/
$ npm install firebase-functions@latest firebase-admin@latest --save

Let’s create a new function called events to handle our endpoint. We’ll start off simple with a basic function that returns a string to let us generate the URL we need to supply our Stripe account with.

const functions = require('firebase-functions');exports.events = functions.https.onRequest((request, response) => {
 response.send("Endpoint for Stripe Webhooks!");
});

We can then deploy our function and get our endpoint (Function URL in output in screenshot).

firebase deploy --only functions

(아래는 stripe에 webhook 만드는 과정)

Now we have our Cloud Function URL, we can head over to the webhooks section of the Stripe dashboard. We then want to + Add Endpoint, and enter our URL into the URL field. You can select the types of events to be sent, but for now we will just stick to all event types.

Once you create the endpoint, take note of your ‘Signing secret’ — we’ll need that to verify the request send to our function.

While we’re in our Stripe Dashboard, let’s head over to the API Keys section to generate and take not of the API key we’re going to use.

You should create a restricted API key and only assign permissions you’re going to need in your firebase project. For example, if you’re only going to read customer objects, you can specify only Customers when creating the key.

Now we have our signing secret and our API key, let’s add them to our Firebase project as environment variables so we don’t need to check them in to any source control.

$ firebase functions:config:set 
   keys.webhooks="your_restricted_key"
   keys.signing="your_signing_key"

That’s our setup complete — We’re now ready to write some code! I’m going to be using examples from Firebase and Stripe, so if there’s anything you would like to dive deeper into, you can use the following links:

To start with, we’re going to need the Stripe NPM package, so let’s go ahead and install that:

(stripe 라이브러리 설치)

$ npm install --save stripe

We added our API keys to our Firebase config, so we can access them using functions.config() (For example: functions.config().keys.webhooks will return our keys.webhooks string we added).

We will then require the Stripe package in our functions index.js. We will also bring in our Signing key to our application (endpointSecret).

const functions = require(‘firebase-functions’);
const stripe = require(‘stripe’)(functions.config().keys.webhooks);
const endpointSecret = functions.config().keys.signing;exports.events = functions.https.onRequest((request, response) => {
 response.send(“Endpoint for Stripe Webhooks!”);
});

Note: Stripe marks a webhook as successful only when your function returns a success (2xx) response. If it receives anything else, such as a 400 or 500, then it marks it as failed, and will try again.

We can use our signing key to verify that a request has actually come from Stripe, and not an unauthorized attacker. The stripe package has a method (stripe.webhooks.constructEvent) which we can use to verify the request. We can also use a Try Catch to return an error if the request fails verification.

// Get the signature from the request header
let sig = request.headers["stripe-signature"];// Verify the request against our endpointSecret
let event = stripe.webhooks.constructEvent(request.rawBody, sig, endpointSecret);

Note: We need to use the original request body otherwise the verification will fail, so we must use Firebase Function’s request.rawBody, instead of the usual request.body.

As mentioned, we can wrap this in a Try Catch to catch any failed requests.

let sig = request.headers["stripe-signature"];try {
 let event = stripe.webhooks.constructEvent(request.rawBody, sig, endpointSecret);
} catch (err) {
 return response.status(400).end();
}

Now we have our valid events, let’s save them to our Firebase Realtime Database.

We can do this by using the firebase-admin database methods. We’re going to be using the .push() method to create a new entry in our database.

const admin = require('firebase-admin');
admin.initializeApp();...return admin.database().ref('/events').push(event)
 .then((snapshot) => {
   return response.json({ received: true, ref: snapshot.ref.toString() });
 })
 .catch((err) => {
   console.error(err);
   return response.status(500).end();
 });

Let’s break this code down a bit.

  • Ref is the path in the database we would like to save our new entry to. This can be whatever you like — i’ve chosen so save my events in the /events ref.
  • Push(event)- event is the variable we’re saving the response from the constructEvent method we called. This is an object with all of our event info
  • Response.json — We respond with a valid json object — this tells Stripe that the webhook event was received and we’re happy we’ve processed it, so mark it as complete.
  • Catch — In case something goes wrong while we’re saving the event to the database, we return an error 500 to tell Stripe that something went wrong. Stripe will then retry sending the event. There are ways you could incorporate this into the Try Catch we have, although I like having the differentiation of errors.

Now we should deploy our function again, then we can test it out.

$ firebase deploy --only functions

Let’s head back over to the Stripe Dashboard Webhooks area, select our endpoint where we can now ‘Send test webhook’.

Select an event type and hit ‘Send test webhook’ — all going well, we get a successful response, and our event is now saved in our database!

That’s it in terms of saving. Now you have endless possibilities of cool things to do with your data. For further reading, you could explore the different triggers Cloud Functions can use. You can run another function whenever anything is added to your database. The example below would run any time a new event is saved to our database. We could now check the event type, and if it’s a successful charge, update our Realtime database to increase our daily revenue on our live dashboard…

You can read more about database events here: https://firebase.google.com/docs/functions/database-events

I hope this was useful. Please leave any feedback or questions – I’m always learning and really appreciate any comments you may have.

You can find the completed code over on Github — https://github.com/GaryH21/Stripe-Webhooks-Tutorial

Happy building!