캔 내역, 캔 충전 페이지 추가

This commit is contained in:
Yu Sung
2023-08-11 03:57:39 +09:00
parent c91301e658
commit cb644f745e
23 changed files with 2013 additions and 4 deletions

View File

@@ -0,0 +1,249 @@
//
// CanPaymentView.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import SwiftUI
import StoreKit
struct CanPaymentView: View {
@StateObject var viewModel = CanPaymentViewModel()
@StateObject var storeManager = StoreManager()
let canProduct: SKProduct
let refresh: () -> Void
let afterCompletionToGoBack: Bool
init(canProduct: SKProduct, refresh: @escaping () -> Void, afterCompletionToGoBack: Bool) {
self.canProduct = canProduct
self.refresh = refresh
self.afterCompletionToGoBack = afterCompletionToGoBack
}
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
GeometryReader { proxy in
VStack(spacing: 0) {
DetailNavigationBar(title: "결제하기")
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 0) {
HStack(spacing: 0) {
Image("ic_can")
.resizable()
.scaledToFill()
.frame(width: 26.7, height: 26.7, alignment: .top)
Text(canProduct.localizedTitle)
.font(.custom(Font.bold.rawValue, size: 15.3))
.foregroundColor(Color(hex: "eeeeee"))
.padding(.leading, 13.3)
Spacer()
Text("\(NumberFormatter.localizedString(from: canProduct.price, number: .currency))")
.font(.custom(Font.bold.rawValue, size: 15.3))
.foregroundColor(Color(hex: "eeeeee"))
}
.padding(.horizontal, 13.3)
.padding(.vertical, 23.3)
.background(Color(hex: "222222"))
.cornerRadius(16.7)
.padding(.horizontal, 13.3)
.frame(width: screenSize().width)
.padding(.top, 13.3)
HStack(spacing: 6.7) {
Image(viewModel.isTermsAgree ? "btn_select_checked" : "btn_select_normal")
.resizable()
.frame(width: 20, height: 20)
Text("구매조건 확인 및 결제 진행 동의")
.font(.custom(Font.medium.rawValue, size: 14.7))
.foregroundColor(Color(hex: "eeeeee"))
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
.padding(.top, 13.3)
.onTapGesture {
viewModel.isTermsAgree.toggle()
}
VStack(spacing: 6.7) {
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("충전된 코인의 유효기간은 충전 후 5년 입니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
.padding(.top, 26.7)
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("결제 취소는 결제 후 7일 이내에만 할 수 있습니다.\n단, 코인의 일부를 사용하면 결제 취소를 할 수 없습니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("광고성 이벤트 등 회사가 무료로 지급한 포인트는 환불되지 않습니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("자세한 내용은 요즘라이브 이용약관에서 확인할 수 있습니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
}
}
}
Spacer()
HStack(spacing: 0) {
VStack(alignment: .leading, spacing: 5) {
Text("결제금액")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "eeeeee"))
HStack(spacing: 0) {
Text("\(NumberFormatter.localizedString(from: canProduct.price, number: .currency))")
.font(.custom(Font.bold.rawValue, size: 23.3))
.foregroundColor(Color(hex: "eeeeee"))
}
}
Spacer()
Text("결제하기")
.font(.custom(Font.bold.rawValue, size: 18.3))
.foregroundColor(.white)
.padding(.vertical, 16)
.frame(minWidth: 200)
.background(Color(hex: "9970ff"))
.cornerRadius(10)
.onTapGesture {
if viewModel.isTermsAgree {
viewModel.chargeCan(canProduct: canProduct, paymentGateway: .APPLE_IAP) { product, chargeId in
storeManager.payment(product: product, chargeId: chargeId)
}
} else {
viewModel.errorMessage = "결제진행에 동의하셔야 결제가 가능합니다."
viewModel.isShowPopup = true
}
}
}
.padding(.leading, 22)
.padding(.trailing, 13.3)
.padding(.vertical, 13.3)
.background(Color(hex: "222222"))
.cornerRadius(16.7, corners: [.topLeft, .topRight])
if proxy.safeAreaInsets.bottom > 0 {
Rectangle()
.foregroundColor(Color(hex: "222222"))
.frame(width: proxy.size.width, height: 15.3)
}
}
.edgesIgnoringSafeArea(.bottom)
}
if viewModel.isLoading || storeManager.isLoading {
LoadingView()
}
}
.popup(isPresented: $viewModel.isShowPopup, type: .toast, position: .top, autohideIn: 2) {
GeometryReader { geo in
HStack {
Spacer()
Text(viewModel.errorMessage)
.padding(.vertical, 13.3)
.padding(.horizontal, 6.7)
.frame(width: geo.size.width - 66.7, alignment: .center)
.font(.custom(Font.medium.rawValue, size: 12))
.background(Color(hex: "9970ff"))
.foregroundColor(Color.white)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.cornerRadius(20)
.padding(.top, 66.7)
Spacer()
}
}
}
.popup(isPresented: $storeManager.isShowPopup, type: .toast, position: .top, autohideIn: 2) {
GeometryReader { geo in
HStack {
Spacer()
Text(storeManager.errorMessage)
.padding(.vertical, 13.3)
.padding(.horizontal, 6.7)
.frame(width: geo.size.width - 66.7, alignment: .center)
.font(.custom(Font.medium.rawValue, size: 12))
.background(Color(hex: "9970ff"))
.foregroundColor(Color.white)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.cornerRadius(20)
.padding(.top, 66.7)
Spacer()
}
}
}
.onAppear {
storeManager.onSuccessPayment = { receiptString, chargeId in
viewModel.verifyPayment(receiptString: receiptString, chargeId: chargeId) {
self.refresh()
if afterCompletionToGoBack {
AppState.shared.back()
} else {
AppState.shared.setAppStep(step: .canStatus(refresh: refresh))
}
let chargeCan = Int(canProduct.localizedDescription) ?? 0
let can = UserDefaults.int(forKey: .can)
UserDefaults.set(can + chargeCan, forKey: .can)
}
}
}
}
}
struct CanPaymentView_Previews: PreviewProvider {
static var previews: some View {
CanPaymentView(
canProduct: SKProduct(),
refresh: {},
afterCompletionToGoBack: false
)
}
}

