Azure Communication Service调用WhatsApp模板触发BadRequest错误求助
问题根源分析
从报错日志和代码来看,核心问题出在WhatsApp模板按钮的类型指定与绑定逻辑错误,具体包含两点:
- 按钮SubType枚举值错误:代码中用字符串"otpcode"作为按钮类型,但Azure ACS要求使用
WhatsAppMessageButtonSubType枚举值,直接导致类型转换失败(触发ModelValidationError)。 - OTP按钮绑定逻辑错误:WhatsApp的验证码(OTP)按钮有专属参数规则,错误地将其当作普通按钮传值,触发了"Url类型按钮缺失必填参数"的错误(实际是OTP按钮的绑定方式不符合要求)。
解决步骤与修正代码
1. 正确指定OTP按钮的SubType
将按钮类型改为枚举WhatsAppMessageButtonSubType.OneTimePassword,这是ACS对应WhatsApp OTP按钮的官方枚举值。
2. 修正OTP按钮的绑定逻辑
WhatsApp的OTP模板按钮不需要手动传递验证码值到按钮绑定中,只需确保模板变量与按钮的参数关联正确。对于ACS的WhatsAppMessageTemplateBindingsButton,OTP类型按钮的第二个参数应为模板中定义的OTP变量名(而非具体验证码值)。
修正后的完整代码
var channelRegistrationId = new Guid(options.Value.ChannelRegistrationId); var recipientList = new List<string> { phoneNumber }; var otpVariableName = "otpcode"; // 与WhatsApp模板中的变量名保持完全一致 var value1 = new MessageTemplateText(otpVariableName, otpCode); var bindings = new WhatsAppMessageTemplateBindings(); bindings.Body.Add(new(value1.Name)); // 修正:使用OneTimePassword枚举,参数为模板变量名而非具体验证码 bindings.Buttons.Add(new WhatsAppMessageTemplateBindingsButton(WhatsAppMessageButtonSubType.OneTimePassword, otpVariableName)); var template = new MessageTemplate(options.Value.PhoneNumberValidationTemplateName, "en_us"); template.Values.Add(value1); template.Bindings = bindings; var content = new TemplateNotificationContent(channelRegistrationId, recipientList, template); Response<SendMessageResult> response = await notificationMessagesClient.SendAsync(content);
额外验证点
- 确认WhatsApp模板中配置的是**"One-Time Password"按钮类型**,而非URL按钮,否则会触发类型不匹配错误。
- 模板中的变量名(如
otpcode)需与代码中MessageTemplateText的Name完全一致,包括大小写。 - 检查
ChannelRegistrationId和模板名称PhoneNumberValidationTemplateName的配置,确保无拼写或格式错误。
内容的提问来源于stack exchange,提问作者Arshad Badar Khan
相关产品推荐
相关产品推荐

