import { Component, Input, OnDestroy, OnInit } from "@angular/core"
import Connect from "@mono.co/connect.js"
@Component({
selector: "app-link-mono-account",
templateUrl: "./link-mono-account.component.html"
})
export class LinkMonoAccountComponent implements OnInit, OnDestroy {
@Input({ required: true }) customerId!: string
private connect: any
ready = false
ngOnInit() {
this.connect = new Connect({
key: "PUBLIC_KEY",
scope: "auth",
data: {
customer: { id: this.customerId }
},
onLoad: () => {
this.ready = true
},
onSuccess: ({ code }) => this.exchangeCode(code),
onClose: () => console.log("Connect closed")
})
this.connect.setup()
}
open() {
this.connect?.open()
}
ngOnDestroy() {
this.connect?.close()
}
private async exchangeCode(code: string) {
const response = await fetch("/api/mono/exchange", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code })
})
if (!response.ok) {
throw new Error("Could not complete Mono account linking")
}
}
}