View File

@@ -0,0 +1,101 @@
//
// CanPaymentViewModel.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import Foundation
import Combine
import StoreKit
final class CanPaymentViewModel: ObservableObject {
private let repository = CanRepository()
private var subscription = Set<AnyCancellable>()
@Published var isTermsAgree = false
@Published var errorMessage = ""
@Published var isShowPopup = false
@Published var isLoading = false
func chargeCan(canProduct: SKProduct, paymentGateway: PaymentGateway, onSuccess: @escaping (SKProduct, Int) -> Void) {
isLoading = true
repository.chargeCan(
title: canProduct.localizedTitle,
chargeCan: Int(canProduct.localizedDescription) ?? 0,
price: canProduct.price.doubleValue,
locale: canProduct.priceLocale.identifier,
paymentGateway: paymentGateway
)
.sink { result in
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { [unowned self] response in
self.isLoading = false
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponse<CanChargeResponse>.self, from: responseData)
if let data = decoded.data, decoded.success {
onSuccess(canProduct, data.chargeId)
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
}
self.isShowPopup = true
}
} catch {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
self.isShowPopup = true
}
}
.store(in: &subscription)
}
func verifyPayment(receiptString: String, chargeId: Int, onSuccess: @escaping () -> Void) {
isLoading = true
repository.verify(receiptString: receiptString, chargeId: chargeId)
.sink { result in
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { [unowned self] response in
self.isLoading = false
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponseWithoutData.self, from: responseData)
if decoded.success {
onSuccess()
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
}
self.isShowPopup = true
}
} catch {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
self.isShowPopup = true
}
}
.store(in: &subscription)
}
}

View File

