电子发票插入微信卡包之PDF上传

项目中需要将开具的电子发票插入到微信的卡包中,采用的是微信自建平台模式。

因为是自己的开的票,所以调用插卡接口前,需要上传PDF文件,代码如下:


/**
* 将电子发票PDF文件上传至微信 * @param accessToken 微信的access_token * @param file 本地的pdf文件 * @return<br> * @author xxx, 2019年9月23日.<br> */ public String uploadPdfFile(String accessToken, File file){ HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/card/invoice/platform/setpdf?access_token="+accessToken); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build(); httpPost.setConfig(requestConfig); //2.3 设置请求实体,封装了请求参数 HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("pdf", new FileBody(file, ContentType.create("multipart/form-data", Consts.UTF_8), file.getName())).build(); httpPost.setEntity(requestEntity); try { response = httpClient.execute(httpPost, new BasicHttpContext()); log.info("\n上传PDF文件至微信返回参数:{}",JSON.toJSONString(response)); if (response.getStatusLine().getStatusCode() != 200) { throw new InsertWxInvoiceCardException(2013,"上传PDF文件至微信,请求失败"); } HttpEntity entity = response.getEntity(); if (entity != null) { String resultStr = EntityUtils.toString(entity, "utf-8"); log.info("\n上传PDF文件至微信返回参数:{}",resultStr); JSONObject result = JSON.parseObject(resultStr); int errcode = (Integer)result.get("errcode"); if(errcode != 0){ throw new InsertWxInvoiceCardException(2013,"上传PDF文件至微信失败"); } return result.getString("s_media_id"); } } catch (IOException e) { e.printStackTrace(); } finally { if (response != null) try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }

返回的是上传pdf成功后的s_media_id,这个参数可以在本地存储,因为在后续的插卡接口中需要使用。

 

posted @ 2019-09-23 15:35  彩云之恋  阅读(6210)  评论(5编辑  收藏  举报