Flutter+Firebase Cloud Functions으로 아임포트 본인인증

Faamica·2022년 3월 22일
0

앱개발 중인 독학 비전공자 늦깎이 멍청코린이.

개발 = flutter + firebase와 vscode의 lib폴더

이게 개발의 전부였던 코린 멍청이는

서버에서 해야된다는 결제 검증 같은 것들도 일단 무조건 클라이언트 코드로 다 조지다가,
채팅 알림에서 드디어 백엔드라는 게 필요한 상황에 다다름

하지만
cloud functions?? CLI???? 이건 대체 무슨 언어?? index.js??? lib폴더가 아닌데?? 어떻게 하라는 것?????

하며 오랫동안 문맹 상태를 벗어나지 못했어서,

너무 높은 벽이었던 cloud functions 코드를 공유하기로 마음 먹었습니다.
이유는 나도 검색하면서 도움 많이 받았어서 나같은 완전 생초보분들 도움 되시라고.
잘 모르겠는건 머리가 백지라 검색도 어렵더라고요

전체 흐름은 다음과 같습니다.

앱에서 요청 -> 본인인증 후 -> 콜백으로 팡션 실행 -> 아임포트 서버에서 인증된 전화번호 가져옴 -> 파이어스토어에서 회원가입되어있는지 확인 -> 회원가입 페이지로

굵게 처리한 단계의 코드입니다.
(https://dev-in-seoul.tistory.com/9?category=462550 블로그 많이 참조. 감 잡는데 크나큰 도움이 되었어요 많이 감사합니다 하트도 눌렀습니다.)

phoneCertification.js



const functions = require("firebase-functions");
const admin = require('firebase-admin');
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json()); 
app.use(cors({ origin: true })); 

const db = admin.firestore(); 

app.post("/", async (req, res) => {
    try {
        const newData = req.body;
        const {imp_uid} = newData;

    //*==================== 아임포트 서버에 인증내역 조회 후 데이터 얻음 ====================
        // 액세스 토큰(access token) 발급 받기(아임포트 서버와 통신하기 위한 엑세스 토큰.)
        const getToken = await axios({
        url: "https://api.iamport.kr/users/getToken",
        method: "POST", // POST method
        headers: { "Content-Type": "application/json" },
        data: {
          imp_key: "key"
          imp_secret: "secret"
           
        },
      });
        const { access_token } = getToken.data.response; // 인증 토큰 확보
        functions.logger.log(`getToken Success: ${access_token}`);

        //비교 검증을 위해 IMP 서버로 들어온 인증데이터 조회
        const getCertificateData = await axios({
        url: `https://api.iamport.kr/certifications/${imp_uid}`, //주문번호 입력
        method: "GET", 
        headers: { "Authorization": access_token }, // 인증 토큰 Authorization header에 추가
      }).catch(err => {
        functions.logger.error(err);
      });

        const certificationInfo = getCertificateData.data.response; // 조회한 인증 정보
        const {phone, name} = certificationInfo;
        functions.logger.log(`phone: ${phone}`);

//*==================== Firestore에 데이터 조회 ====================
        let docListGet = await db.collection("Users").where("PhoneNumber", "==", phone).get();
        let docList = docListGet.docs;

        if (docList.length>0) {
            const email = docList[0].data().Email;
            functions.logger.info("가입된 번호 있음");
            res.send(JSON.stringify({ status: "number-exist", message: `${email}로 가입된 번호가 존재해요.`})); 
        } else {
            functions.logger.info("가입된 번호 없음");
            paidSendMsg = res.status(200).send(JSON.stringify({ status: "number-no-exist", message: `${phone}는 가입가능한 번호예요!`,phone: phone, name: name}));
        }
    }
    catch (e)  {
        functions.logger.error(`error: ${e}`);
        res.status(400).send(JSON.stringify({ status: "Error", message: `진행 중 에러가 발생했어요!\n${e}`}));
    }

});

exports.phoneCertificate = functions.region("asia-northeast3").https.onRequest(app);

index.js


const phoneCertificate = require("./iamportCertificate");
exports.phoneCertificate = phoneCertificate.phoneCertificate;

0개의 댓글