@@ -0,0 +1,310 @@
//
// CanPgPaymentView.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import SwiftUI
import Bootpay
import BootpayUI
struct CanPgPaymentView: View {
@StateObject var viewModel = CanPgPaymentViewModel()
let canResponse: GetCanResponse
let refresh: () -> Void
let afterCompletionToGoBack: Bool
init(canResponse: GetCanResponse, refresh: @escaping () -> Void, afterCompletionToGoBack: Bool) {
self.canResponse = canResponse
self.refresh = refresh
self.afterCompletionToGoBack = afterCompletionToGoBack
}
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
if viewModel.isShowPamentView {
BootpayUI(payload: viewModel.payload, requestType: BootpayRequest.TYPE_PAYMENT)
.onConfirm {
DEBUG_LOG("onConfirm: \($0)")
return true
}
.onCancel {
DEBUG_LOG("onCancel: \($0)")
}
.onError {
DEBUG_LOG("onError: \($0)")
viewModel.isShowPamentView = false
viewModel.errorMessage = "결제 중 오류가 발생했습니다."
viewModel.isShowPopup = true
}
.onDone {
DEBUG_LOG("onDone: \($0)")
viewModel.verifyPayment($0) {
self.refresh()
if afterCompletionToGoBack {
AppState.shared.back()
} else {
AppState.shared.setAppStep(step: .canStatus(refresh: refresh))
}
let can = UserDefaults.int(forKey: .can)
UserDefaults.set(can + canResponse.can + canResponse.rewardCan, forKey: .can)
}
}
.onClose {
DEBUG_LOG("onClose")
viewModel.isShowPamentView = false
}
} else {
GeometryReader { proxy in
VStack(spacing: 0) {
DetailNavigationBar(title: "결제하기")
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 0) {
HStack(spacing: 0) {
Image("ic_can")
.resizable()
.scaledToFill()
.frame(width: 26.7, height: 26.7, alignment: .top)
Text(canResponse.title)
.font(.custom(Font.bold.rawValue, size: 15.3))
.foregroundColor(Color(hex: "eeeeee"))
.padding(.leading, 13.3)
Spacer()
Text("\(canResponse.price)")
.font(.custom(Font.bold.rawValue, size: 15.3))
.foregroundColor(Color(hex: "eeeeee"))
}
.padding(.horizontal, 13.3)
.padding(.vertical, 23.3)
.background(Color(hex: "222222"))
.cornerRadius(16.7)
.padding(.horizontal, 13.3)
.frame(width: screenSize().width)
.padding(.top, 13.3)
Text("결제 수단 선택")
.font(.custom(Font.bold.rawValue, size: 16.7))
.foregroundColor(Color(hex: "eeeeee"))
.frame(width: screenSize().width - 26.7, alignment: .leading)
.padding(.top, 26.7)
HStack(spacing: 13.3) {
Text("카드")
.font(.custom( viewModel.paymentMethod == .card ? Font.bold.rawValue : Font.medium.rawValue, size: 16.7))
.foregroundColor(Color(hex: viewModel.paymentMethod == .card ? "9970ff" : "eeeeee"))
.frame(width: (screenSize().width - 40) / 2)
.padding(.vertical, 16.7)
.background(
Color(hex: viewModel.paymentMethod == .card ? "9970ff" : "232323")
.opacity(viewModel.paymentMethod == .card ? 0.3 : 1)
)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(lineWidth: 1)
.foregroundColor(Color(hex: viewModel.paymentMethod == .card ? "9970ff" : "777777"))
)
.onTapGesture {
if viewModel.paymentMethod != .card {
viewModel.paymentMethod = .card
}
}
Text("계좌이체")
.font(.custom( viewModel.paymentMethod == .bank ? Font.bold.rawValue : Font.medium.rawValue, size: 16.7))
.foregroundColor(Color(hex: viewModel.paymentMethod == .bank ? "9970ff" : "eeeeee"))
.frame(width: (screenSize().width - 40) / 2)
.padding(.vertical, 16.7)
.background(
Color(hex: viewModel.paymentMethod == .bank ? "9970ff" : "232323")
.opacity(viewModel.paymentMethod == .bank ? 0.3 : 1)
)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(lineWidth: 1)
.foregroundColor(Color(hex: viewModel.paymentMethod == .bank ? "9970ff" : "777777"))
)
.onTapGesture {
if viewModel.paymentMethod != .bank {
viewModel.paymentMethod = .bank
}
}
}
.frame(width: screenSize().width - 26.7)
.padding(.top, 16.7)
HStack(spacing: 6.7) {
Image(viewModel.isTermsAgree ? "btn_select_checked" : "btn_select_normal")
.resizable()
.frame(width: 20, height: 20)
Text("구매조건 확인 및 결제 진행 동의")
.font(.custom(Font.medium.rawValue, size: 14.7))
.foregroundColor(Color(hex: "eeeeee"))
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
.padding(.top, 16.7)
.onTapGesture {
viewModel.isTermsAgree.toggle()
}
VStack(spacing: 6.7) {
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("충전된 캔의 유효기간은 충전 후 5년 입니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
.padding(.top, 26.7)
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("결제 취소는 결제 후 7일 이내에만 할 수 있습니다.\n단, 캔의 일부를 사용하면 결제 취소를 할 수 없습니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("광고성 이벤트 등 회사가 무료로 지급한 포인트는 환불되지 않습니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
HStack(alignment: .top, spacing: 0) {
Text("- ")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
Text("자세한 내용은 요즘라이브 이용약관에서 확인할 수 있습니다.")
.font(.custom(Font.medium.rawValue, size: 12))
.foregroundColor(Color(hex: "777777"))
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: screenSize().width - 53.4, alignment: .leading)
}
}
}
Spacer()
HStack(spacing: 0) {
VStack(alignment: .leading, spacing: 5) {
Text("결제금액")
.font(.custom(Font.medium.rawValue, size: 13.3))
.foregroundColor(Color(hex: "eeeeee"))
HStack(spacing: 0) {
Text("\(canResponse.price)")
.font(.custom(Font.bold.rawValue, size: 23.3))
.foregroundColor(Color(hex: "eeeeee"))
}
}
Spacer()
Text("결제하기")
.font(.custom(Font.bold.rawValue, size: 18.3))
.foregroundColor(.white)
.padding(.vertical, 16)
.frame(minWidth: 200)
.background(Color(hex: "9970ff"))
.cornerRadius(10)
.onTapGesture {
if viewModel.paymentMethod == nil {
viewModel.errorMessage = "결제수단을 선택해 주세요."
viewModel.isShowPopup = true
} else if !viewModel.isTermsAgree {
viewModel.errorMessage = "결제진행에 동의하셔야 결제가 가능합니다."
viewModel.isShowPopup = true
} else {
viewModel.chargeCan(canId: canResponse.id) {
viewModel.payload.orderName = canResponse.title
viewModel.payload.price = Double(canResponse.price)
viewModel.payload.taxFree = 0
viewModel.isShowPamentView = true
}
}
}
}
.padding(.leading, 22)
.padding(.trailing, 13.3)
.padding(.vertical, 13.3)
.background(Color(hex: "222222"))
.cornerRadius(16.7, corners: [.topLeft, .topRight])
if proxy.safeAreaInsets.bottom > 0 {
Rectangle()
.foregroundColor(Color(hex: "222222"))
.frame(width: proxy.size.width, height: 15.3)
}
}
.edgesIgnoringSafeArea(.bottom)
}
}
if viewModel.isLoading {
LoadingView()
}
}
.popup(isPresented: $viewModel.isShowPopup, type: .toast, position: .top, autohideIn: 2) {
GeometryReader { geo in
HStack {
Spacer()
Text(viewModel.errorMessage)
.padding(.vertical, 13.3)
.padding(.horizontal, 6.7)
.frame(width: geo.size.width - 66.7, alignment: .center)
.font(.custom(Font.medium.rawValue, size: 12))
.background(Color(hex: "9970ff"))
.foregroundColor(Color.white)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.cornerRadius(20)
.padding(.top, 66.7)
Spacer()
}
}
}
}
}
struct CanPgPaymentView_Previews: PreviewProvider {
static var previews: some View {
CanPgPaymentView(
canResponse: GetCanResponse(id: 1, title: "300 캔", can: 300, rewardCan: 0, price: 7500),
refresh: {},
afterCompletionToGoBack: false
)
}
}

