Gateway Pembayaran Authorize.net Dengan Node.js - CRUDPRO

Gateway Pembayaran Authorize.net Dengan Node.js

Gateway Pembayaran Authorize.net Dengan Node.js

Halo semua, saya berharap Anda semua baik-baik saja!

Hari ini, kita akan masuk ke dunia gateway pembayaran dengan menerapkan Authorize.net dengan NodeJS.

Saat sebelum kita awali, penting untuk pahami keutamaan gateway pembayaran di dunia e-commerce dan transaksi bisnis online. Gateway pembayaran bertindak selaku bridge di antara pedagang dan konsumen setia, memberikan fasilitas proses pembayaran online dan pastikan keamanan info keuangan yang peka. Authorize.net ialah gateway pembayaran yang kaya dan sering dipakai, dan dalam artikel ini, kita akan mengeksploitasi bagaimana kita bisa memadukannya dengan NodeJS.

Saat sebelum kita awali membuat code, penting untuk jadi perhatian jika untuk memakai API Authorize.net, Anda harus membuat account kotak pasir dengan ikuti link ini: https://developer.authorize.net/hello_world/sandbox.html. Ini akan memberikan Anda akses ke API dan memungkinkannya Anda untuk mengetes implikasi Anda saat sebelum disiarkan. Anda harus juga memperoleh kunci masuk API dan kunci transaksi bisnis dari link berikut ini: https://dukungan.authorize.net/knowledgebase/Knowledgearticle/?code=000001560#:~:text=3.0-,Answer,-To %20obtain%20the dan https://developer.authorize.net/hello_world/common_setup_questions.html#:~:text=To%20obtain%20the%20transaction%20key%3A.

Pada artikel ini, saya akan mengulas dua hal khusus: membebankan jumlah tertentu dan mengembalikan dana. Saya akan memakai NestJS sebagai frame-work, tapi ide yang dibahas dalam artikel ini bisa secara mudah diaplikasikan ke frame-work lain seperti Kilat. Code yang diberi ialah versus refactored dari code yang disiapkan oleh Authorize.net, saya membuat code lebih minimalis dan memakai promise dibanding callback untuk keringanan pemakaian.

Peranan Kartu Jumlah Ongkos:

export const chargeAmount = async (chargePayload: IChargeAmount) => {
  const { price, cardDetails, authorizeCrendintals } = chargePayload;
  const { cardNumber, expiry, cvc } = cardDetails;
  const { apiLoginKey, transactionKey } = authorizeCrendintals;
  const expiryDate = expiry.split("/")?.join("")?.split(" ")?.join("");
  const card = cardNumber?.split(" ")?.join("");
  const merchantAuthenticationType =
    new ApiContracts.MerchantAuthenticationType();
  merchantAuthenticationType.setName(apiLoginKey);
  merchantAuthenticationType.setTransactionKey(transactionKey);

  const creditCard = new ApiContracts.CreditCardType();
  creditCard.setCardNumber(card);
  creditCard.setExpirationDate(expiryDate);
  creditCard.setCardCode(cvc);

  const paymentType = new ApiContracts.PaymentType();
  paymentType.setCreditCard(creditCard);

  const transactionSetting1 = new ApiContracts.SettingType();
  transactionSetting1.setSettingName("duplicateWindow");
  transactionSetting1.setSettingValue("120");

  const transactionSettings = new ApiContracts.ArrayOfSetting();

  const transactionRequestType = new ApiContracts.TransactionRequestType();
  transactionRequestType.setTransactionType(
    ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION
  );
  transactionRequestType.setPayment(paymentType);
  transactionRequestType.setAmount(price);
  transactionRequestType.setTransactionSettings(transactionSettings);


  const createRequest = new ApiContracts.CreateTransactionRequest();
  createRequest.setMerchantAuthentication(merchantAuthenticationType);
  createRequest.setTransactionRequest(transactionRequestType);

  const ctrl = new ApiControllers.CreateTransactionController(
    createRequest.getJSON()
  );
  const chargeAmountPromise = new Promise((resolve, reject) => {
    ctrl.execute(function () {
      let apiResponse = ctrl.getResponse();

      let response = new ApiContracts.CreateTransactionResponse(apiResponse);
      response;
      let errorMessage;
      if (response != null) {
        if (
          response.getMessages().getResultCode() ==
          ApiContracts.MessageTypeEnum.OK
        ) {
          if (response.getTransactionResponse().getMessages() != null) {
            resolve(response);
          } else {
            if (response.getTransactionResponse().getErrors() != null) {
              errorMessage = response
                .getTransactionResponse()
                .getErrors()
                .getError()[0]
                .getErrorText();
              reject({ errormessage: errorMessage, statusCode: 400 });
            }
          }
        } else {
          if (
            response.getTransactionResponse() != null &&
            response.getTransactionResponse().getErrors() != null
          ) {
            errorMessage = response
              .getTransactionResponse()
              .getErrors()
              .getError()[0]
              .getErrorText();
            reject({ errormessage: errorMessage, statusCode: 400 });
          }
        }
      } else {
        reject({
          errormessage: "unable to process the payemnt",
          statusCode: 424,
        });
      }
    });
  });
  try {
    return await chargeAmountPromise;
  } catch (error) {
    throw new HttpException(
      errorApiWrapper(error.errormessage, error.statusCode),
      error.statusCode
    );
  }
};

Ini ialah sistem jumlah bill, peranan ini beberapa argument yang disebut harga yang ingin Anda bebankan, Anda mempertimbangkan kredensial authrioze.net untuk meminta jumlah, argument paling akhir ialah detil kartu object pemakai yang Anda gunakan ongkos untuk suatu hal. sebuah hal.

