### Install Midtrans Python Client from Repository Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Install the library by navigating to the repository folder and running pip install. ```bash pip install . ``` -------------------------------- ### Initialize Core API and Handle Notifications Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Setup the Core API client and process incoming transaction notifications. ```python api_client = midtransclient.CoreApi( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) status_response = api_client.transactions.notification(mock_notification) order_id = status_response['order_id'] transaction_status = status_response['transaction_status'] fraud_status = status_response['fraud_status'] print('Transaction notification received. Order ID: {0}. Transaction status: {1}. Fraud status: {3}'.format(order_id, transaction_status, fraud_status)) # Sample transaction_status handling logic if transaction_status == 'capture': if fraud_status == 'challenge': # TODO set transaction status on your databaase to 'challenge' else if fraud_status == 'accept': # TODO set transaction status on your databaase to 'success' else if transaction_status == 'cancel' or transaction_status == 'deny' or transaction_status == 'expire': # TODO set transaction status on your databaase to 'failure' else if transaction_status == 'pending': # TODO set transaction status on your databaase to 'pending' / waiting payment ``` -------------------------------- ### Install Project Locally Source: https://github.com/midtrans/midtrans-python-client/blob/master/Maintaining.md Installs the project locally using pipenv, allowing for development and testing within a virtual environment. Ensure pipenv is installed and you are in the project directory. ```bash pipenv install ``` ```bash pipenv install --python /usr/bin/python3 ``` ```bash pipenv shell ``` ```bash pip install -e . ``` -------------------------------- ### Install Midtrans Client Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Use pip to install the official Midtrans Python library. ```bash pip install midtransclient ``` -------------------------------- ### Run Project with Docker Compose Source: https://github.com/midtrans/midtrans-python-client/blob/master/Maintaining.md Starts the project services using Docker Compose, typically for running tests within a containerized environment. Use 'docker-compose down' to stop and clean up containers. ```bash docker-compose up ``` ```bash docker-compose down ``` -------------------------------- ### Build and Upload Package to PyPI Source: https://github.com/midtrans/midtrans-python-client/blob/master/Maintaining.md Commands to build the package distribution files and upload them to the Python Package Index (PyPI) or TestPyPI. This process involves installing necessary tools like setuptools, wheel, and twine. ```bash python -m pip install --upgrade setuptools wheel ``` ```bash python setup.py sdist bdist_wheel ``` ```bash python -m pip install --upgrade twine ``` ```bash twine upload dist/* --skip-existing ``` ```bash twine upload --repository-url https://test.pypi.org/legacy/ dist/* --skip-existing ``` -------------------------------- ### GoPay Account Linking Initialization Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Initialize the Midtrans Core API client for GoPay account linking. This setup is a prerequisite for tokenization processes. ```python import midtransclient import datetime core_api = midtransclient.CoreApi( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) ``` -------------------------------- ### Get Subscription Details Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Retrieve the current details of an existing subscription using its ID. ```python details = core_api.get_subscription(subscription_id) print(f"Next execution: {details['schedule']['next_execution_at']}") ``` -------------------------------- ### Create Snap Transaction Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Prepare transaction parameters and call the create_transaction method to get a transaction token and details. The parameter dictionary must include transaction details and can optionally include credit card configurations. ```python # Create Snap API instance snap = midtransclient.Snap( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Prepare parameter param = { "transaction_details": { "order_id": "test-transaction-123", "gross_amount": 200000 }, "credit_card":{ "secure" : True } } transaction = snap.create_transaction(param) transaction_token = transaction['token'] # alternative way to create transaction_token: # transaction_token = snap.create_transaction_token(param) ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/midtrans/midtrans-python-client/blob/master/Maintaining.md Executes tests using pytest. For specific test cases, use the -k flag. Ensure pytest is installed if you encounter errors. ```bash pytest ``` ```bash pytest -k "test_core_api_charge_fail_401" ``` ```bash pip install pytest ``` -------------------------------- ### Get B2B Transaction Status Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Retrieve the status of a B2B transaction using its order ID. This is applicable for VA transactions. ```python b2b_status = api_client.transactions.statusb2b(order_id) ``` -------------------------------- ### Initialize Snap API Client Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Create an instance of the Snap class for customizable payment popups. Ensure your server and client keys are correctly set. ```python # Create Snap API instance snap = midtransclient.Snap( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) ``` -------------------------------- ### Initialize Core API Client Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Create an instance of the CoreApi class for backend integrations. Ensure your server and client keys are correctly set. ```python # Create Core API instance core_api = midtransclient.CoreApi( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) ``` -------------------------------- ### Create Subscription Payment Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Set up recurring subscription payments using credit card tokens. Requires initial payment token and scheduling details. ```python import midtransclient import datetime core_api = midtransclient.CoreApi( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Create subscription (requires saved_token_id from initial card payment) subscription_param = { "name": "PREMIUM-MONTHLY-" + datetime.datetime.now().strftime("%Y%m%d%H%M%S"), "amount": "100000", "currency": "IDR", "payment_type": "credit_card", "token": "SAVED_TOKEN_ID_FROM_INITIAL_PAYMENT", "schedule": { "interval": 1, "interval_unit": "month", # Options: day, week, month "max_interval": 12, "start_time": "2024-01-01 00:00:00 +0700" }, "metadata": { "description": "Premium subscription" }, "customer_details": { "first_name": "John", "last_name": "Doe", "email": "johndoe@email.com", "phone": "+62812345678" } } # Create subscription subscription = core_api.create_subscription(subscription_param) subscription_id = subscription['id'] print(f"Subscription ID: {subscription_id}") print(f"Status: {subscription['status']}") ``` -------------------------------- ### Instantiate Midtrans Snap API Client Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Create an instance of the Midtrans Snap API client. Set `is_production` to `False` for sandbox environment. Requires server and client keys. ```python snap = midtransclient.Snap( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) ``` -------------------------------- ### Configure Advanced Client Settings Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Shows how to initialize the Midtrans client with custom HTTP headers, override notification URLs, configure proxy settings, and re-configure client properties after initialization. ```python import midtransclient snap = midtransclient.Snap( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) snap.api_config.custom_headers = { 'x-custom-header': 'custom-value', 'x-override-notification': 'https://myapp.com/webhook', 'x-append-notification': 'https://backup.myapp.com/webhook' } snap.api_config.proxies = { 'http': 'http://proxy.company.com:8080', 'https': 'http://proxy.company.com:8080' } snap.api_config.set( is_production=True, server_key='PRODUCTION_SERVER_KEY', client_key='PRODUCTION_CLIENT_KEY' ) snap.api_config.is_production = True snap.api_config.server_key = 'NEW_SERVER_KEY' ``` -------------------------------- ### Create Snap Transaction Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Initialize the Snap client and generate payment tokens or redirect URLs for the payment popup. ```python import midtransclient # Initialize Snap API client snap = midtransclient.Snap( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Prepare transaction parameters param = { "transaction_details": { "order_id": "order-12345", "gross_amount": 200000 }, "credit_card": { "secure": True }, "customer_details": { "first_name": "John", "last_name": "Doe", "email": "johndoe@email.com", "phone": "+62812345678" } } # Create transaction transaction = snap.create_transaction(param) # Get transaction token for Snap.js popup transaction_token = transaction['token'] print(f"Token: {transaction_token}") # Get redirect URL for Snap redirect method redirect_url = transaction['redirect_url'] print(f"Redirect URL: {redirect_url}") # Alternative methods to get token or URL directly token = snap.create_transaction_token(param) url = snap.create_transaction_redirect_url(param) ``` -------------------------------- ### Initialize Snap JS for Frontend Payments Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Embeds the Snap JS library and configures the pay button to trigger the payment modal with a transaction token. ```html
JSON result will appear here after payment:
``` -------------------------------- ### Process Credit Card Charge via Core API Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Demonstrates how to charge a credit card transaction using the Core API instance. ```python # Create Core API instance core_api = midtransclient.Snap( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Prepare parameter param = { "payment_type": "credit_card", "transaction_details": { "gross_amount": 12145, "order_id": "test-transaction-54321", }, "credit_card":{ "token_id": 'CREDIT_CARD_TOKEN', # change with your card token "authentication": True } } # charge transaction charge_response = core_api.charge(param) print('charge_response:') print(charge_response) ``` -------------------------------- ### Generate Snap Redirect URL Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Initializes the Snap client and creates a transaction to obtain a redirect URL for the payment page. ```python # Create Snap API instance snap = midtransclient.Snap( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Prepare parameter param = { "transaction_details": { "order_id": "test-transaction-123", "gross_amount": 200000 }, "credit_card":{ "secure" : True } } transaction = snap.create_transaction(param) transaction_redirect_url = transaction['redirect_url'] # alternative way to create redirect_url: # transaction_redirect_url = snap.create_redirect_url(param) ``` -------------------------------- ### Create Subscription API for Credit Card Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Use this snippet to create a subscription for credit card payments. Ensure you have obtained a 1-click saved token and include necessary customer and schedule details. ```python # Create Subscription API instance core_api = midtransclient.CoreApi( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Prepare parameter param = { "name": "SUBSCRIPTION-STARTER-1", "amount": "100000", "currency": "IDR", "payment_type": "credit_card", "token": "436502qFfqfAQKScMtPRPdZDOaeg7199", "schedule": { "interval": 1, "interval_unit": "month", "max_interval": 3, "start_time": "2021-10-01 07:25:01 +0700" }, "metadata": { "description": "Recurring payment for STARTER 1" }, "customer_details": { "first_name": "John A", "last_name": "Doe A", "email": "johndoe@email.com", "phone": "+62812345678" } } create_subscription_response = core_api.create_subscription(param) subscription_id_response = create_subscription_response['id'] # get subscription by subscription_id get_subscription_response = core_api.get_subscription(subscription_id_response) # disable subscription by subscription_id disable_subscription_response = core_api.disable_subscription(subscription_id_response) # enable subscription by subscription_id enable_subscription_response = core_api.enable_subscription(subscription_id_response) # update subscription by subscription_id update_param = { "name": "SUBSCRIPTION-STARTER-1-UPDATE", "amount": "100000", "currency": "IDR", "token": "436502qFfqfAQKScMtPRPdZDOaeg7199", "schedule": { "interval": 1 } update_subscription_response = core_api.update_subscription(subscription_id_response, update_param) ``` -------------------------------- ### Re-configure Snap API Client Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md Update the configuration of an existing Snap API instance using the set method. This allows dynamic changes to production status, server key, and client key. ```python # initialize object, empty config snap = midtransclient.Snap() # re-set full config snap.api_config.set( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # re-set server_key only snap.api_config.set(server_key='YOUR_SERVER_KEY') # re-set is_production only snap.api_config.set(is_production=True) ``` -------------------------------- ### Tokenization API for Gopay Account Linking Source: https://github.com/midtrans/midtrans-python-client/blob/master/README.md This snippet demonstrates how to link a customer's Gopay account using the Tokenization API. You need to obtain a Gopay payment token first via the `get_payment_account` API call. ```python # Create Tokenization API instance core_api = midtransclient.CoreApi( is_production=False, server_key='YOUR_SERVER_KEY', client_key='YOUR_CLIENT_KEY' ) # Prepare parameter param = { "payment_type": "gopay", "gopay_partner": { "phone_number": "81234567891", "country_code": "62", "redirect_url": "https://mywebstore.com/gopay-linking-finish" #please update with your redirect URL } } # link payment account link_payment_account_response = core_api.link_payment_account(param) # get payment account get_payment_account_response = core_api.get_payment_account(active_account_id) # unlink account unlink_payment_account_response = core_api.unlink_payment_account(active_account_id) ``` -------------------------------- ### Enable Subscription Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Resume recurring charges for a disabled subscription. Requires the subscription ID. ```python core_api.enable_subscription(subscription_id) ``` -------------------------------- ### Link and Charge GoPay Account Source: https://context7.com/midtrans/midtrans-python-client/llms.txt Demonstrates linking a GoPay account, retrieving its details, and then using it to charge a transaction. Requires customer authorization for linking. ```python link_param = { "payment_type": "gopay", "gopay_partner": { "phone_number": "81234567891", "country_code": "62", "redirect_url": "https://mystore.com/gopay-callback" } } link_response = core_api.link_payment_account(link_param) account_id = link_response['account_id'] print(f"Account ID: {account_id}") print(f"Status: {link_response['account_status']}") # PENDING initially activation_url = link_response['actions'][0]['url'] print(f"Activation URL: {activation_url}") account = core_api.get_payment_account(account_id) if account['account_status'] == 'ENABLED': payment_token = account['metadata']['payment_options'][0]['token'] charge_param = { "payment_type": "gopay", "gopay": { "account_id": account_id, "payment_option_token": payment_token, "callback_url": "https://mystore.com/payment-callback" }, "transaction_details": { "gross_amount": 50000, "order_id": "GOPAY-" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") } } charge_response = core_api.charge(charge_param) print(f"Transaction: {charge_response['transaction_id']}") unlink_response = core_api.unlink_payment_account(account_id) ``` -------------------------------- ### Frontend Tokenization and 3DS Authentication Source: https://github.com/midtrans/midtrans-python-client/blob/master/examples/flask_app/templates/core_api_credit_card_frontend_sample.html JavaScript implementation for capturing card tokens and handling 3DS authentication flows. ```javascript document.querySelector("#token-form").onsubmit = function(e){ var card = { "card\_number": document.querySelector("#card-number").value, "card\_exp\_month": document.querySelector("#card-expiry-month").value, "card\_exp\_year": document.querySelector("#card-expiry-year").value, "card\_cvv": document.querySelector("#card-cvv").value, }; MidtransNew3ds.getCardToken( card, { onSuccess: function(response){ // Success to get card token\_id, implement as you wish here: document.querySelector("#token\_id\_result").value = response.token\_id; document.querySelector("#token\_id").value = response.token\_id; }, onFailure: function(response){ // Fail to get card token\_id alert(`Fail to get card token\_id: ${JSON.stringify(response)}`); console.log(`Fail to get card token\_id: ${JSON.stringify(response)}`); } } ); return e.preventDefault() && 0; // prevent form submit } document.querySelector("#authentication-form").onsubmit = function(e){ var redirect\_url = document.querySelector("#redirect\_url").value; // Utilize MidtransNew3Ds.authenticate function to perform 3DS authentication, // and handle the success/failure result MidtransNew3ds.authenticate( redirect\_url, { performAuthentication: function(redirect\_url){ // open iframe to display 3ds authentication redirect\_url to customer popupModal.openPopup(redirect\_url); }, onSuccess: function(response){ // 3ds authentication success, implement payment success scenario popupModal.closePopup(); document.querySelector("#result").innerText = JSON.stringify(response,null,2); }, onFailure: function(response){ // 3ds authentication failure, implement payment failure scenario popupModal.closePopup(); document.querySelector("#result").innerText = JSON.stringify(response,null,2); }, onPending: function(response){ // transaction is pending, transaction result will be notified later via POST notification popupModal.closePopup(); document.querySelector("#result").innerText = JSON.stringify(response,null,2) } } ); return e.preventDefault() && 0; // prevent form submit } /** * Alternatively instead of opening 3ds authentication redirect\_url using iframe, * you can also redirect customer using: ``` MidtransNew3ds.redirect(redirect\_url, { callbackUrl : 'https://mywebsite.com/finish\_3ds' }); ``` * */ /** * helper functions to open Iframe popup, you may replace this with your own method to open iframe * PicoModal library is used: *