Skip to content

Create webhook when config is created #1873

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/stripe/src/__tests__/mocks/mock-stripe-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ export const mockedStripeConfig = StripeConfig.create({
publishableKey: mockedStripePublishableKey,
restrictedKey: mockedStripeRestrictedKey,
webhookSecret: mockStripeWebhookSecret,
webhookId: "wh_123456789",
})._unsafeUnwrap();
11 changes: 5 additions & 6 deletions apps/stripe/src/app/api/stripe/webhook/webhook-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,10 @@ export class WebhookParams {
}
}

static createFromParams() {
// todo
}

createWebhookUrl() {
// todo
static createFromParams(params: { saleorApiUrl: SaleorApiUrl; configurationId: string }) {
return new WebhookParams({
saleorApiUrl: params.saleorApiUrl,
configurationId: params.configurationId,
});
}
}
4 changes: 4 additions & 0 deletions apps/stripe/src/modules/app-config/file-app-config-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
restrictedKey: z.string(),
publishableKey: z.string(),
webhookSecret: z.string(),
webhookId: z.string(),

Check warning on line 38 in apps/stripe/src/modules/app-config/file-app-config-repo.ts

View check run for this annotation

Codecov / codecov/patch

apps/stripe/src/modules/app-config/file-app-config-repo.ts#L38

Added line #L38 was not covered by tests
}),
),
channelMapping: z.record(z.string(), z.string()),
Expand All @@ -47,6 +48,7 @@
restrictedKey: config.restrictedKey,
publishableKey: config.publishableKey,
webhookSecret: config.webhookSecret,
webhookId: config.webhookId,

Check warning on line 51 in apps/stripe/src/modules/app-config/file-app-config-repo.ts

View check run for this annotation

Codecov / codecov/patch

apps/stripe/src/modules/app-config/file-app-config-repo.ts#L51

Added line #L51 was not covered by tests
};
}

Expand Down Expand Up @@ -175,6 +177,7 @@
restrictedKey: restrictedKey,
publishableKey: publishableKey,
webhookSecret: whSecret,
webhookId: resolvedConfig.webhookId,

Check warning on line 180 in apps/stripe/src/modules/app-config/file-app-config-repo.ts

View check run for this annotation

Codecov / codecov/patch

apps/stripe/src/modules/app-config/file-app-config-repo.ts#L180

Added line #L180 was not covered by tests
})._unsafeUnwrap();

return ok(stripeConfig);
Expand Down Expand Up @@ -226,6 +229,7 @@
publishableKey: createStripePublishableKey(configJson.publishableKey)._unsafeUnwrap(),
restrictedKey: createStripeRestrictedKey(configJson.restrictedKey)._unsafeUnwrap(),
webhookSecret: createStripeWebhookSecret(configJson.webhookSecret)._unsafeUnwrap(),
webhookId: configJson.webhookId,

Check warning on line 232 in apps/stripe/src/modules/app-config/file-app-config-repo.ts

View check run for this annotation

Codecov / codecov/patch

apps/stripe/src/modules/app-config/file-app-config-repo.ts#L232

Added line #L232 was not covered by tests
})._unsafeUnwrap();

return acc;
Expand Down
13 changes: 11 additions & 2 deletions apps/stripe/src/modules/app-config/stripe-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ describe("StripeConfig", () => {
publishableKey: mockedStripePublishableKey,
restrictedKey: mockedStripeRestrictedKey,
webhookSecret: mockStripeWebhookSecret,
webhookId: mockStripeWebhookSecret,
});

expect(result.isOk()).toBe(true);
Expand All @@ -38,6 +39,7 @@ describe("StripeConfig", () => {
publishableKey: mockedStripePublishableKey,
restrictedKey: mockedStripeRestrictedKey,
webhookSecret: mockStripeWebhookSecret,
webhookId: mockStripeWebhookSecret,
});

expect(result.isErr()).toBe(true);
Expand All @@ -52,6 +54,7 @@ describe("StripeConfig", () => {
publishableKey: mockedStripePublishableKey,
restrictedKey: mockedStripeRestrictedKey,
webhookSecret: mockStripeWebhookSecret,
webhookId: mockStripeWebhookSecret,
});

expect(result.isErr()).toBe(true);
Expand All @@ -66,6 +69,7 @@ describe("StripeConfig", () => {
publishableKey: mockedStripePublishableKeyTest,
restrictedKey: mockedStripeRestrictedKey,
webhookSecret: mockStripeWebhookSecret,
webhookId: mockStripeWebhookSecret,
})._unsafeUnwrapErr();

