項目中須要將開具的電子發票插入到微信的卡包中,採用的是微信自建平臺模式。api
由於是本身的開的票,因此調用插卡接口前,須要上傳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,這個參數能夠在本地存儲,由於在後續的插卡接口中須要使用。