View File

@@ -0,0 +1,123 @@
//
// CanPgPaymentViewModel.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import Foundation
import Combine
import Bootpay
enum PaymentMethod: String {
case card = "디지털카드"
case bank = "디지털계좌이체"
}
final class CanPgPaymentViewModel: ObservableObject {
private let repository = CanRepository()
private var subscription = Set<AnyCancellable>()
@Published var isTermsAgree = false
@Published var errorMessage = ""
@Published var isShowPopup = false
@Published var isLoading = false
@Published var isShowPamentView = false
@Published var paymentMethod: PaymentMethod? = nil
let payload = Payload()
func chargeCan(canId: Int, onSuccess: @escaping () -> Void) {
isLoading = true
repository.pgChargeCan(canId: canId)
.sink { result in
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { [unowned self] response in
self.isLoading = false
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponse<CanChargeResponse>.self, from: responseData)
if let data = decoded.data, decoded.success {
payload.applicationId = BOOTPAY_APP_ID
payload.pg = "웰컴페이먼츠"
payload.orderId = "\(data.chargeId)"
payload.method = paymentMethod!.rawValue
onSuccess()
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
}
self.isShowPopup = true
}
} catch {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
self.isShowPopup = true
}
}
.store(in: &subscription)
}
func verifyPayment(_ data: [String: Any], onSuccess: @escaping () -> Void) {
isLoading = true
let _data = data["data"] as? [String: Any]
if let data = _data {
let receiptId = data["receipt_id"] as! String
let orderId = data["order_id"] as! String
repository.pgVerify(receiptId: receiptId, orderId: orderId)
.sink { result in
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { [unowned self] response in
self.isLoading = false
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponseWithoutData.self, from: responseData)
if decoded.success {
onSuccess()
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
}
self.isShowPopup = true
}
} catch {
self.errorMessage = "다시 시도해 주세요.\n계속 같은 문제가 발생할 경우 고객센터로 문의 주시기 바랍니다."
self.isShowPopup = true
}
}
.store(in: &subscription)
} else {
isLoading = false
errorMessage = "본인인증 중 오류가 발생했습니다."
isShowPopup = true
}
}
}

View File

@@ -0,0 +1,12 @@
//
// PaymentGateway.swift
// SodaLive
//
// Created by klaus on 2023/08/11.
//
import Foundation
enum PaymentGateway: String, Codable {
case PG, APPLE_IAP
}