VIETQR API
한국어 (Korea)
한국어 (Korea)
  • 🇻🇳VIETQR XIN CHÀO!
    • Tổng quan
      • Giới thiệu chung
      • Mô tả luồng nghiệp API
      • Khai báo merchant connection
      • Giá trị của mã QR
    • 📖API VIETQR CALLBACK
      • 1️⃣API Get Token
      • 2️⃣API Transaction Sync
      • 3️⃣Gọi API Get Token
      • 4️⃣Gọi API Generate VietQR Code
      • 5️⃣Gọi API Test Callback
      • Đồng bộ thông tin
        • ➕Đồng bộ tổng đại lý
        • ➕Kiểm tra danh sách đại lý
        • ➕Đồng bộ điểm bán
        • ➕Kiểm tra danh sách điểm bán
      • MASTER MERCHANT
      • Retry giao dịch
    • API Nâng cao
      • VietQR Refund APIs
        • 1️Gọi API Check Transaction
        • 2️Gọi API Refund
        • 3️Chú ý đối với refund
      • 🛜API Host to Device (MQTTs)
        • 1️Liên kết với VietQR
        • 2️Thiết lập và kết nối
        • 3️MQTT Nhận Biến Động Số Dư
        • 4️MQTT Tạo Mã Thanh Toán VietQR
        • 5️MQTT Nhận Mã Thanh Toán VietQR
        • 6️MQTT Giả Lập Thanh Toán
        • 7️Nghiệm thu và yêu cầu GoLive
        • ➕MQTT Tra Cứu Thông Tin Giao Dịch
        • ➕MQTT Phản Hồi Tra Cứu Thông Tin
        • Các bước đồng bộ MQTT
      • ⚙️Host To Client
        • 1️Gọi API Get Token
        • 2️API Ecommerce Sync
        • 3️WS: Sync Bank Account
        • 4️WS: Transaction Sync
        • 5️Đồng bộ tài khoản ngân hàng
        • 6️Gọi API Generate VietQR Code
        • ➕API Check Transaction
    • WordPress Plugin
      • 1️Cài đặt Plugin VietQR
      • 2️Liên kết với VietQR
      • 3️Đồng bộ tài khoản ngân hàng
      • 4️Tạo mã QR và nhận biến động số dư
      • ➕[FAQs] Câu hỏi thường gặp
    • Golive dịch vụ
      • *️Nghiệm thu và yêu cầu GoLive
    • API CHO SẢN PHẨM IOT
      • Api Tbị Gọi quầy
      • API cho thiết bị PAYBox
      • API cho thiết bị SoundBox
    • ⁉️Bảng mã lỗi
    • 🏦Danh sách mã ngân hàng
    • ℹ️Thông tin bổ sung
    • 🤖Robot tài chính RPA
      • Quy trình mẫu cho Doanh nghiệp
      • Quy trình mẫu đối với Ngân hàng
    • 🎧Hỗ trợ và liên hệ
    • 1️Mở TK VietQR và liên kết
Powered by GitBook
On this page
  • 2.1 POST Get Token
  • 2.2 - Code cài đặt
  • 2.3 - Các câu hỏi thường gặp chủ đề API Get Token
  1. VIETQR XIN CHÀO!
  2. API VIETQR CALLBACK

API Get Token

API này cho phép đối tác cấp quyền truy cập để VietQR có thể kết nối và đồng bộ dữ liệu với API Transaction Sync (đồng bộ biến động số dư). Để cấp quyền, đối tác cần cấu hình và tạo điểm nhận dữ liệu

2.1 POST Get Token

https://<your-host>/<your-basepath>/api/token_generate

Headers

Name
Value

Content-Type

application/json

Authorization

Basic Authentication: Base64[username:password]

username và password của API này sẽ do bạn định nghĩa và cung cấp cho VietQR.

Body

Name
Type
Required
Description

access_token

String

Yes

Là Bearer Token do đối tác cung cấp.

token_type

String

Yes

