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

Kotlin调用Zarinpal支付API时参数验证失败求助

问题排查与修复

核心问题分析

接口返回所有必填字段缺失,本质是服务器无法正确解析你发送的JSON数据,结合代码来看有以下几个问题:

  • JSON格式语法错误:metadata对象中card_pan字段末尾多了一个逗号,这会导致JSON解析失败,服务器无法读取任何参数,进而判定所有必填字段缺失。
  • 字段名错误:你用了back_uri字段,但接口要求的必填字段是description,这直接导致description字段缺失的验证错误。
  • 编码不明确:直接调用postData.toByteArray()会使用系统默认编码,可能导致JSON传输过程中出现乱码,建议明确指定UTF-8编码。

修正后的代码

import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets

fun main() {
    val url = URL("https://api.zarinpal.com/pg/v4/payment/request.json")
    val connection = url.openConnection() as HttpURLConnection
    connection.requestMethod = "POST"
    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
    connection.setRequestProperty("Accept", "application/json")
    connection.doOutput = true

    val postData: String = """{
          "amount": 1100,
          "callback_url": "https://ali568865.ir/",
          "merchant_id": "1344b5d4-0048-11e8-94db-005056a205be",
          "description": "Transaction description.",
          "metadata": {
            "mobile": "09106869409",
            "email": "info.test@gmail.com",
            "card_pan": "5022291083818920"
          }
        }
    """.trimIndent()

    connection.outputStream.use { outputStream ->
        outputStream.write(postData.toByteArray(StandardCharsets.UTF_8))
    }

    val responseCode = connection.responseCode
    if (responseCode == HttpURLConnection.HTTP_OK) {
        val response = connection.inputStream.bufferedReader().use { it.readText() }
        println(response)
    } else {
        // 错误时读取错误响应内容,方便排查
        val errorResponse = connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error details"
        println("Failed to make the request. Response code: $responseCode, Error: $errorResponse")
    }

    connection.disconnect()
}

关键修复点说明

  1. 移除metadata中card_pan字段末尾的多余逗号,确保JSON语法合法。
  2. 将back_uri替换为接口要求的description字段,满足必填项要求。
  3. 明确指定Content-Type为application/json; charset=UTF-8,并使用StandardCharsets.UTF_8将字符串转为字节数组,避免编码问题。
  4. 增加错误响应内容的读取,方便后续排查其他问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:33:19