File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { freemius } from '@/lib/freemius' ;
2+ import { deleteEntitlement , renewCreditsFromWebhook , syncEntitlementFromWebhook } from '@/lib/user-entitlement' ;
3+
4+ const listener = freemius . webhook . createListener ( ) ;
5+
6+ listener . on (
7+ [
8+ 'license.created' ,
9+ 'license.extended' ,
10+ 'license.shortened' ,
11+ 'license.updated' ,
12+ 'license.cancelled' ,
13+ 'license.expired' ,
14+ 'license.plan.changed' ,
15+ ] ,
16+ async ( { objects : { license } } ) => {
17+ if ( license && license . id ) {
18+ await syncEntitlementFromWebhook ( license . id ) ;
19+ }
20+ }
21+ ) ;
22+
23+ listener . on ( 'license.deleted' , async ( { data } ) => {
24+ await deleteEntitlement ( data . license_id ) ;
25+ } ) ;
26+
27+ listener . on ( 'license.extended' , async ( { data } ) => {
28+ if ( data . is_renewal ) {
29+ renewCreditsFromWebhook ( data . license_id ) ;
30+ }
31+ } ) ;
32+
33+ const processor = freemius . webhook . createRequestProcessor ( listener ) ;
34+
35+ export { processor as POST } ;
Original file line number Diff line number Diff line change @@ -72,6 +72,35 @@ export const getFsUser: UserRetriever = async () => {
7272 return freemius . entitlement . getFsUser ( entitlement , email ) ;
7373} ;
7474
75+ export async function syncEntitlementFromWebhook ( fsLicenseId : string ) : Promise < void > {
76+ const purchaseInfo = await freemius . purchase . retrievePurchase ( fsLicenseId ) ;
77+ if ( purchaseInfo ) {
78+ await processPurchaseInfo ( purchaseInfo ) ;
79+ }
80+ }
81+
82+ export async function deleteEntitlement ( fsLicenseId : string ) : Promise < void > {
83+ await prisma . userFsEntitlement . delete ( {
84+ where : { fsLicenseId : fsLicenseId } ,
85+ } ) ;
86+ }
87+
88+ export async function renewCreditsFromWebhook ( fsLicenseId : string ) : Promise < void > {
89+ const purchaseInfo = await freemius . purchase . retrievePurchase ( fsLicenseId ) ;
90+
91+ if ( purchaseInfo ) {
92+ const credits = getCreditsForPurchase ( purchaseInfo ) ;
93+
94+ const entitlement = await prisma . userFsEntitlement . findUnique ( {
95+ where : { fsLicenseId } ,
96+ } ) ;
97+
98+ if ( entitlement && credits > 0 ) {
99+ await addCredits ( entitlement . userId , credits ) ;
100+ }
101+ }
102+ }
103+
75104//#endregion
76105
77106// #region Credit & Entitlement Management
You can’t perform that action at this time.
0 commit comments