You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java指定语言下载Stripe发票 适配Spring Boot多语言需求

解决方案

问题根因

Stripe的公开发票URL返回的文档语言由HTTP请求的Accept-Language请求头决定,你当前使用的FileUtils.copyURLToFile方法不会携带自定义语言头,默认使用HTTP客户端自带的英文头,所以无论JVM locale、Stripe客户配置、账户国家设置是什么,最终拿到的都是英文发票。

可选解决方案

方案1:下载时自定义请求头(适配现有流程)

替换FileUtils.copyURLToFile的调用,改用支持自定义请求头的HTTP客户端下载文件,示例代码如下(以JDK自带的HttpURLConnection为例,你也可以替换为RestTemplate、OkHttp等你项目中正在使用的HTTP客户端):

public void copyInvoice(Etude etude, String invoiceName, URL invoiceURL, String bucketName, Locale userLocale) {      
    var invoiceTmp = new File(System.getProperty("java.io.tmpdir") + invoiceName);
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) invoiceURL.openConnection();
        // 设置对应用户的Accept-Language头,传入标准ISO语言标签即可,比如法语传入fr、法语(法国)传入fr-FR
        connection.setRequestProperty("Accept-Language", userLocale.toLanguageTag());
        // 将响应流直接写入临时文件
        Files.copy(connection.getInputStream(), invoiceTmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
        
        var s3 = this.getCredentials();
        s3.putObject(new PutObjectRequest(bucketName, "invoices/" + invoiceName, invoiceTmp));
        invoiceTmp.delete();
    } catch (IOException e) {
        log.error("copyInvoice, IOException exception when copying invoice from Stripe", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

调用该方法时传入对应用户设置的Locale,即可拿到对应语言的发票。

方案2:创建发票时指定首选语言(更稳妥,无需每次下载修改请求头)

如果用户的语言偏好是固定的,可以在创建Stripe客户或者发票时直接设置preferred_locales参数,设置完成后该发票的默认返回语言就是你指定的语言,不需要额外修改下载请求,Stripe官方Java SDK示例如下:

// 创建客户时设置首选语言为法语
CustomerCreateParams customerParams = CustomerCreateParams.builder()
  .setEmail("user@example.com")
  .addPreferredLocale("fr")
  .build();
Customer customer = Customer.create(customerParams);

// 也可以在创建单张发票时单独指定语言优先级
InvoiceCreateParams invoiceParams = InvoiceCreateParams.builder()
  .setCustomer(customer.getId())
  .addPreferredLocale("fr")
  // 其他发票参数配置
  .build();
Invoice invoice = Invoice.create(invoiceParams);

内容的提问来源于stack exchange,提问作者Ajrarn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 06:21:03