Là dạng token dạng “Bearer”.

expires_in

String

Yes

Thời gian hết hạn của token.

Response

{
    "access_token": "bearer_token",
    "token_type": "Bearer",
    "expires_in": 300
}
{
    "status": "FAILED",
    "message": "mã_lỗi"
}

2.2 - Code cài đặt

Test với Posmant :

namespace YourNamespace.Controllers
{
    [Route("vqr/api")]
    [ApiController]
    public class TokenController : ControllerBase
    {
        private const string VALID_USERNAME = "customer-vietqrtest-user2468";
        private const string VALID_PASSWORD = "Y3VzdG9tZXItdmlldHFydGVzdC11c2VyMjQ2ODpZM1Z6ZEc5dFpYSXRkbWxsZEhGeWRHVnpkQzExYzJWeU1qUTJPQT09"; // Base64 của username:password
        private const string SECRET_KEY = "your-256-bit-secret"; // Bí mật để ký JWT token

        [HttpPost("token_generate")]
        public IActionResult GenerateToken([FromHeader] string Authorization)
        {
            // Kiểm tra Authorization header
            if (string.IsNullOrEmpty(Authorization) || !Authorization.StartsWith("Basic "))
            {
                return BadRequest("Authorization header is missing or invalid");
            }

            // Giải mã Base64
            var base64Credentials = Authorization.Substring("Basic ".Length).Trim();
            var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(base64Credentials));
            var values = credentials.Split(':', 2);

            if (values.Length != 2)
            {
                return BadRequest("Invalid Authorization header format");
            }

            var username = values[0];
            var password = values[1];

            // Kiểm tra username và password
            if (username == VALID_USERNAME && password == VALID_PASSWORD)
            {
                var token = GenerateJwtToken(username);
                return Ok(new
                {
                    access_token = token,
                    token_type = "Bearer",
                    expires_in = 300 // Thời gian hết hạn token
                });
            }
            else
            {
                return Unauthorized("Invalid credentials");
            }
        }

        // Hàm tạo JWT token
        private string GenerateJwtToken(string username)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(SECRET_KEY);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, username)
                }),
                Expires = DateTime.UtcNow.AddMinutes(5), // Token hết hạn sau 5 phút
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}

// Đây là Sample Code mang tính chất tham khảo
@RestController
@RequestMapping("/vqr/api")
public class TokenController {

    private static final String VALID_USERNAME = "customer-vietqrtest-user2468";
    private static final String VALID_PASSWORD = "Y3VzdG9tZXItdmlldHFydGVzdC11c2VyMjQ2ODpZM1Z6ZEc5dFpYSXRkbWxsZEhGeWRHVnpkQzExYzJWeU1qUTJPQT09"; // Đây là chuỗi base64 từ username:password thật của bạn.

    // API để tạo token
    @PostMapping("/token_generate")
    public ResponseEntity<?> generateToken(@RequestHeader("Authorization") String authHeader) {
        // Kiểm tra xem header có Authorization không
        if (authHeader != null && authHeader.startsWith("Basic ")) {
            // Giải mã Base64 từ Authorization header
            String base64Credentials = authHeader.substring("Basic ".length()).trim();
            String credentials = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8);

            // Phân tách username và password
            final String[] values = credentials.split(":", 2);
            String username = values[0];
            String password = values[1];

            // Kiểm tra tính hợp lệ của username và password
            if (VALID_USERNAME.equals(username) && VALID_PASSWORD.equals(password)) {
                // Nếu hợp lệ, tạo JWT token
                String token = "your-generated-jwt-token"; // Ở đây bạn cần tạo JWT token thực sự, ví dụ với jjwt.

                return ResponseEntity.ok(new TokenResponse(token, "Bearer", 300));
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
            }
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Authorization header is missing or invalid");
        }
    }

    // Class cho response
    public static class TokenResponse {
        private String access_token;
        private String token_type;
        private int expires_in;

        public TokenResponse(String access_token, String token_type, int expires_in) {
            this.access_token = access_token;
            this.token_type = token_type;
            this.expires_in = expires_in;
        }

        // Getters và Setters
        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public String getToken_type() {
            return token_type;
        }

        public void setToken_type(String token_type) {
            this.token_type = token_type;
        }

        public int getExpires_in() {
            return expires_in;
        }

        public void setExpires_in(int expires_in) {
            this.expires_in = expires_in;
        }
    }
}