satu perihal yang penting jadi perhatian: Sama seperti yang saya ucapkan awalnya jika code ini dicatat dalam nestjs, jadi saya sudah membuat peranan dan sediakan semua patokan peranan dari service pembayaran, tapi ini terserah Anda bagaimana ingin memakainya.

Code ini ialah versus refactored dari code yang disiapkan oleh authorize.net tersebut, saya hapus semua sektor yang tidak dibutuhkan. Anda bisa memakai sektor lain sama sesuai keperluan usaha Anda seperti pengangkutan, pajak, bea, dan yang lain. Silahkan check deskripsi sektor yang disuruh di bawah code, disini Anda akan memperoleh gagasan mengenai sektor yang mana harus dan yang mana tidak.

Code Antar-muka IChargeAmount:

export interface IChargeAmount{
    price:string;
    authorizeCrendintals:{
        transactionKey:string;
        apiLoginKey:string;
        // transactionId:string;
    }
    cardDetails:{
        cardNumber:string; 
        expiry:string; 
        cvc:string;
    }
}

Kode fungsi jumlah pengembalian dana:

export async function refundUsersPayment(refundRequestPayload: IRefundRequestPaload) {
  const { price, cardDetails, transactionId, authorizeCrendintals } = refundRequestPayload;
  const { cardNumber, expiry } = cardDetails;
  const { apiLoginKey, transactionKey } = authorizeCrendintals;
  const merchantAuthenticationType =
    new ApiContracts.MerchantAuthenticationType();
  merchantAuthenticationType.setName(apiLoginKey);
  merchantAuthenticationType.setTransactionKey(transactionKey);

  const creditCard = new ApiContracts.CreditCardType();
  creditCard.setCardNumber(cardNumber);
  creditCard.setExpirationDate(expiry);

  const paymentType = new ApiContracts.PaymentType();
  paymentType.setCreditCard(creditCard);

  const transactionRequestType = new ApiContracts.TransactionRequestType();
  transactionRequestType.setTransactionType(
    ApiContracts.TransactionTypeEnum.REFUNDTRANSACTION
  );
  transactionRequestType.setPayment(paymentType);
  transactionRequestType.setAmount(price);
  transactionRequestType.setRefTransId(transactionId);

  const createRequest = new ApiContracts.CreateTransactionRequest();
  createRequest.setMerchantAuthentication(merchantAuthenticationType);
  createRequest.setTransactionRequest(transactionRequestType);

  

  const ctrl = new ApiControllers.CreateTransactionController(
    createRequest.getJSON()
  );

  const refundedPaymentPromise = new Promise((resolve, reject) => {
    ctrl.execute(function () {
      const apiResponse = ctrl.getResponse();
      const response = new ApiContracts.CreateTransactionResponse(apiResponse);


      if (response != null) {
        if (
          response.getMessages().getResultCode() ==
          ApiContracts.MessageTypeEnum.OK
        ) {
          if (response.getTransactionResponse().getMessages() != null) {
            resolve("Payement Refunded...");
            return;
          } else {
            if (response.getTransactionResponse().getErrors() != null) {
              let errorMessage = response
                ?.getTransactionResponse()
                ?.getErrors()
                ?.getError()[0]
                ?.getErrorText();
              reject({ errormessage: errorMessage, statusCode: 400 });
            }
          }
        } else {
          if (
            response.getTransactionResponse() != null &&
            response.getTransactionResponse().getErrors() != null
          ) {
            let errorMessage = response
              ?.getTransactionResponse()
              ?.getErrors()
              ?.getError()[0]
              ?.getErrorText();
            reject({ errormessage: errorMessage, statusCode: 400 });
          } else {
            let errorMessage = response
              ?.getTransactionResponse()
              ?.getErrors()
              ?.getError()[0]
              ?.getErrorText();
            reject({ errormessage: errorMessage, statusCode: 424 });
          }
        }
      } else {
        reject({
          errormessage: "unable to refund payment, please try again",
          statusCode: 424,
        });
      }
    });
  });
  try {
    return await refundedPaymentPromise;
  } catch (error) {
    throw new HttpException(
      errorApiWrapper(error.errormessage, error.statusCode),
      error.statusCode
    );

Kode interface IRefundRequestPaload:

export interface IRefundRequestPaload{
    price:string;
    transactionId:string; 
    authorizeCrendintals:{
        transactionKey:string;
        apiLoginKey:string;
    }
    cardDetails:{
        cardNumber:string; 
        expiry:string; 
    }
}

catatan: untuk sistem ini Anda harus simpan detil kartu credit pemakai, cuma empat digit paling akhir kartu dan masa aktif kartu yang dibutuhkan untuk lakukan transaksi bisnis pengembalian dana. Terserah Anda bagaimana Anda simpan ini di database, tapi praktek terbaik ialah mengenkripsi nilai-nilai ini lebih dulu lalu menyimpan di database.

Saya sudah ikuti semua praktek terbaik yang saya kenali, tapi tolong beritahu saya di komentar bila saya melewatinya.

Saya pahami jika menerapkan gateway pembayaran menjadi pekerjaan yang mengerikan, tapi saya berharap artikel ini memberikan Anda pengetahuan dan info yang Anda butuhkan untuk mengawali. Saya sudah coba membuat segampang kemungkinan untuk dimengerti dan diaplikasikan, tapi bila Anda mempunyai pertanyaan atau membutuhkan verifikasi selanjutnya, silahkan kontak di komentar. Terima kasih sudah membaca dan sampai jumpa di artikel kami seterusnya.