收藏
回答

申请二级商户资金账单API,下载文件获取到乱码,怎么办?

key已经从encrypt_key解密出,nonce也有,只有ciphertext 是乱码,导致解出明文报错,微信的接口调用返回状态都是200,不知道错在哪

回答关注问题邀请回答
收藏

2 个回答

  • 蓝桥
    蓝桥
    2022-02-15
      //以下方法注意 byte[] bytes = EntityUtils.toByteArray(response.getEntity());
    
    public static byte[] downloadUrl(String download_url) throws Exception {
    
    
        //请求URL
        //账单文件的下载地址的有效时间为30s
        URIBuilder uriBuilder = new URIBuilder(download_url);
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");
    
        //执行请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                //重点在此处返回byte[]数组
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return bytes;
            } else if (statusCode == 204) {
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }
        return null;
    }
    
    /**
         * 解密二级商户账单
         * @param associatedData
         * @param nonce
         * @param ciphertext 二进制密文,需以字节数组形式处理,不需要进行Base64解码。
         * @return
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public String decryptToString(byte[] associatedData, byte[] nonce, byte[] ciphertext)
                throws GeneralSecurityException, IOException {
            try {
                Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    
                SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
                GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
    
                cipher.init(Cipher.DECRYPT_MODE, key, spec);
                cipher.updateAAD(associatedData);
    
                return new String(cipher.doFinal(ciphertext), "utf-8");
            } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
                throw new IllegalStateException(e);
            } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
                throw new IllegalArgumentException(e);
            }
        }
    
    }
    
    
    2022-02-15
    有用
    回复
  • 来一间
    来一间
    2021-05-27

    官方给出下载API账单的详细说明,有空可以看下https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_8.shtml

    2021-05-27
    有用
    回复
登录 后发表内容