// Đây là Sample Code mang tính chất tham khảo
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

// Khởi tạo ứng dụng Express
const app = express();
app.use(bodyParser.json());

const VALID_USERNAME = 'customer-vietqrtest-user2468';
const VALID_PASSWORD = 'Y3VzdG9tZXItdmlldHFydGVzdC11c2VyMjQ2ODpZM1Z6ZEc5dFpYSXRkbWxsZEhGeWRHVnpkQzExYzJWeU1qUTJPQT09'; // Base64 của username:password
const SECRET_KEY = 'your-256-bit-secret'; // Secret key để ký JWT

// API để tạo token
app.post('/vqr/api/token_generate', (req, res) => {
    // Kiểm tra Authorization header
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Basic ')) {
        return res.status(400).json({ error: 'Authorization header is missing or invalid' });
    }

    // Giải mã Base64 từ Authorization header
    const base64Credentials = authHeader.split(' ')[1];
    const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
    const [username, password] = credentials.split(':');

    // Kiểm tra username và password
    if (username === VALID_USERNAME && password === VALID_PASSWORD) {
        // Tạo JWT token
        const token = jwt.sign(
            { username }, 
            SECRET_KEY, 
            { algorithm: 'HS512', expiresIn: '5m' } // Token hết hạn sau 5 phút
        );

        // Trả về token
        res.json({
            access_token: token,
            token_type: 'Bearer',
            expires_in: 300 // 300 giây = 5 phút
        });
    } else {
        res.status(401).json({ error: 'Invalid credentials' });
    }
});

// Chạy server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

// Đây là Sample Code mang tính chất tham khảo
<?php
require __DIR__ . '/vendor/autoload.php'; // Autoload từ Composer
use \Firebase\JWT\JWT;

class TokenAPI {
    private $validUsername = 'customer-vietqrtest-user2468';
    private $validPassword = 'Y3VzdG9tZXItdmlldHFydGVzdC11c2VyMjQ2ODpZM1Z6ZEc5dFpYSXRkbWxsZEhGeWRHVnpkQzExYzJWeU1qUTJPQT09'; // Base64 của username:password
    private $secretKey = 'your-256-bit-secret'; // Secret key để ký JWT

    public function generateToken() {
        // Kiểm tra Authorization header
        if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
            http_response_code(400);
            echo json_encode(["error" => "Authorization header is missing or invalid"]);
            return;
        }

        $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
        if (strpos($authHeader, 'Basic ') !== 0) {
            http_response_code(400);
            echo json_encode(["error" => "Invalid Authorization header"]);
            return;
        }

        // Giải mã Base64 từ Authorization header
        $base64Credentials = substr($authHeader, 6);
        $credentials = base64_decode($base64Credentials);
        list($username, $password) = explode(':', $credentials);

        // Kiểm tra username và password
        if ($username === $this->validUsername && $password === $this->validPassword) {
            $token = $this->createJwtToken($username);
            echo json_encode([
                "access_token" => $token,
                "token_type" => "Bearer",
                "expires_in" => 300
            ]);
        } else {
            http_response_code(401);
            echo json_encode(["error" => "Invalid credentials"]);
        }
    }

    // Hàm tạo JWT token
    private function createJwtToken($username) {
        $issuedAt = time();
        $expirationTime = $issuedAt + 300;  // Token hết hạn sau 300 giây
        $payload = [
            'iss' => 'https://yourdomain.com', // Issuer của token
            'iat' => $issuedAt,
            'exp' => $expirationTime,
            'username' => $username
        ];

        return JWT::encode($payload, $this->secretKey, 'HS512');
    }
}

