2️Triển khai API Get Token

API này là để yêu cầu đối tác cung cấp quyền truy cập để có thể kết nối và đồng bộ với API Transaction Sync (đồng bộ biến động số dư).

2.1 POST Get Token

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

Headers

NameValue

Content-Type

application/json

Authorization

Basic Authentication: Base64[username:password]

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

Body

NameTypeRequiredDescription

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
}

2.2 - Code cài đặt

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

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.

Last updated