const instance2 = StripeConfig.create({
Expand All @@ -74,11 +78,16 @@ describe("StripeConfig", () => {
publishableKey: mockedStripePublishableKey,
restrictedKey: mockedStripeRestrictedKeyTest,
webhookSecret: mockStripeWebhookSecret,
webhookId: mockStripeWebhookSecret,
})._unsafeUnwrapErr();

expect(instance1).toMatchInlineSnapshot(`[ValidationError: Publishable key and restricted key must be of the same environment - TEST or LIVE]`);
expect(instance1).toMatchInlineSnapshot(
`[ValidationError: Publishable key and restricted key must be of the same environment - TEST or LIVE]`,
);

expect(instance2).toMatchInlineSnapshot(`[ValidationError: Publishable key and restricted key must be of the same environment - TEST or LIVE]`);
expect(instance2).toMatchInlineSnapshot(
`[ValidationError: Publishable key and restricted key must be of the same environment - TEST or LIVE]`,
);
});
});

Expand Down
5 changes: 5 additions & 0 deletions apps/stripe/src/modules/app-config/stripe-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export class StripeConfig {
readonly restrictedKey: StripeRestrictedKey;
readonly publishableKey: StripePublishableKey;
readonly webhookSecret: StripeWebhookSecret;
readonly webhookId: string;

static ValidationError = BaseError.subclass("ValidationError", {
props: {
Expand All @@ -24,18 +25,21 @@ export class StripeConfig {
restrictedKey: StripeRestrictedKey;
publishableKey: StripePublishableKey;
webhookSecret: StripeWebhookSecret;
webhookId: string;
}) {
this.name = props.name;
this.id = props.id;
this.restrictedKey = props.restrictedKey;
this.publishableKey = props.publishableKey;
this.webhookSecret = props.webhookSecret;
this.webhookId = props.webhookId;
}

static create(args: {
name: string;
id: string;
webhookSecret: StripeWebhookSecret;
webhookId: string;
restrictedKey: StripeRestrictedKey;
publishableKey: StripePublishableKey;
}): Result<StripeConfig, InstanceType<typeof StripeConfig.ValidationError>> {
Expand Down Expand Up @@ -72,6 +76,7 @@ export class StripeConfig {
restrictedKey: args.restrictedKey,
publishableKey: args.publishableKey,
webhookSecret: args.webhookSecret,
webhookId: args.webhookId,
}),
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { GetStripeConfigTrpcHandler } from "@/modules/app-config/trpc-handlers/get-stripe-config-trpc-handler";
import { GetStripeConfigsListTrpcHandler } from "@/modules/app-config/trpc-handlers/get-stripe-configs-list-trpc-handler";
import { NewStripeConfigTrpcHandler } from "@/modules/app-config/trpc-handlers/new-stripe-config-trpc-handler";
import { StripeWebhookManager } from "@/modules/stripe/stripe-webhook-manager";

Check warning on line 4 in apps/stripe/src/modules/app-config/trpc-handlers/app-config-router.ts

View check run for this annotation

Codecov / codecov/patch

apps/stripe/src/modules/app-config/trpc-handlers/app-config-router.ts#L4

Added line #L4 was not covered by tests
import { router } from "@/modules/trpc/trpc-server";

/**
* TODO Figure out end-to-end router testing (must somehow check valid jwt token)
*/
export const appConfigRouter = router({
getStripeConfig: new GetStripeConfigTrpcHandler().getTrpcProcedure(),
saveNewStripeConfig: new NewStripeConfigTrpcHandler().getTrpcProcedure(),
saveNewStripeConfig: new NewStripeConfigTrpcHandler({
webhookManager: new StripeWebhookManager(),
}).getTrpcProcedure(),

Check warning on line 14 in apps/stripe/src/modules/app-config/trpc-handlers/app-config-router.ts

View check run for this annotation

Codecov / codecov/patch

apps/stripe/src/modules/app-config/trpc-handlers/app-config-router.ts#L12-L14

Added lines #L12 - L14 were not covered by tests
getStripeConfigsList: new GetStripeConfigsListTrpcHandler().getTrpcProcedure(),
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const getTestCaller = () => {
token: mockedAppToken,
configRepo: mockedAppConfigRepo,
apiClient: mockedGraphqlClient,
appUrl: "https://localhost:3000",
}),
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,5 @@ export const newStripeConfigInputSchema = z.object({
);
}),
});

export type NewStripeConfigInput = z.infer<typeof newStripeConfigInputSchema>;
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { err, ok } from "neverthrow";
import Stripe from "stripe";
import { beforeEach, describe, expect, it, vi } from "vitest";

import { mockedAppConfigRepo } from "@/__tests__/mocks/app-config-repo";
Expand All @@ -7,16 +8,23 @@ import { mockedGraphqlClient } from "@/__tests__/mocks/graphql-client";
import { mockedStripePublishableKey } from "@/__tests__/mocks/mocked-stripe-publishable-key";
import { mockedStripeRestrictedKey } from "@/__tests__/mocks/mocked-stripe-restricted-key";
import { mockedSaleorApiUrl } from "@/__tests__/mocks/saleor-api-url";
import { mockStripeWebhookSecret } from "@/__tests__/mocks/stripe-webhook-secret";
import { TEST_Procedure } from "@/__tests__/trpc-testing-procedure";
import { BaseError } from "@/lib/errors";
import { NewStripeConfigTrpcHandler } from "@/modules/app-config/trpc-handlers/new-stripe-config-trpc-handler";
import { StripeClient } from "@/modules/stripe/stripe-client";
import { StripeWebhookManager } from "@/modules/stripe/stripe-webhook-manager";
import { router } from "@/modules/trpc/trpc-server";

const webhookCreator = new StripeWebhookManager();

/**
* TODO: Probably create some test abstraction to bootstrap trpc handler for testing
*/
const getTestCaller = () => {
const instance = new NewStripeConfigTrpcHandler();
const instance = new NewStripeConfigTrpcHandler({
webhookManager: webhookCreator,
});

// @ts-expect-error - context doesnt match but its applied in test
instance.baseProcedure = TEST_Procedure;
Expand All @@ -27,19 +35,38 @@ const getTestCaller = () => {

return {
mockedAppConfigRepo,
webhookCreator,
caller: testRouter.createCaller({
appId: mockedSaleorAppId,
saleorApiUrl: mockedSaleorApiUrl,
token: mockedAppToken,
configRepo: mockedAppConfigRepo,
apiClient: mockedGraphqlClient,
appUrl: "https://localhost:3000",
}),
};
};

describe("NewStripeConfigTrpcHandler", () => {
const stripe = new Stripe("key");

beforeEach(() => {
vi.resetAllMocks();

vi.spyOn(stripe.paymentIntents, "list").mockImplementation(() => {
return Promise.resolve({}) as Stripe.ApiListPromise<Stripe.PaymentIntent>;
});
vi.spyOn(StripeClient, "createFromRestrictedKey").mockImplementation(() => {
return {
nativeClient: stripe,
};
});
vi.spyOn(webhookCreator, "createWebhook").mockImplementation(async () =>
ok({
id: "whid_1234",
secret: mockStripeWebhookSecret,
}),
);
});

it("Returns error 500 if repository fails to save config", async () => {
Expand Down Expand Up @@ -109,20 +136,42 @@ describe("NewStripeConfigTrpcHandler", () => {
config: {
id: expect.any(String),
},
},
`
}, `
{
"appId": "saleor-app-id",
"config": {
"id": Any<String>,
"name": "Test config",
"publishableKey": "pk_live_1",
"restrictedKey": "rk_live_AAAAABBBBCCCCCEEEEEEEFFFFFGGGGG",
"webhookSecret": "whsec_TODO",
"webhookId": "whid_1234",
"webhookSecret": "whsec_XYZ",
},
"saleorApiUrl": "https://foo.bar.saleor.cloud/graphql/",
}
`,
);
`);
});

describe("Stripe Auth", () => {
it("Calls auth service and returns error if Stripe RK is invalid", () => {
// @ts-expect-error - mocking stripe client
vi.spyOn(stripe.paymentIntents, "list").mockImplementationOnce(async () => {
throw new Error("Invalid key");
});

const { caller } = getTestCaller();

return expect(() =>
caller.testProcedure({
name: "Test config",
publishableKey: mockedStripePublishableKey,
restrictedKey: mockedStripeRestrictedKey,
}),
).rejects.toThrowErrorMatchingInlineSnapshot(
`[TRPCError: Failed to create Stripe configuration. Restricted key is invalid]`,
);

expect(stripe.paymentIntents.list).toHaveBeenCalledOnce();
});
});
});
Loading
Loading