// Khởi tạo đối tượng và gọi hàm generateToken
$api = new TokenAPI();
$api->generateToken();


// Đây là Sample Code mang tính chất tham khảo
from flask import Flask, request, jsonify
import jwt
import time
import base64

app = Flask(__name__)

# Cấu hình username, password hợp lệ và secret key
VALID_USERNAME = 'customer-vietqrtest-user2468'
VALID_PASSWORD = 'Y3VzdG9tZXItdmlldHFydGVzdC11c2VyMjQ2ODpZM1Z6ZEc5dFpYSXRkbWxsZEhGeWRHVnpkQzExYzJWeU1qUTJPQT09' # Base64 của username:password
SECRET_KEY = 'your-256-bit-secret'  # Secret key để ký JWT

# API để tạo token
@app.route('/vqr/api/token_generate', methods=['POST'])
def generate_token():
    # Kiểm tra Authorization header
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Basic '):
        return jsonify({"error": "Authorization header is missing or invalid"}), 400

    # Giải mã Base64 từ Authorization header
    base64_credentials = auth_header.split(' ')[1]
    credentials = base64.b64decode(base64_credentials).decode('utf-8')
    username, password = credentials.split(':')

    # Kiểm tra username và password
    if username == VALID_USERNAME and password == VALID_PASSWORD:
        # Tạo JWT token
        issued_at = int(time.time())
        expiration_time = issued_at + 300  # Token hết hạn sau 300 giây (5 phút)
        payload = {
            'username': username,
            'iat': issued_at,
            'exp': expiration_time
        }

        token = jwt.encode(payload, SECRET_KEY, algorithm='HS512')

        # Trả về token
        return jsonify({
            "access_token": token,
            "token_type": "Bearer",
            "expires_in": 300
        })
    else:
        return jsonify({"error": "Invalid credentials"}), 401

if __name__ == '__main__':
    app.run(port=5000)

// Đây là Sample Code mang tính chất tham khảo

2.3 - Các câu hỏi thường gặp chủ đề API Get Token

Làm thế nào để cấp quyền truy cập cho VietQR vào API của chúng tôi?

Bạn cần tạo một username và password dành riêng cho VietQR để họ có thể truy cập vào API Transaction Sync của bạn. Sau đó, bạn chia sẻ thông tin này với đội ngũ VietQR để họ có thể thực hiện đồng bộ dữ liệu.

Thông tin đăng nhập VietQR sử dụng có bảo mật không?

VietQR cam kết tuân thủ các quy trình bảo mật nghiêm ngặt. Thông tin đăng nhập mà bạn cung cấp sẽ được mã hóa và chỉ sử dụng cho mục đích đồng bộ dữ liệu theo thỏa thuận giữa hai bên.

Có giới hạn nào về tần suất truy cập mà VietQR có thể thực hiện vào API của tôi?

Nếu có bất kỳ giới hạn nào về tần suất truy cập hoặc tài nguyên, bạn nên thông báo trước với đội ngũ VietQR để họ có thể điều chỉnh tần suất truy cập phù hợp và tránh quá tải hệ thống.

Tôi có thể giới hạn quyền truy cập của VietQR vào một phần nhất định của API không?

Có, bạn có thể cấu hình quyền truy cập để VietQR chỉ có thể truy cập vào các endpoint cần thiết cho việc đồng bộ dữ liệu. Điều này giúp đảm bảo an toàn và bảo mật cho hệ thống của bạn.

PreviousAPI VIETQR CALLBACKNextAPI Transaction Sync

curl --location --request POST '' \ --header 'Authorization: Basic dGFpcGhpbTRrOjYxZTU1ZmU0LTBhNjMtNGU4Zi1hZDgyLTBlNjFiYzk4M\mRlNA=='

🇻🇳
📖
1️⃣
https://uat8.thuythu.vn/mrtao/wp-json/tt-vietqr/api/token_generate