Skip to content
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

Stripe Feature #37

Merged
merged 2 commits into from
Dec 19, 2023
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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"pg": "^8.11.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0",
"stripe": "^14.9.0",
"tweetnacl": "^1.0.3",
"typeorm": "^0.3.17",
"uuid": "^9.0.0"
Expand Down
8 changes: 8 additions & 0 deletions src/common/config/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ export const configuration = () => ({
api_key: process.env.SENDGRID_API_KEY,
email: process.env.SENDGRID_EMAIL,
},
stripe: {
api_key: process.env.STRIPE_API_KEY,
api_version: process.env.STRIPE_API_VERSION,
webhook_secret: process.env.STRIPE_WEBHOOK_SECRET,
base_product: process.env.STRIPE_BASE_PRODUCT,
success_url: process.env.STRIPE_SUCCESS_URL,
error_url: process.env.STRIPE_ERROR_URL,
},
email_domains: process.env.EMAIL_DOMAINS,
storage_cost_usd: process.env.STORAGE_COST_USD,
});
1 change: 1 addition & 0 deletions src/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export const MAX_FILE_SIZE_1000MB = 1048576000;
export const NEAR_PRICE_USD_COINGECKO_URL =
'https://api.coingecko.com/api/v3/simple/price?ids=near&vs_currencies=usd';
export const MIME_TYPE_WAV = 'audio/wav';
export const default_currency = 'usd';
58 changes: 58 additions & 0 deletions src/common/email-templates/invoice-template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
export const invoiceLinkTemplate = (invoiceUrl: string) => `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
<title>Your Invoice Link</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
background-color: #fff;
border-radius: 8px;
margin: 20px auto;
max-width: 600px;
padding: 20px;
text-align: center;
}
.button {
background-color: #ff6b6b;
border: none;
border-radius: 4px;
color: #ffffff;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
font-weight: 500;
letter-spacing: 2px;
}

.button:hover {
filter: brightness(110%);
}
#built-on-near {
width: 250px;
}
</style>
</head>
<body>
<div class="container">
<img src="https://raidar-platform-images.s3.eu-central-1.amazonaws.com/berklee-logo.png" alt="Berklee Logo"/>
<h1>Your Invoice from Raidar</h1>
<p>Thank you for your purchase. You can view and download your invoice by clicking the link below:</p>
<a href="${invoiceUrl}" class="button" style="color: black; text-decoration: none;">View Invoice</a>
<p>If you have any questions, please contact support.</p>
<p>Sincerely,</p>
<p>The Raidar Team</p>
<img id="built-on-near" src="https://raidar-platform-images.s3.eu-central-1.amazonaws.com/built-on-near-black.png" alt="Built on NEAR Logo" />
</div>
</body>
</html>
`;
7 changes: 6 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,13 @@ import { TasksModule } from './modules/task/task.module';
import { CoingeckoModule } from './modules/coingecko/coingecko.module';
import { MarketplaceModule } from './modules/marketplace/marketplace.module';
import { ContractModule } from './modules/contract/contract.module';
import { StripeModule } from './modules/stripe/stripe.module';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
rawBody: true,
});
const configService = app.get(ConfigService);
app.useGlobalPipes(new ValidationPipe());

Expand All @@ -40,6 +44,7 @@ async function bootstrap() {
FileModule,
MarketplaceModule,
ContractModule,
StripeModule,
],
});

Expand Down
16 changes: 16 additions & 0 deletions src/migrations/1702992129177-stripe_attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class StripeAttributes1702992129177 implements MigrationInterface {
name = 'StripeAttributes1702992129177'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "licence" ADD "invoice_id" character varying(255)`);
await queryRunner.query(`ALTER TABLE "song" ADD "price_id" character varying(255)`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "song" DROP COLUMN "price_id"`);
await queryRunner.query(`ALTER TABLE "licence" DROP COLUMN "invoice_id"`);
}

}
2 changes: 2 additions & 0 deletions src/modules/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { CoingeckoModule } from '../coingecko/coingecko.module';
import { ScheduleModule } from '@nestjs/schedule';
import { MarketplaceModule } from '../marketplace/marketplace.module';
import { ContractModule } from '../contract/contract.module';
import { StripeModule } from '../stripe/stripe.module';

