96 lines
2.5 KiB
TypeScript
96 lines
2.5 KiB
TypeScript
import { useState } from 'react'
|
|
import type { Article } from '@/types/nostr'
|
|
import type { AlbyInvoice } from '@/types/alby'
|
|
import { paymentService } from '@/lib/payment'
|
|
import { nostrService } from '@/lib/nostr'
|
|
|
|
export function useArticlePayment(
|
|
article: Article,
|
|
pubkey: string | null,
|
|
onUnlockSuccess?: () => void
|
|
) {
|
|
const [loading, setLoading] = useState(false)
|
|
const [error, setError] = useState<string | null>(null)
|
|
const [paymentInvoice, setPaymentInvoice] = useState<AlbyInvoice | null>(null)
|
|
const [paymentHash, setPaymentHash] = useState<string | null>(null)
|
|
|
|
const checkPaymentStatus = async (hash: string, userPubkey: string) => {
|
|
try {
|
|
const hasPaid = await paymentService.waitForArticlePayment(
|
|
hash,
|
|
article.id,
|
|
article.pubkey,
|
|
article.zapAmount,
|
|
userPubkey,
|
|
300000
|
|
)
|
|
|
|
if (hasPaid) {
|
|
const content = await nostrService.getPrivateContent(article.id, article.pubkey)
|
|
if (content) {
|
|
setPaymentInvoice(null)
|
|
setPaymentHash(null)
|
|
onUnlockSuccess?.()
|
|
} else {
|
|
setError('Content not available. Please contact the author.')
|
|
}
|
|
}
|
|
} catch (e) {
|
|
console.error('Payment check error:', e)
|
|
}
|
|
}
|
|
|
|
const handleUnlock = async () => {
|
|
if (!pubkey) {
|
|
setError('Please connect with Nostr first')
|
|
return
|
|
}
|
|
|
|
setLoading(true)
|
|
setError(null)
|
|
|
|
try {
|
|
const paymentResult = await paymentService.createArticlePayment({
|
|
article,
|
|
userPubkey: pubkey,
|
|
})
|
|
|
|
if (!paymentResult.success || !paymentResult.invoice || !paymentResult.paymentHash) {
|
|
setError(paymentResult.error ?? 'Failed to create payment invoice')
|
|
setLoading(false)
|
|
return
|
|
}
|
|
|
|
setPaymentInvoice(paymentResult.invoice)
|
|
setPaymentHash(paymentResult.paymentHash)
|
|
setLoading(false)
|
|
checkPaymentStatus(paymentResult.paymentHash, pubkey)
|
|
} catch (e) {
|
|
const errorMessage = e instanceof Error ? e.message : 'Failed to process payment'
|
|
console.error('Payment processing error:', e)
|
|
setError(errorMessage)
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
const handlePaymentComplete = async () => {
|
|
if (paymentHash && pubkey) {
|
|
await checkPaymentStatus(paymentHash, pubkey)
|
|
}
|
|
}
|
|
|
|
const handleCloseModal = () => {
|
|
setPaymentInvoice(null)
|
|
setPaymentHash(null)
|
|
}
|
|
|
|
return {
|
|
loading,
|
|
error,
|
|
paymentInvoice,
|
|
handleUnlock,
|
|
handlePaymentComplete,
|
|
handleCloseModal,
|
|
}
|
|
}
|