Flutter API,得不到我想要的结果。但是当我将令牌和签名等打印结果复制到 Postman 时,它就起作用了

问题描述 投票:0回答:0

我创建了一个代码,它使用 post 值从主机获取数据到我的测试文件,生成主机想要的所有 API。在满足所有要求后,前 1-2 天它可以正常工作。但在下次测试后它说

invalid parameter request
。尝试检查并打印我从请求中获得的所有语法和数据,并将数据放入邮递员中,它工作正常。这是我为使用 API 请求而创建的代码

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:crypto/crypto.dart';
import 'package:intl/intl.dart';

String generateSignature(String path, String verb, String token,
    String timestamp, String body, String secret) {
  String message =
      'path=$path&verb=$verb&token=$token&timestamp=$timestamp&body=$body';
  var key = utf8.encode(secret);
  var bytes = utf8.encode(message);
  var hmacSha256 = Hmac(sha256, key);
  var digest = hmacSha256.convert(bytes);
  String signature = base64.encode(digest.bytes);
  return signature;
}

Future<void> main() async {
  const String consumerKey = 'jQnNwRUUMlvxznfcYIB0uVJzzyeVY4jv';
  const String consumerSecret = 'wc8bVAjytYLnVJPZ';
  const String tokenUrl =
      'https://sandbox.partner.api.bri.co.id/oauth/client_credential/accesstoken?grant_type=client_credentials';
  const String baseUrl = 'https://sandbox.partner.api.bri.co.id/v1/briva';
  String path = '/v1/briva';
  String verb = 'POST';

  final resp = await http.post(
    Uri.parse(tokenUrl),
    headers: {
      'Authorization':
          'Basic ${base64.encode(utf8.encode('$consumerKey:$consumerSecret'))}',
    },
  );

  if (resp.statusCode == 200) {
    final body = json.decode(resp.body);
    final accessToken = body['access_token'];

    DateTime localTime = DateTime.now();
    DateTime utcTime = localTime.toUtc();
    String time = localTime.toIso8601String();
    String timestamp =
        DateFormat('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'').format(utcTime);

    String timeplus1day = DateFormat('yyyy-MM-dd HH:mm:ss')
        .format(utcTime.add(const Duration(days: 1)));

    final data = jsonEncode({
      "institutionCode": "J104408",
      "brivaNo": "77777",
      "custCode": "1255",
      "nama": "John Doe",
      "amount": "20000",
      "keterangan": "",
      "expiredDate": timeplus1day
    });

    String tokens = 'Bearer $accessToken';

    String signature =
        generateSignature(path, verb, tokens, timestamp, data, consumerSecret);

    final response = await http.post(
      Uri.parse(baseUrl),
      headers: {
        'content-type': 'application/json',
        'BRI-Timestamp': timestamp,
        'BRI-Signature': signature,
        'Authorization': 'Bearer $accessToken',
      },
      body: data,
    );

    print('Generated signature: $signature');
    print('Generated token: $tokens');
    print('Generated timestamp: $timestamp');

    print('URL: $baseUrl');
    print('Request body: $data');
    print('Response: ${response.statusCode} - ${response.body}');
  } else {
    throw Exception('Failed to obtain access token: ${resp.statusCode}');
  }
}

这是我从中得到的打印结果

Generated signature: Sm6kTu6hdS0T3LP+1NshIujv6rXKw1JXwzhikwRCT8E=
Generated token: Bearer CfUClN8TTyGqBeQ2D5POQN6fTxn1
Generated timestamp: 2023-04-02T07:48:03.678Z
URL: https://sandbox.partner.api.bri.co.id/v1/briva
Request body: {"institutionCode":"J104408","brivaNo":"77777","custCode":"1255","nama":"John Doe","amount":"20000","keterangan":"","expiredDate":"2023-04-03 07:48:03"}
Response: 400 - 
                {
                    "status": {
                        "code": "0109",
                        "desc": "Invalid request parameter"
                    }
                }

它说无效的请求参数,但是当我把它放到邮递员API中时,它工作得很好。

我还整合了我被告知要尝试的步骤。 这是我尝试将标题更改为全部小写的时候。并且仍然得到邮递员 API 的回复。

flutter api dart post
© www.soinside.com 2019 - 2024. All rights reserved.