Authorize.net payment provider by VISA
Dear Developers and E-commerce Enthusiasts,
Are you ready to revolutionize the world of online stores with MedusaJS? We have an exciting opportunity that will make payment processing a breeze for our beloved Medusa platform! Introducing the Payment-Authorizenet provider, a community-driven project that brings the immensely popular Authorize.net payment gateway to our MedusaJS commerce stack.
What's in it for You?
🚀 Streamline Payment Processing: With payment-authorizenet-medusa, you can unleash the full potential of Authorize.net's features, ensuring seamless and secure payments for your customers.
Features:
Authorize Payment : Authorize funds on a customer's card without immediate charge.
Capture Payment : Charge the previously authorized funds.
Auth-and-Capture : Authorize and capture funds in a single seamless step.
Cancel Payment : Cancel an authorization before the payment is captured.
Void Payment : Void a transaction before it has been settled.
Refund Payment : Process refunds for transactions that have already been settled.
No hassle, no fuss! Install Payment-Authorizenet effortlessly with npm:
Authorize.net an immensely popular payment gateway with a host of features. This provider enables the Authorize.net payment interface on Medusa commerce stack
Use the package manager npm to install Payment-Authorizenet.
npm install payment-authorizenet-medusaRegister for a Authorize.net account and generate the api keys In your environment file (.env) define the API Login ID and Transaction Key:
1API_LOGIN_ID=<your AUTHORIZE_NET_API_LOGIN_ID>2TRANSACTION_KEY=<your AUTHORIZE_NET_TRANSACTION_KEY>You need to add the provider into your medusa-config.ts as shown below:
1module.exports = defineConfig({2modules: [3 { 4 resolve: "@medusajs/medusa/payment",5 options: {6 providers: [7 {8 resolve: "payment-authorizenet-medusa",9 id: "authorizenet",10 options: {11 api_login_id: process.env.AUTHORIZE_NET_API_LOGIN_ID,12 transaction_key: process.env.AUTHORIZE_NET_TRANSACTION_KEY,13 capture: <boolean>,14 enviornment: "sandbox", // <sandbox | production> based on enviornment Api's will point accordingly15 },16 },17 ],18 } 19 },20 ]21})For the NextJs start, make the following changes
Step 1.
Install package to your next starter. This simplifies the process by importing all the scripts implicitly
npm install authorizenet-reactor
yarn add authorizenet-reactStep 2.
Add environment variables in the client (storefront) (.env) file:
Note : To generate the Client Key, log in to the Merchant Interface as an Administrator and navigate to Account > Settings > Security Settings > General Security Settings > Manage Public Client Key
1ANUTHORIZENET_PUBLIC_CLIENT_KEY= <your ANUTHORIZENET PUBLIC CLIENT KEY>2 ANUTHORIZENET_PUBLIC_API_LOGIN_ID= <your ANUTHORIZENET API LOGIN ID>Step 3.
Add
1export const isAuthorizeNet = (providerId?: string) => {2 return providerId?.startsWith("pp_authorizenet")3}4
5
6// and the following to the list7
8 "pp_authorizenet_authorizenet":{9 title: "Credit Card", // or Authorize.net as per users perference 10 icon: <CreditCard />,11 },Step 4.
Add a AuthoirizenetCardConatiner in
1import { AuthorizeNetProvider,Card} from "authorizenet-react"2
3export const AuthorizeNetCardContainer = ({4 paymentProviderId,5 selectedPaymentOptionId,6 paymentInfoMap,7 disabled = false,8 setCardBrand,9 setError,10 setCardComplete,11 setOpaqueData,12 cardComplete13}: Omit<PaymentContainerProps, "children"> & {14 setCardBrand: (brand: string) => void15 setError: (error: string | null) => void16 setCardComplete: (complete: boolean) => void17 cardComplete:boolean18}) => {19 return (20 <PaymentContainer21 paymentProviderId={paymentProviderId}22 selectedPaymentOptionId={selectedPaymentOptionId}23 paymentInfoMap={paymentInfoMap}24 disabled={disabled}25 >26 {selectedPaymentOptionId === paymentProviderId &&27 ((isAuthorizeNet(selectedPaymentOptionId)) ? (28 <AuthorizeNetProvider 29 apiLoginId={process.env.NEXT_PUBLIC_API_LOGIN_ID} 30 clientKey={process.env.NEXT_PUBLIC_CLIENT_KEY}>31 <div className="my-4 transition-all duration-150 ease-in-out">32 <Text className="txt-medium-plus text-ui-fg-base mb-1">33 Enter your card details:34 </Text>35 <Card36 options={{37 style: {38 base: {39 fontSize: '16px',40 color: '#424770',41 '::placeholder': {42 color: '#aab7c4'43 }44 },45 invalid: {46 color: '#9e2146'47 }48 }49 50 }}51 onChange={(e:any)=>{ 52 setCardComplete(e.complete)53 setError(e.error?.message || null)54 }}55 />56 </div> 57 </AuthorizeNetProvider>58 ) : (59 <SkeletonCardDetails />60 ))}61 </PaymentContainer>62 )63}Step 5.
add AuthorizeNetCardContainer in the client
1import PaymentContainer, {2 StripeCardContainer,3 AuthorizeNetCardContainer4} from "@modules/checkout/components/payment-container"5
6 <>7 <RadioGroup8 value={selectedPaymentMethod}9 onChange={(value: string) => setPaymentMethod(value)}10 >11 {availablePaymentMethods.map((paymentMethod) => (12 <div key={paymentMethod.id}>13 {isStripeFunc(paymentMethod.id) ? (14 <StripeCardContainer15 paymentProviderId={paymentMethod.id}16 selectedPaymentOptionId={selectedPaymentMethod}17 paymentInfoMap={paymentInfoMap}18 setCardBrand={setCardBrand}19 setError={setError}20 setCardComplete={setCardComplete}21 />22 ) :23 (isAuthorizeNetFunc(paymentMethod.id) ? (24 <AuthorizeNetCardContainer25 paymentProviderId={paymentMethod.id}26 selectedPaymentOptionId={selectedPaymentMethod}27 paymentInfoMap={paymentInfoMap}28 setCardBrand={setCardBrand}29 setError={setError}30 setCardComplete={setCardComplete}31 setOpaqueData={setOpaqueData}32 cardComplete={cardComplete}33 />34 ): (35 <PaymentContainer36 paymentInfoMap={paymentInfoMap}37 paymentProviderId={paymentMethod.id}38 selectedPaymentOptionId={selectedPaymentMethod}39 />40 ))}41 </div>42 ))}43 </RadioGroup>44</>45 ....Step 6.
modify initiatePaymentSession in the client
1import {createToken} from "authorizenet-react"2
3
4 const handleSubmit = async () => {5 setIsLoading(true)6 try {7
8 const response = await createToken();9 10 const shouldInputCard =11 isStripeFunc(selectedPaymentMethod) && !activeSession12
13 const checkActiveSession =14 activeSession?.provider_id === selectedPaymentMethod15
16 if (!checkActiveSession) {17 await initiatePaymentSession(cart, {18 provider_id: selectedPaymentMethod,19 data: {20 ...response,21 cart // provides cart data to plugin22 },23 })24 }25
26 if (!shouldInputCard) {27 return router.push(28 pathname + "?" + createQueryString("step", "review"),29 {30 scroll: false,31 }32 )33 }34 } catch (err: any) {35 setError(err.message)36 } finally {37 setIsLoading(false)38 }39 }40 ....Step 7.
Create a button for Autorize.net
like below
1const AuthorizenetPaymentButton = ({ notReady }: { notReady: boolean }) => {2 const [submitting, setSubmitting] = useState(false)3 const [errorMessage, setErrorMessage] = useState<string | null>(null)4
5 const onPaymentCompleted = async () => {6 await placeOrder()7 .catch((err) => {8 setErrorMessage(err.message)9 })10 .finally(() => {11 setSubmitting(false)12 })13 }14
15 const handlePayment = () => {16 setSubmitting(true)17
18 onPaymentCompleted()19 }20
21 return (22 <>23 <Button24 disabled={notReady}25 isLoading={submitting}26 onClick={handlePayment}27 size="large"28 data-testid="submit-order-button"29 >30 Place order31 </Button>32 <ErrorMessage33 error={errorMessage}34 data-testid="manual-payment-error-message"35 />36 </>37 )38}Step 8.
Add into the payment element
then
1case isAuthorizeNet(paymentSession?.provider_id):2 return(3 <AuthorizenetPaymentButton4 notReady={notReady}5 data-testid={dataTestId}6 />7 )Caveat the default starter template has an option which says use the same shipping and billing address please ensure you deselect this and enter the phone number manually in the billing section.
For more info on medusa modules. Please refer https://docs.medusajs.com/learn
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
The code was tested on limited number of usage scenarios. There maybe unforseen bugs, please raise the issues as they come, or create pull requests if you'd like to submit fixes.