收藏
回答

第三方平台上传小程序备案媒体材料?

这里是什么才行,实在没搞懂

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

5 个回答

  • 鹏哥
    鹏哥
    2023-10-09

    最近我在开发小程序备案这块功能涉及到上传备案材料,我可以将自己的实现分享出来 。使用的是响应式编程。

    先看接口层:


    @RequestMapping(value = {"/security_superadmin/mini/icp/media/upload"}, method = RequestMethod.POST)
    public Mono image_upload(@RequestPart("file") Mono filePartMono,
                                         @RequestParam(value="component_appid",required = true) String component_appid,
                                         @RequestParam(value="authorizer_appid",required = true) String authorizer_appid,
                                         @RequestHeader(value="admintoken", required = true) String token,
                                         @RequestHeader("Content-Length") long contentLength,
                                         @RequestParam(value="type",required = true) String type,
                                         @RequestParam(value="certificate_type",required = true) String certificate_type,
                                         @RequestParam(value="icp_order_field",required = true) String icp_order_field
                                         ) throws Throwable
       {
    
             return wechatPlatformService.uploadMediaFile( filePartMono, component_appid, authorizer_appid, type, certificate_type, icp_order_field).map(res -> res);
    
       }
    


    再看服务层:

     public  Mono  uploadMediaFile(Mono filePartMono , String component_appid, String authorizer_appid, String type, String certificate_type, String icp_order_field)
            throws Throwable {
    
         return filePartMono.doOnNext(fp -> log.info("Receiving File:{}" ,fp.filename())).flatMap(filePart -> {
    
             PlatformGrant grant = null;
             try {
                 grant = super.getApiToken(component_appid, authorizer_appid);
    
             } catch (Exception e) {
    
                 return Mono.just(Response.error(e));
             }
             String url = "https://api.weixin.qq.com/wxa/icp/upload_icp_media?access_token=" + grant.getAuthorizer_access_token();
             log.info("---> url {}", url);
             log.info("---->go here <----");
    
             File temFile = new File("/tmp");
             if (!temFile.exists()) {
                 temFile.mkdirs();
             }
             File upFile = new File(temFile + "/" + UUID.randomUUID() + ".jpg");
             if (!upFile.exists()) {
                 try {
                     upFile.createNewFile();
                 } catch (Exception e) {
                     return Mono.just(Response.error("上传文件异常:" + e.getMessage()));
                 }
    
             }
             filePart.transferTo(upFile);
    
             byte[] bytes = null;
             try {
                 bytes = Files.readAllBytes(upFile.toPath());
             } catch (Exception e) {
                 return Mono.just(Response.error("上传文件异常:" + e.getMessage()));
             }
    
             HttpHeaders headers = new HttpHeaders();
             headers.setContentType(MediaType.MULTIPART_FORM_DATA);
             HttpHeaders pictureHeader = new HttpHeaders();
             pictureHeader.setContentDispositionFormData("file",upFile.getName());
             pictureHeader.setContentType(MediaType.IMAGE_PNG);
             ByteArrayResource bar = new ByteArrayResource(bytes);
             HttpEntity picturePart = new HttpEntity<>(bar, pictureHeader);
             MultiValueMap multipartRequest = new LinkedMultiValueMap<>();
             multipartRequest.add("media", picturePart);
             multipartRequest.add("type", type);
             multipartRequest.add("certificate_type", certificate_type);
             multipartRequest.add("icp_order_field", icp_order_field);
             HttpEntity entity = new HttpEntity(multipartRequest, headers);
             JSONObject json =  restTemplate.postForObject(url, entity, JSONObject.class);
    
             log.info("--->上传备案媒体素材结果{}", json.toJSONString());
             if (upFile.exists()){
    
                 upFile.delete();
                 log.info("---->删除文件<----");
             }
             Integer errocode = json.getInteger("errcode");
             if (0 == errocode.intValue()) {
    
                 MiniMediaRecord record = new MiniMediaRecord();
                 record.setMedia_id(json.getString("media_id"));
                 record.setType(type);
                 record.setAuthorizer_appid(authorizer_appid);
                 record.setComponent_appid(component_appid);
                 record.setAuthorizer_appname(grant.getMuch_mini_name() != null ? grant.getMuch_mini_name() : "");
                 record.setCert_type(certificate_type);
                 record.setSubmit_time(new Date());
                 record.setIcp_order_field(icp_order_field);
                 miniMediaRecordRepository.save(record);
             }
    
             return Mono.just(Response.success("success"));
    
         }).then(Mono.just(Response.success("success")));
    
    
    }
    



    需要注意的是: 微信官方的这个接口不能以JSON格式提交参数,使用 restTemplate 需要

    构造出一个 HttpEntity<ByteArrayResource> 对象。

    HttpEntity picturePart = new HttpEntity<>(bar, pictureHeader);
    



    UI 界面:


    响应结果:



    希望有帮助。 欢迎加我微信:comeon_betty 来交流学习。


    2023-10-09
    有用 1
    回复 1
    • yuik-🍊
      yuik-🍊
      2023-10-09
      传递的图片这个参数是怎么传的,原链接还是二进制图片?
      2023-10-09
      回复
  • 苦行僧V
    苦行僧V
    2023-10-11

    这个参数该怎么传啊?例如我上传的是营业执照,certificate_type和icp_order_field对应传啥?没有看到微信有文档解释呢

    2023-10-11
    有用
    回复 2
    • Tim.
      Tim.
      2023-10-12
      certificate_type: 1, icp_order_field: icp_subject.organize_info.certificate_photo
      2023-10-12
      1
      回复
    • 苦行僧V
      苦行僧V
      2023-10-12
      这个有什么文档解释么或者命名规律么?再例如我上传手持证件照,certificate_type和icp_order_field对应传啥呢?在线等,急急!求大神指教!
      2023-10-12
      回复
  • 💩懒大王
    💩懒大王
    2023-09-11

    我也不行,你解决了吗?

    2023-09-11
    有用
    回复 13
    • Tim.
      Tim.
      2023-09-16
      没有解决
      2023-09-16
      回复
    • 💩懒大王
      💩懒大王
      2023-09-16回复Tim.
      我是这么整的 你要是java的话可以借鉴一下
      public JSONObject uploadIcpMedia(UploadIcpMediaReq req) {
          try {
            String componentAppId =
                    weChatOpenAuthorizationInfoService.selectByBuinessId(req.getBusinessId())
                            .getWeixinOpenAuthorizationInfoDto().getComponentAppid();
            String authorizerAccessToken = wechatServiceSupport.getAuthorizerAccessToken(componentAppId,
                    req.getBusinessId());
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/icp/upload_icp_media?access_token="+ authorizerAccessToken);
            HttpGet httpGet = new HttpGet(req.getImgUrl());
              // 设置表单数据
              MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
              entityBuilder.addTextBody("type", req.getType());
              entityBuilder.addTextBody("certificate_type", req.getCertificateType());
              entityBuilder.addTextBody("icp_order_field", req.getIcpOrderField()==1?"icp_subject.principal_info.certificate_photo_front":"icp_subject.principal_info.certificate_photo_back");


              // 添加文件参数
              HttpResponse getImageResponse = httpClient.execute(httpGet);
              HttpEntity imageEntity = getImageResponse.getEntity();
              InputStream imageStream = imageEntity.getContent();
              File file= inputStreamToFile(imageStream, "image.jpg");
              entityBuilder.addBinaryBody("media", file, ContentType.create("image/jpeg"), file.getName());
              HttpEntity multipartEntity = entityBuilder.build();
              httpPost.setEntity(multipartEntity);


              // 执行请求
              HttpResponse response = httpClient.execute(httpPost);


              // 读取响应内容
              String responseBody = EntityUtils.toString(response.getEntity());


              // 打印响应内容
              log.info("uploadIcpMedia resp {}",responseBody);
              JSONObject resultJSON = JSONObject.parseObject(responseBody);
              if (resultJSON.getInteger("errcode")==0) {
                DcWechatIcpUploadMedia dcWechatIcpUploadMedia=new DcWechatIcpUploadMedia();
                dcWechatIcpUploadMedia.setMediaId(resultJSON.getString("media_id"));
                dcWechatIcpUploadMedia.setBusinessId(req.getBusinessId());
                dcWechatIcpUploadMedia.setMediaType(req.getType());
                dcWechatIcpUploadMedia.setIcpOrderField(req.getIcpOrderField());
                dcWechatIcpUploadMediaMapper.insertSelective(dcWechatIcpUploadMedia);
                return resultJSON;
              }
              return resultJSON;
            } catch (Exception e) {
              e.printStackTrace();
              return null;
            }
      2023-09-16
      1
      回复
    • Tim.
      Tim.
      2023-09-18回复💩懒大王
      上传营业执照一直提示无法读取图片识别内容,这个你知道怎么回事吗
      2023-09-18
      回复
    • 💩懒大王
      💩懒大王
      2023-09-18回复Tim.
      这就不知道了,我们现在主要做个人小程序的备案
      2023-09-18
      回复
    • 李大虾
      李大虾
      2023-09-20回复💩懒大王
      你好我按这个写法配好了但是请求报了errcode:40004,;errmsg:invalid media type,请问你有遇到吗?
      2023-09-20
      回复
    查看更多(8)
  • 拾光盒子
    拾光盒子
    2023-09-11

    content-type不能是json,要是multipart/form-data

    2023-09-11
    有用
    回复
  • 跨商通
    跨商通
    2023-09-11

    待上传的图片或视频的二进制内容

    2023-09-11
    有用
    回复
登录 后发表内容