dotenv.config({
path: existsSync(`.env.${process.env.MODE}`)
Expand Down Expand Up @@ -48,6 +49,7 @@ dotenv.config({
CoingeckoModule,
MarketplaceModule,
ContractModule,
StripeModule,
],
controllers: [AppController],
providers: [
Expand Down
3 changes: 3 additions & 0 deletions src/modules/licence/licence.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,7 @@ export class Licence extends BaseEntity {

@Column({ type: 'varchar', length: 255, nullable: true })
sold_price: string;

@Column({ type: 'varchar', length: 255, nullable: true })
public invoice_id: string;
}
3 changes: 3 additions & 0 deletions src/modules/song/song.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ export class Song extends BaseEntity {
})
price: number;

@Column({ type: 'varchar', length: 255, nullable: true })
price_id: string;

@Column({
type: 'integer',
nullable: false,
Expand Down
3 changes: 2 additions & 1 deletion src/modules/song/song.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import { User } from '../user/user.entity';
import { EmailService } from '../email/email.service';
import { HttpModule } from '@nestjs/axios';
import { CoingeckoModule } from '../coingecko/coingecko.module';
import { StripeService } from '../stripe/stripe.service';

@Module({
imports: [
HttpModule,
TypeOrmModule.forFeature([Song, File, Album, User, Licence]),
CoingeckoModule,
],
providers: [SongService, EmailService],
providers: [SongService, EmailService, StripeService],
controllers: [SongController],
})
export class SongModule {}
7 changes: 7 additions & 0 deletions src/modules/song/song.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { ServiceResult } from '../../helpers/response/result';
import { EmailService } from '../email/email.service';
import { ConfigService } from '@nestjs/config';
import { CoingeckoService } from '../coingecko/coingecko.service';
import { StripeService } from '../stripe/stripe.service';

describe('SongService', () => {
let songService: SongService;
Expand Down Expand Up @@ -125,6 +126,12 @@ describe('SongService', () => {
send: jest.fn().mockReturnValue(true),
},
},
{
provide: StripeService,
useValue: {
createPrice: jest.fn().mockReturnValue('1'),
},
},
{
provide: ConfigService,
useValue: {
Expand Down
10 changes: 9 additions & 1 deletion src/modules/song/song.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import { ConfigService } from '@nestjs/config';
import { songDownloadTemplate } from '../../common/email-templates/song-dowload-template';
import { songBoughtTemplate } from '../../common/email-templates/song-bought-notif-template';
import { CoingeckoService } from '../coingecko/coingecko.service';
import { StripeService } from '../stripe/stripe.service';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const nearAPI = require('near-api-js');
Expand All @@ -64,6 +65,7 @@ export class SongService {
private readonly emailService: EmailService,
private readonly configService: ConfigService,
private readonly coingeckoService: CoingeckoService,
private readonly stripeService: StripeService,
) {}

async createSong(dto: CreateSongDto): Promise<ServiceResult<SongDto>> {
Expand Down Expand Up @@ -119,6 +121,12 @@ export class SongService {
if (!user) {
return new NotFound<SongDto>(`User not found!`);
}

const stripePrice = await this.stripeService.createPrice(dto.price);
if (!stripePrice) {
throw new Error('Failed to create price in Stripe');
}

const priceInNear = await this.coingeckoService.convertUsdToNear(
dto.price,
);
Expand All @@ -127,7 +135,7 @@ export class SongService {
const new_song = this.songRepository.create(
createSongMapper(dto, user, album, music_file, art_file),
);

new_song.price_id = stripePrice.id;
await this.songRepository.save(new_song);

const song = await this.songRepository.findOne(findOneSong(new_song.id));
Expand Down
50 changes: 50 additions & 0 deletions src/modules/stripe/stripe.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {
BadRequestException,
Controller,
Post,
Req,
UseFilters,
HttpCode,
Param,
RawBodyRequest,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { StripeService } from './stripe.service';
import { HttpExceptionFilter } from '../../helpers/filters/http-exception.filter';
import { AuthRequest } from '../../common/types/auth-request.type';
import { Auth } from '../../helpers/decorators/auth.decorator';
import { Role } from '../../common/enums/enum';
import { handle } from '../../helpers/response/handle';

@ApiTags('stripe')
@Controller('stripe')
export class StripeController {
constructor(private readonly stripeService: StripeService) {}

@Post('session/:songId')
@Auth(Role.User)
@UseFilters(new HttpExceptionFilter())
@HttpCode(200)
async createSession(
@Req() request: AuthRequest,
@Param('songId') songId: string,
) {
return handle(
await this.stripeService.createCheckoutSession(songId, request.user.id),
);
}

@Post('webhook')
@UseFilters(new HttpExceptionFilter())
async chargeCaptured(@Req() request: RawBodyRequest<Request>) {
if (!request.headers['stripe-signature']) {
throw new BadRequestException('Missing stripe-signature header');
}
return handle(
await this.stripeService.constructEventFromPayload(
request.headers['stripe-signature'],
request.rawBody,
),
);
}
}
15 changes: 15 additions & 0 deletions src/modules/stripe/stripe.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { StripeService } from './stripe.service';
import { StripeController } from './stripe.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '../user/user.entity';
import { Song } from '../song/song.entity';
import { Licence } from '../licence/licence.entity';
import { EmailService } from '../email/email.service';

@Module({
imports: [TypeOrmModule.forFeature([User, Song, Licence])],
controllers: [StripeController],
providers: [StripeService, EmailService],
})
export class StripeModule {}
Loading