Braintree webhooks: Error: payload包含非法字符



我正在尝试在java微服务(Micronaut flow)中使用Braintree webhook。

我遇到的问题是,当我试图解析webhook主体时,我得到一个错误:"错误:有效负载包含非法字符"。所以我想知道如果也许我正在转换请求体插入字符的东西…?(正文为x-www-form-urlencoded)

package com.autonomy;
import com.braintreegateway.*;
import event_broker.BrokerServiceGrpc;
import event_broker.EventBroker;
import events.Events;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.micronaut.context.annotation.Value;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.Normalizer;
import java.time.Clock;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller("/webhooks")
public class WebhooksController {
private final Logger logger = LoggerFactory.getLogger("BraintreeServiceJava");
@Value("${env}") String env;
@Value("${braintree.merchant.id}") String braintreeMerchantId;
@Value("${braintree.public.key}") String braintreePublicKey;
@Value("${braintree.private.key}") String braintreePrivateKey;

@Post(consumes = MediaType.APPLICATION_FORM_URLENCODED)
public HttpResponse<?> consumeWebhook(@Body String body) {
BraintreeGateway gateway =
new BraintreeGateway(determineEnv(env),
braintreeMerchantId,
braintreePublicKey,
braintreePrivateKey
);
logger.info(body);
try {
String decodedBody = body; // was doing a decode here that didn't do anything
logger.info(decodedBody);
Map<String, String> map = new HashMap<>();
Arrays.stream(decodedBody.split("&")).toList().forEach(pair -> {
String[] param = pair.split("=");
map.put(param[0], param[1]);
});
WebhookNotification webhookNotification = gateway.webhookNotification().parse(
map.get("bt_signature"),
map.get("bt_payload")
);

..... Do stuff
} catch (Exception e) {
logger.error(String.format("Braintree webhook failed for %s. Error: %s", kind, e.getMessage()), e);
return HttpResponse.status(HttpStatus.BAD_REQUEST);
}
return HttpResponse.status(HttpStatus.OK);
}
private Environment determineEnv(String env) {
if (env.equals("beta") || env.equals("prod")) {
return Environment.PRODUCTION;
} else {
return Environment.SANDBOX;
}
}
}

尝试:

@Post(consumes = MediaType.APPLICATION_FORM_URLENCODED)
public HttpResponse<?> consumeWebhook(String bt_signature, String bt_payload)

BTW:在被记录的主体中有哪些"非法字符"?

在Java中使用Quarkus,而不是使用

@Body String body

因为参数类型是x-www-form-urlencoded,所以可以使用

@FormParam("bt_signature"字符串btSignature,@FormParam("bt_payload"字符串btPayload。

您的问题所指的内容可以通过使用换行符替换空格来解决。因为braintree库解析具有以下验证正则表达式,并且在btPayload中我遇到了空白:

private static final Pattern PAYLOAD_CHARS_PATTERN = Pattern.compile("[^A-Za-z0-9+=/n]"

解决方案:

btPayload = btPayload.replaceAll(" ", "n");
WebhookNotification webhookNotification = gateway.webhookNotification()
.parse(btSignature, btPayload);