midtrans / midtrans-nodejs-client Goto Github PK
View Code? Open in Web Editor NEWOfficial Midtrans Payment API Client for Node JS | https://midtrans.com
License: MIT License
Official Midtrans Payment API Client for Node JS | https://midtrans.com
License: MIT License
Halo, saya mendapatkan error "Credit card token is no longer available. Please create a new one." ketika implementasi card payment. untuk token sendiri aku dapatkan dari response success midtrans-new-3ds. bagaimana mengatasinya?
env = production
window.snap.pay(post.transaction.redirect_url, {
onSuccess: async (result) => {
console.log(result, "result");
},
onPending: async (result) => {
return alert("Pending");
// return settemp(temp.concat(result));
},
onError: async (result) => {
return alert("Error");
// return settemp(temp.concat(result));
},
});
says membuat website dimana pembayaran menggunakan midtrans semua berjalan baik baik saja sampai callback pending berjalan dua kali
It is possible to add custom field in snap API? My goal is to attach additional data (e.g customer_id) on HTTP notification webhook.
I found this on api docs:
Set Custom Fields is a feature that enables merchants to charge a transaction with a unique data according to the merchant's need. Midtrans provides merchants with 3 custom fields that can be used for various utilities.
It seems I could not find my way there using snap API.
I've already added the desired field label name from general settings in my merchant admin portal, and send it upon createTransaction() call (alongside the required data such as transaction_details, payment_type, etc). But everytime I received the HTTP notification POST data, I can't find my custom field data.
Thank you in advance.
Halo mas @rizdaprasetya maaf mas, saya ingin bertanya. saya di sini kesulitan terkait melakukan callback midtrans setelah user melakukan pembayaran yang dimana saya harus mengupdate status transaksi saya dengan mengecek apakah fraud status nya ini accept, failure dll. Di sini lebih tepat nya saya harus menggunakan method yang mana dan mohon maaf mas bisa berikan contoh implementasinya agar saya bisa lebih mengerti cara penggunaan nya mas. Terima kasih :)
Sorry if this issue not belongs this repo but I don't see any special repository for snap products.
"expired" status is ambiguous on a transaction detail/status and when receiving a callback.
On the transaction status, I get a json response with "expire" word. But at the time of the callback, the status is "expired" (there is letter d). Is this really intentional or is there an error?
It is recommended that this be generalized to prevent future errors.
Then, I want to report a layout problem with snap for the customer section that should be corrected because there was a not used bootstrap column (col-md-6). It should be removed just so that the customer email can be sideways.
Thanks!
Hello Pak Rizda, izin bertanya apakah midtrans memungkingkan registrasi user melalui API kedepannya, pak? Terima kasih.
Kenapa server mengirimkan response status 401 di mode production?
Sebelumnya saya test di mode sandbox berhasil tidak ada kendala.
Berikut adalah response yang saya dapet di mode production:
{
"status_code": "401",
"status_message": "Transaction cannot be authorized with the current client/server key.",
"id": "1679fb5e-31b2-49e0-bbae-cec703a5cdde"
}
Berikut adalah request dari servernya:
const midtransClient = require('midtrans-client');
const midtrans = new midtransClient.CoreApi({
isProduction: true,
serverKey: 'SERVER_KEY',
clientKey: 'CLIENT_KEY',
});
module.exports.charge = async (req, res) => {
try {
const promise = await midtrans.charge(req.body);
return res.send(promise);
} catch (err) {
return res.status(err.httpStatusCode).send(err.ApiResponse);
}
};
Mungkin ada yang bisa bantu jawab, saya pertama kali menggunakan midtrans sampe di mode production, atau apakah musti kontak pihak midtrans jika mau mengganti mode ke production?
Terima kasih
sudo journalctl -u node-xxx -n 100 --no-pager
(node:1671271) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
Oct 26 16:05:24 imt node-[1671271]: --> starting at object with constructor 'ClientRequest'
Oct 26 16:05:24 imt node-[1671271]: | property 'socket' -> object with constructor 'TLSSocket'
Oct 26 16:05:24 imt node-[1671271]: --- property '_httpMessage' closes the circle
Oct 26 16:05:24 imt node-[1671271]: at JSON.stringify (<anonymous>)
Oct 26 16:05:24 imt node-[1671271]: at stringify (/var/www/html/api/xxxx/node_modules/express/lib/response.js:1123:12)
Oct 26 16:05:24 imt node-[1671271]: at ServerResponse.json (/var/www/html/api/xxxx/node_modules/express/lib/response.js:260:14)
Oct 26 16:05:24 imt node-[1671271]: at ServerResponse.send (/var/www/html/api/xxxx/node_modules/express/lib/response.js:158:21)
Oct 26 16:05:24 imt node-[1671271]: at Object.exports.err (/var/www/html/api/xxxx/src/utils/res.js:17:26)
Oct 26 16:05:24 imt node-[1671271]: at /var/www/html/api/xxxx/src/controllers/notification.controller.js:55:26
Oct 26 16:05:24 imt node-[1671271]: at processTicksAndRejections (internal/process/task_queues.js:93:5)
Oct 26 16:05:24 imt node-[1671271]: (Use `node --trace-warnings ...` to show where the warning was created)
https://docs.midtrans.com/en/after-payment/http-notification
let notificationJson = req.body;
apiClient.transaction.notification(notificationJson)
not solve dunno why, https://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json , i have seen on #34 its work properly right ?
let notificationJson = stringify(req.body);
let sss = JSON.stringify({ ...req.body });
let sssd = req.body;
console.log(`notificationJson : ${notificationJson}`);
console.log(`notificationJson : ${req.body}`);
console.log(`notificationJson : ${sss}`);
console.log(`notificationJson : ${sssd}`);
serverKey : SB-Mid-server-xxx. clientKey : SB-Mid-client-xx-xxx
Oct 26 17:32:11 imt xx[1676873]: notificationJson : [{"statusResponse":"1"},{"transaction_time":"2","no":"3"},"yogi","as"]
Oct 26 17:32:11 imt xx[1676873]: notificationJson : [object Object]
Oct 26 17:32:11 imt xx[1676873]: notificationJson : {"statusResponse":{"transaction_time":"yogi","no":"as"}}
Oct 26 17:32:11 imt xx[1676873]: notificationJson : [object Object]
Hi, thanks for great snapjs payment to ease us doing a payment!
disclaimer: Im using https://app.sandbox.midtrans.com/snap/snap.js
, am i put this issue in the correct place? I can't find the repo regarding this snap js to put an issue.
This issue only happened in iOS 12, but it is fine in latest iOS. Here full log:
Error: snap.pay is not allowed to be called in this state. Invalid state transition from PopupInView to PopupInView (anonymous function) — snap.js:232
ex — 8967.304662da3cf90d03.js:148
onSuccess — 8967.304662da3cf90d03.js:144
promiseReactionJob
I call the window snap like:
if (!('snap' in window)) {
const script = document.createElement('script')
script.type = 'text/javascript'
script.dataset.clientKey = process.env.NEXT_PUBLIC_MIDTRANS_CLIENT_KEY ?? '' // prettier-ignore
script.src = midtrans('/snap/snap.js')
script.onload = () => onCallback(token, payload)
document.head.append(script)
return
}
onCallback(token, payload)
where onCallback
is:
window.snap.pay(token, {
onSuccess: (result: unknown) => {
const { transaction: trx } = paymentType.shape
const transaction = trx.parse(result)
checkout([...detail.payment, { ...payload, transaction }])
},
})
Help to explain why the error happened, or snap.js not supported in iOS 12 ? Thankyou!
snap.js: https://app.sandbox.midtrans.com/snap/snap.js
Hi, thanks for the library, currently i have problem with the import statement
how can I import the package using ejs syntax in my client?
import snap from 'midtrans-client'
currently the available docs only explain about common js import
const blah = require('midtrans-client')
thank you
Saya sudah coba mengakses API menggunakan URL https://api.sandbox.midtrans.com/v1/statements tetapi mendapatkan 404, apakah saya salah mengakses link ?
saya tidak menemukan cara lain untuk akses data Transaction List ini
I'm using TypeScript and don't see any type from your library.
And it bothers me a lot.
I create my own using this command
tsc ./node_modules/midtrans-client/index.js ./node_modules/midtrans-client/lib/*.js --declaration --allowjs --emitDeclarationOnly --outFile @types/midtrans.d.ts
I thing you can provide better one with creating npm package @types/midtrans-client.
You are a big company. and it's a shame if you can't give something like that (at least for me).
Hi, saya ingin bertanya apakah ada cara, referensi, atau dokumentasi untuk melanjutkan transaksi yang telah terbuat sebelumnya? Saya mendapatkan kesulitan mencari permasalahan yang saya cari, baik di website dokumentasi resmi, google, dan lainnya. Terima kasih.
In the Midtrans documentation, it is shown that we can override the webhook url via headers, How can I achieve the same result using this library ?
https://docs.midtrans.com/docs/https-notification-webhooks#customizing-notification-url-via-api
I've seen this example how to handle the transaction status
https://github.com/Midtrans/midtrans-nodejs-client/blob/master/examples/expressApp/app.js#L87
But what if i just use the req.body
to handle transaction status directly, instead of
core.transaction.status(req.body.transaction_id).then(transactionObject)
to get transaction status and handle it from that.
Aren't they basically same data?
Is it has "secure" thing purposes using CoreAPI rather than the req.body itself?
Example, i can get the transaction_id directly from req.body.transaction_id
instead of transactionObject.transaction_id
Assalamu'alaikum teman-teman. Saya mau minta tolong. Disini saya sedang membuat pembayaran di aplikasi menggunakan Snap dari Midtrans. Tapi terkendala ketika memilih salah satu metode pembayarannya tidak bisa jalan. Saya menggunakan webview_flutter versi 4.0.2.
di log muncul [INFO:CONSOLE(1)] "Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://app.sandbox.midtrans.com') does not match the recipient window's origin ('null').", source: https://app.sandbox.midtrans.com/snap/snap.js (1)
Saya sedang mengintegraskan dengan menggunakan CoreAPI dan next js
tapi kenapa selalu kena cors ya?
saat saya menjalankan code midatransSnap.transaction.notification(notificationJson);
saya mendapatkan error
2021-08-19T17:32:49.789Z error: /v1/transaction/payment_status - 127.0.0.1 - ReferenceError: notificationJson is not defined
apakah bisa dibantu? Terima kasih
Thanks for this awesome SDK. Are there any plans to rewrite this in Typescript? I would love to help
Can i revoke snap token that generated from createTransaction()
method?
Saya baru belajar reactjs dan mencoba membuat ecommerce dengan API ke Laravel untuk backendnya. Mohon bantuannya bagaimana cara saya jika ingin menggunakan payment gateway di reactjs ini
bagaimana cara import
<script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="<Set your ClientKey here>"></script>
di react js component?
bagaimana menggunakan snap.pay('SNAP_TOKEN') di react js component?
Kenapa popup Snap tidak menampilkan informasi costumer detail dan shipping address? Saya lihat di halaman demo bisa menampilkan informasi tersebut https://demo.midtrans.com/
Screenshot: https://prnt.sc/ysbpzy
Backend REST API
....
const midtransSnapAPI = new midtransClient.Snap({
isProduction: false,
serverKey: "XXX",
clientKey: "XXX",
});
const snapOrderParameter = {
transaction_details: {
order_id: generateOrderID(userID),
gross_amount: planDetail.planPrice.price,
},
item_details: {
id: planID,
quantity: 1,
name: planDetail.name,
price: planDetail.planPrice.price,
},
costumer_details: {
first_name: firstName,
last_name: lastName,
email: email,
},
shipping_address: {
first_name: "TEST",
last_name: "MIDTRANSER",
email: "[email protected]",
phone: "0 8128-75 7-9338",
address: "Sudirman",
city: "Jakarta",
postal_code: "12190",
country_code: "IDN",
},
};
const snapOrderParameterToJSON = JSON.stringify(snapOrderParameter);
const midtransResult = await midtransSnapAPI.createTransaction(
snapOrderParameterToJSON
);
...
console.log(midtransResult);
{
token: '81ec1e51-39e8-xxxxxxxx',
redirect_url: 'https://app.sandbox.midtrans.com/snap/v2/vtweb/81ec1e51-xxxxx'
}
console.log(snapOrderParameterToJSON);
{
"transaction_details":{
"order_id":"10-xxxxx",
"gross_amount":125000
},
"item_details":{
"id":"2",
"quantity":1,
"name":"Standard",
"price":125000
},
"costumer_details":{
"first_name":"Mimin",
"last_name":"Sirimin",
"email":"[email protected]"
},
"shipping_address":{
"first_name":"TEST",
"last_name":"MIDTRANSER",
"email":"[email protected]",
"phone":"0 8128-75 7-9338",
"address":"Sudirman",
"city":"Jakarta",
"postal_code":"12190",
"country_code":"IDN"
}
}
NextJS/ReactJS:
const ProductCard = (props) => {
const [snapCheckoutToken, setSnapCheckoutToken] = useState("");
useEffect(() => {
if (typeof window !== "undefined") {
const myScript = document.createElement("script");
myScript.setAttribute(
"src",
"https://app.sandbox.midtrans.com/snap/snap.js"
);
myScript.setAttribute(
"data-client-key",
"SB-Mid-client-XXX"
);
document.head.appendChild(myScript);
}
}, []);
useEffect(() => {
if (snapCheckoutToken && typeof window !== "undefined") {
window.snap.pay(snapCheckoutToken, {
onSuccess: function (result) {
console.log("onsuccess", result);
},
// Optional
onPending: function (result) {
console.log("onPending", result);
},
// Optional
onError: function (result) {
console.log("oneerror", result);
},
});
}
}, [snapCheckoutToken]);
const handleOrderButton = (id) => {
axiosAuth
.post(`/payment/checkout/${id}`)
.then((result) => {
console.log(result);
setSnapCheckoutToken(result.data.data.token);
})
.catch((error) => {
console.log(error);
});
};
return (
<button
className={styles.orderButton}
onClick={() => handleOrderButton(id)}
>
Pilih Sekarang
</button>
);
};
export default ProductCard;
Terimakasih sebelumnya,
according to this documentation we can change notification url by adding header X-Override-Notification
but with this library there is no way we can do this.
selamat malam, library ini bisa untuk react-native?
Halo developers 👋
Thanks for your awesome sdk.
But currently I need a direct refund feature and I can't find any function for direct refund
like on this link.
Are you have any plan to add this feature on the sdk ?
Tanya, tolong berikan best practice,
Jika order_id = 00561/05/ADI-IL/24JKT
, dan ini adalah ketentuan tempat bekerja,
maka saat GET transaction_status seperti:
return Transaction::status('00561/05/ADI-IL/24JKT')
pasti error, dengan response:
{
"timestamp":"2024-05-17T06:24:01.223+0000",
"status":404,
"error":"Not Found",
"message":"Not Found",
"path":"/v2/00561/05/ADI-IL/24JKT/status"
}
path nya jadi tidak sesuai. Terima kasih.
Dan, jika mengguanakan Transaction::status($param)
, dimana $param
tidak bisa menggunakan order_id
, melainkan harus transaction_id
halo, saya mendapatkan response HTTP status code: 401. HTTP Basic: Access denied untuk API IRIS getBeneficiaryBanks tetapi saat menggunakan API Core maupun Snap berjalan dengan normal. Apakah ada config yang kurang?
Saya baru dalam menggunakan Midtrans, dan mencoba untuk menggunakan CoreAPI serta Custom VA. Tapi, kenapa va_number yang di return selalu berbeda ? Tidak sama dengan apa yang saya kirimkan. Di dokumentasi - Bank Transfer Object, ada peraturan terkait seberapa panjang Custom VA Number,
Sebagai contoh untuk Permata, saya buat sebuah row di database, dan menggunakan account_number sebagai VA,
let va_number = '6374912369123123123'
bank_account = await models.BankAccount.create({
account_number: va_number,
account_name: data.method,
description: 'Permata Virtual Account',
bank_id: data.bank_id,
tenant_id: tenant.id,
virtual: true,
created_by: tenant.name,
updated_by: tenant.name
})
Returnya adalah error 400, dengan message One or more parameters in the payload is invalid., [bank_transfer.va_number length must be equal to 10]
. Case nya di sini, kalau dibuat sesuai, dengan panjang va_number 10 (misalnya 8273645263), returnya malah seperti ini,
{
"status_code": "201",
"status_message": "Success, PERMATA VA transaction is successful",
"transaction_id": "19092cc6-f60e-47f8-9c01-a32763e28cfe",
"order_id": "DEP2021061578348",
"gross_amount": "100000.00",
"currency": "IDR",
"payment_type": "bank_transfer",
"transaction_time": "2021-06-15 12:53:45",
"transaction_status": "pending",
"fraud_status": "accept",
"permata_va_number": "996007792398731",
"merchant_id": "XXXXXX5"
}
Lain kalau BCA, rulenya adalah Accepts 6-11 digits
, tapi berapapun yang saya kirim, sukses, tanpa error, tapi VA Number nya ngga sesuai dengan apa yang dikirim.
Mungkin kalau BNI dan BRI beda lagi, tapi ya ini dulu lah.
Terimakasih
Overall untuk case payment menggunakan Midtrans semuanya aman, kecuali 1 case yaitu ketika user menggunakan kartu kredit, semua input-an tidak bisa di masukan data apapun oleh user
Steps to reproduce the Unexpected Behavior :
existing skenario yang terjadi skrng adalah tidak bisa input sama sekali semua field
Expected Behavior
Ketika Modal Pop Payment Midtrans muncul, maka dapat input data Kartu Kredit, CC, dll
Informasi Video ScreenRecorder
https://photos.app.goo.gl/BLCcgWyxjSCw7AT78
NextJS v10.0.5
Kami mengimplementasikan SnapMidtrans kurang lebih seperti ini
Halo. Saya ingin bertanya. Saya mengerjakan projek react.js dan ingin menggunakan library ini. Saya menginstallnya dengan menggunakan npm install midtrans-nodejs-client. Tetapi setelah itu, saat saya mencoba memanggilnya menggunakan const midtransClient = require('midtrans-client'); muncul pesan error berikut :
ERROR in ./node_modules/midtrans-client/lib/httpClient.js 9:18-40
Module not found: Error: Can't resolve 'querystring' in 'C:\Users[Username]\Documents[Project-name]\node_modules\midtrans-client\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "querystring": require.resolve("querystring-es3") }'
- install 'querystring-es3'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "querystring": false }
Saya mohon bantuannya. Terimakasih
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.