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

update readme #8

Merged
merged 2 commits into from
Feb 11, 2024
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
9 changes: 7 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,14 @@
"allowSeparatedGroups": true
},
],
"import/no-unresolved": "error",
"import/order": [
"import/no-unresolved": [
"error",
{
"ignore": ["^msw/.+"],
}
],
"import/order": [
"warn",
{
"groups": [
"builtin",
Expand Down
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"semi": false,
"trailingComma": "none",
"trailingComma": "all",
"singleQuote": false,
"tabWidth": 4,
"arrowParens": "avoid",
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ export const config: VendureConfig = {
shortCodeType: "SHORTCODE_TYPE",
passkey: "YOUR_PASSKEY",
environment: "APP_ENVIRONMENT",
vendureHost: "https://yourvendurestore.com"
})
]
vendureHost: "https://yourvendureserver.com",
}),
],
}
```

2. Start the server and navigate to `Settings > Payment methods`. Add a new payment method, selecting `Lipa na Mpesa Online` as the handler.

> Note: Select the 'Check whether Mpesa supports the payment' eligibility checker when creating the payment method.
> Be sure to select the 'Check whether Mpesa supports the payment' eligibility checker when creating the payment method. This plugin consumes the Mpesa Daraja API which currently only supports Safaricom numbers in Kenya.

3. Calling the `addPaymentToOrder` mutation on the storefront with the corresponing payment method code will initiate an STK push to the customer's phone.

Expand Down
2 changes: 1 addition & 1 deletion e2e/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const envSchema = z.object({
PASSKEY: z.string(),
ENVIRONMENT: z.enum(["sandbox", "live"]),
SHORTCODE_TYPE: z.enum(["till", "paybill"]),
VENDURE_HOST: z.string()
VENDURE_HOST: z.string(),
})

export const config = envSchema.parse(process.env)
22 changes: 11 additions & 11 deletions e2e/dev-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import {
DefaultLogger,
DefaultSearchPlugin,
LogLevel,
mergeConfig
mergeConfig,
} from "@vendure/core"
import {
SqljsInitializer,
createTestEnvironment,
registerInitializer,
testConfig
testConfig,
} from "@vendure/testing"

import { config } from "./config"
Expand All @@ -23,18 +23,18 @@ import { MpesaPlugin } from "../src/mpesa.plugin"

const devConfig = mergeConfig(testConfig, {
dbConnectionOptions: {
synchronize: true
synchronize: true,
},
logger: new DefaultLogger({ level: LogLevel.Debug }),
plugins: [
AssetServerPlugin.init({
assetUploadDir: path.join(__dirname, "__data__/assets"),
route: "assets"
route: "assets",
}),
DefaultSearchPlugin,
AdminUiPlugin.init({
port: 3050,
route: "admin"
route: "admin",
}),
MpesaPlugin.init({
consumerKey: config.CONSUMER_KEY,
Expand All @@ -43,21 +43,21 @@ import { MpesaPlugin } from "../src/mpesa.plugin"
shortCode: config.SHORTCODE,
passkey: config.PASSKEY,
shortCodeType: config.SHORTCODE_TYPE,
vendureHost: config.VENDURE_HOST
})
vendureHost: config.VENDURE_HOST,
}),
],
apiOptions: {
shopApiPlayground: true,
adminApiPlayground: true
}
adminApiPlayground: true,
},
})

const { server } = createTestEnvironment(devConfig)
await server.init({
initialData: {
...initialData,
shippingMethods: [{ name: "Standard Shipping", price: 500 }]
shippingMethods: [{ name: "Standard Shipping", price: 500 }],
},
productsCsvPath: path.join(__dirname, "product-import.csv")
productsCsvPath: path.join(__dirname, "product-import.csv"),
})
})()
13 changes: 8 additions & 5 deletions e2e/initial-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ export const initialData: InitialData = {
filters: [
{
code: "facet-value-filter",
args: { facetValueNames: ["computers"], containsAny: false }
}
]
}
args: {
facetValueNames: ["computers"],
containsAny: false,
},
},
],
},
],
paymentMethods: []
paymentMethods: [],
}
1 change: 1 addition & 0 deletions e2e/mocks/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const handlers = []
5 changes: 5 additions & 0 deletions e2e/mocks/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { setupServer } from "msw/node"

import { handlers } from "./handlers"

export const server = setupServer(...handlers)
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"eslint-plugin-prettier": "^5.1.3",
"husky": "^8.0.0",
"lint-staged": "^15.2.1",
"msw": "^2.1.7",
"prettier": "^3.2.5",
"rimraf": "^5.0.5",
"ts-node": "^10.9.2",
Expand Down
8 changes: 4 additions & 4 deletions src/api/callback-webhook.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
ChannelService,
LanguageCode,
Logger,
RequestContext
RequestContext,
} from "@vendure/core"

import { CALLBACK_URL_ENDPOINT, loggerCtx } from "../constants"
Expand All @@ -14,15 +14,15 @@ import { STKCallbackPayload } from "../types"
export class CallbackWebhookController {
constructor(
private channelService: ChannelService,
private mpesaService: MpesaService
private mpesaService: MpesaService,
) {}

@Post()
async handleCallback(@Body() payload: STKCallbackPayload) {
const { CheckoutRequestID, ResultCode } = payload.Body.stkCallback
Logger.info(
`Mpesa Callback ${CheckoutRequestID}, status: ${ResultCode}`,
loggerCtx
loggerCtx,
)

const ctx = await this.createRequestContext()
Expand All @@ -36,7 +36,7 @@ export class CallbackWebhookController {
isAuthorized: true,
authorizedAsOwnerOnly: false,
channel,
languageCode: LanguageCode.en
languageCode: LanguageCode.en,
})
}
}
4 changes: 2 additions & 2 deletions src/api/mpesa-shop.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ export class MpesaShopResolver {
@Mutation()
async verifyMpesaTransaction(
@Ctx() ctx: RequestContext,
@Args() args: { transactionId: string }
@Args() args: { transactionId: string },
): Promise<boolean> {
const isSuccessful = await this.mpesaService.verifyMpesaPayment(
ctx,
args.transactionId
args.transactionId,
)
return isSuccessful
}
Expand Down
12 changes: 6 additions & 6 deletions src/config/mpesa-eligibility-checker.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
LanguageCode,
Logger,
PaymentMethodEligibilityChecker
PaymentMethodEligibilityChecker,
} from "@vendure/core"

import { loggerCtx } from "../constants"
Expand All @@ -12,8 +12,8 @@ export const mpesaEligibilityChecker = new PaymentMethodEligibilityChecker({
description: [
{
languageCode: LanguageCode.en,
value: "Check whether Mpesa supports the payment"
}
value: "Check whether Mpesa supports the payment",
},
],
args: {},
check: async (_, order) => {
Expand All @@ -27,7 +27,7 @@ export const mpesaEligibilityChecker = new PaymentMethodEligibilityChecker({
if (!customerPhoneNumber) {
Logger.info(
"Could not get valid phone number from order",
loggerCtx
loggerCtx,
)
return false
}
Expand All @@ -36,11 +36,11 @@ export const mpesaEligibilityChecker = new PaymentMethodEligibilityChecker({
if (!isMpesaNumber) {
Logger.info(
`Phone number ${customerPhoneNumber} is not a Safaricom number`,
loggerCtx
loggerCtx,
)
return false
}

return true
}
},
})
14 changes: 7 additions & 7 deletions src/config/mpesa.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
CreatePaymentResult,
Injector,
LanguageCode,
PaymentMethodHandler
PaymentMethodHandler,
} from "@vendure/core"

import { MpesaService } from "../service/mpesa.service"
Expand All @@ -13,7 +13,7 @@ let mpesaService: MpesaService
export const mpesaPaymentMethodHandler = new PaymentMethodHandler({
code: "mpesa",
description: [
{ languageCode: LanguageCode.en, value: "Lipa na Mpesa Online" }
{ languageCode: LanguageCode.en, value: "Lipa na Mpesa Online" },
],
args: {},
init(injector: Injector) {
Expand All @@ -28,26 +28,26 @@ export const mpesaPaymentMethodHandler = new PaymentMethodHandler({
const result = await mpesaService.initiateStkPush(
amountInShillings,
phoneNumber,
order.code
order.code,
)

if (!result) {
return {
amount: order.totalWithTax,
state: "Declined",
errorMessage: "Could not initiate Mpesa payment."
errorMessage: "Could not initiate Mpesa payment.",
}
}

return {
amount: order.totalWithTax,
state: "Authorized",
transactionId: result.CheckoutRequestID
transactionId: result.CheckoutRequestID,
}
},
settlePayment: async () => {
return {
success: true
success: true,
}
}
},
})
12 changes: 6 additions & 6 deletions src/mpesa.plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,24 +63,24 @@ export interface MpesaPluginOptions {
controllers: [CallbackWebhookController],
configuration: config => {
config.paymentOptions.paymentMethodHandlers.push(
mpesaPaymentMethodHandler
mpesaPaymentMethodHandler,
)
config.paymentOptions.paymentMethodEligibilityCheckers?.push(
mpesaEligibilityChecker
mpesaEligibilityChecker,
)
return config
},
shopApiExtensions: {
schema: shopApiExtensions,
resolvers: [MpesaShopResolver]
resolvers: [MpesaShopResolver],
},
providers: [
{
provide: MPESA_PLUGIN_INIT_OPTIONS,
useFactory: () => MpesaPlugin.options
useFactory: () => MpesaPlugin.options,
},
MpesaService
]
MpesaService,
],
})
export class MpesaPlugin {
static options: MpesaPluginOptions
Expand Down
Loading
Loading