Git Product home page Git Product logo

fudiwei / dotnetcore.skit.flurlhttpclient.wechat Goto Github PK

View Code? Open in Web Editor NEW
1.4K 22.0 277.0 16.07 MB

可能是全网最完整的 C# 版微信 SDK,封装全部已知的微信 API,包含微信公众平台(订阅号+服务号+小程序+小游戏+小商店+视频号)、微信开放平台、微信商户平台(微信支付+微企付)、企业微信、微信广告平台、微信智能对话开放平台等模块,可跨平台。持续随官方更新,欢迎 Star/Fork/PR。QQ 交流群 875580418【满】、930461548。

Home Page: https://github.com/fudiwei/DotNetCore.SKIT.FlurlHttpClient

License: MIT License

C# 100.00%
wechat wechat-sdk weixin weixin-sdk tenpay wxpay wxpay-sdk wxwork wechat-work wechat-pay

dotnetcore.skit.flurlhttpclient.wechat's Issues

[BUG] 请一句话描述此缺陷

⚠⚠ 请注意:不符合格式要求的 Issue 可能会被直接关闭。


关于问题的简单描述
失败System.IO.FileLoadException: Could not load file or assembly 'System.Text.Json, Version=6.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
文件名:“System.Text.Json, Version=6.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51”
在 SKIT.FlurlHttpClient.FlurlSystemTextJsonSerializer..ctor()
在 SKIT.FlurlHttpClient.CommonClientBase.<.ctor>b__8_0(ClientFlurlHttpSettings flurlSettings)
在 Flurl.Http.SettingsExtensions.Configure(IFlurlClient client, Action`1 action)
在 SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClient..ctor(WechatTenpayClientOptions options)
在 Crowd.buness.Mini.PayV3.PayV(String openid, String orderno, Int32 amount)
在 Crowd.web.Controllers.CashController.Transfer(Int32 id)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].


与问题相关的源代码

请在此粘贴与问题相关的代码,或提供可复现问题的最小化项目(可提供仓库地址或 GitHub Gist)。

注意,请不要以截图形式提供代码。

var manager = new InMemoryCertificateManager();
            var options = new WechatTenpayClientOptions()
            {
                MerchantId = Tool.Mchid(),  //"微信商户号",
                MerchantV3Secret = Tool.WxPayKey(),   //"微信商户 v3 API 密钥",
                MerchantCertificateSerialNumber = Tool.Serial(), //"微信商户证书序列号",
                MerchantCertificatePrivateKey = @"-----BEGIN PRIVATE KEY-----
***
-----END PRIVATE KEY-----",
                PlatformCertificateManager = manager 
            };
            var client = new WechatTenpayClient(options);
            client.Configure(config =>
            {
                JsonSerializerOptions jsonSerializerOptions = FlurlSystemTextJsonSerializer.GetDefaultSerializerOptions();
                jsonSerializerOptions.WriteIndented = true;
                config.JsonSerializer = new FlurlSystemTextJsonSerializer(jsonSerializerOptions);
            });
            List<CreateTransferBatchRequest.Types.TransferDetail> details = new List<CreateTransferBatchRequest.Types.TransferDetail>();
            CreateTransferBatchRequest.Types.TransferDetail transferDetail = new CreateTransferBatchRequest.Types.TransferDetail();
            transferDetail.OutDetailNumber = orderno;
            transferDetail.TransferAmount = amount;
            transferDetail.TransferRemark = "会员分红提现";
            transferDetail.OpenId = openid;
            //transferDetail.UserName = "";
            details.Add(transferDetail);


            //商家转账到零钱
            var req = new CreateTransferBatchRequest()
            {
                AppId = Tool.WxAppID(),
                OutBatchNumber = orderno+"001",
                BatchName = "会员分红提现",
                BatchRemark = "会员分红提现",
                TotalAmount = amount,
                TotalNumber =1 ,
                TransferDetailList = details
            };
            CreateTransferBatchResponse resp = null;
            Task.Run(async () =>
            {
                resp = await client.ExecuteCreateTransferBatchAsync(req);
            }).GetAwaiter().GetResult();
...

异常堆栈或异常原因

System.IO.FileLoadException: Could not load file or assembly 'System.Text.Json, Version=6.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
文件名:“System.Text.Json, Version=6.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51”
在 SKIT.FlurlHttpClient.FlurlSystemTextJsonSerializer..ctor()
在 SKIT.FlurlHttpClient.CommonClientBase.<.ctor>b__8_0(ClientFlurlHttpSettings flurlSettings)
在 Flurl.Http.SettingsExtensions.Configure(IFlurlClient client, Action`1 action)
在 SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClient..ctor(WechatTenpayClientOptions options)
在 Crowd.buness.Mini.PayV3.PayV(String openid, String orderno, Int32 amount)
在 Crowd.web.Controllers.CashController.Transfer(Int32 id)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].


发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统: Windows Server 2012 R2
  2. .NET 版本: .NET Framework 4.6.1
  3. 使用的模块及版本:SKIT.FlurlHttpClient.Wechat.TenpayV3 2.4.0.0
  4. 其他环境信息。

补充说明

请在此填写任何其他可以定位问题的信息。

[BUG] complaint_callback 回调事件的 XML 格式错误

public class ComplaintCallbackEvent : WechatApiEvent, WechatApiEvent.Serialization.IJsonSerializable, WechatApiEvent.Serialization.IXmlSerializable

在代码中,推送过来的投诉信息内容包含在 下

根据微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/guarantee/complaint.html ,推送过来的投诉信息内容应包含在 这个标签中

XmlSerializer 可能导致的内存泄漏问题

XmlSerializer xmlSerializer = new XmlSerializer(typeof(TEvent), new XmlRootAttribute("xml"));
之前在项目中也是类似这样的使用xml序列化, 后面发现这个东西会导致内存泄漏
可以参考一下这篇博文:
https://www.cnblogs.com/leo_wl/p/3619126.html

顺便咨询一下, 这个库怎么解析出电话号码呢, 就是用 sessionKey 和 iv 解密加密数据获取的, 有直接提供方法不, 是AESUtility.Decrypt 这个吗?

SKIT.FlurlHttpClient.Wechat.TenpayV3 .ExecuteCreatePayTransactionNativeAsync(request)报错: System.NullReferenceException HResult=0x80004003

开发环境:asp.net 4.6.1
SKIT.FlurlHttpClient.Wechat.TenpayV3: 2.9.1

异常抛出的错误信息如下:
System.NullReferenceException
HResult=0x80004003
Message=未将对象引用设置到对象的实例。
Source=mscorlib
StackTrace:
在 System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction(Object state)
在 System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task& currentTask)
--- 上一位置中堆栈跟踪的末尾 ---
在 System.Threading.Tasks.AwaitTaskContinuation.<>c.b__18_0(Object s)
在 System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
在 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
在 System.Threading.ThreadPoolWorkQueue.Dispatch()
在 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

此异常最初是在此调用堆栈中引发的:
[外部代码]
System.NullReferenceException:“未将对象引用设置到对象的实例。”

我的业务代码如下
` protected void Page_Load(object sender, EventArgs e)
{
var response = UI.Payment.Wechatpay.Get_Ewm_Response("http://localhost:6363weixinpay/Notify_url.aspx", "wx5xx", "xx", 1, "Image形象店-深圳腾大-QQ公仔");

        if (response.IsCompleted && response.Status == TaskStatus.RanToCompletion)
        {
            if (response.Result.IsSuccessful())
            {
                Response.Write(response.Result.QrcodeUrl);
            }
            else
            {
                Response.Write("HTTP 状态:" + response.Result.RawStatus);
                Response.Write("错误代码:" + response.Result.ErrorCode);
                Response.Write("错误描述:" + response.Result.ErrorMessage);
            }
        }
        else if (response.Status == TaskStatus.Faulted)
        {
            Response.Write(response.Exception.ToString());
        }

    }

    /// <summary>
    /// 获得一个微信支付Client
    /// </summary>
    /// <returns></returns>
    private static WechatTenpayClient Get_Client()
    {
        var manager = new InMemoryCertificateManager();
        var options = new WechatTenpayClientOptions()
        {
            MerchantId = "16xx",
            MerchantV3Secret = "58xxx",
            MerchantCertificateSerialNumber = "xxx",
            MerchantCertificatePrivateKey = "-----BEGIN PRIVATE KEY-----xxx-----END PRIVATE KEY-----",
            PlatformCertificateManager = manager // 证书管理器的具体用法请参阅下文的高级技巧与加密、验签有关的章节
        };
        return new WechatTenpayClient(options);
    }

    /// <summary>
    /// 获得一个支付二维码输出 Response
    /// </summary>
    /// <param name="notifyUrl"></param>
    /// <param name="AppId">AppId</param>
    /// <param name="out_trade_no">商家订单号</param>
    /// <param name="total_amount">订单金额:分</param>
    /// <param name="subject">订单标题</param>
    /// <returns>AlipayTradePagePayResponse</returns>
    public static async Task<CreatePayTransactionNativeResponse> Get_Ewm_Response(string notifyUrl, string AppId, string out_trade_no, int total_amount, string subject)
    {
        var request = new CreatePayTransactionNativeRequest()
        {
            OutTradeNumber = out_trade_no,
            AppId = AppId,
            Description = subject,
            NotifyUrl = notifyUrl,
            Amount = new CreatePayTransactionNativeRequest.Types.Amount()
            {
                Total = 1,
                Currency = "CNY"
            }
        };
       
        var response = await Get_Client().ExecuteCreatePayTransactionNativeAsync(request); 
        if (response.IsSuccessful())
        {
            //Console.WriteLine("QrcodeUrl:" + response.QrcodeUrl);
        }
        else
        {
            //Console.WriteLine("错误代码:" + response.ErrorCode);
            // Console.WriteLine("错误描述:" + response.ErrorMessage);
        }
        return response;
    }

`

调试异常代码如下:
`
public async Task SendRequestWithJsonAsync(IFlurlRequest flurlRequest, object? data = null, CancellationToken cancellationToken = default)
where T : WechatTenpayResponse, new()
{
if (flurlRequest == null) throw new ArgumentNullException(nameof(flurlRequest));

        try
        {
            bool isSimpleRequest = data == null ||
                flurlRequest.Verb == HttpMethod.Get ||
                flurlRequest.Verb == HttpMethod.Head ||
                flurlRequest.Verb == HttpMethod.Options;
            using IFlurlResponse flurlResponse = isSimpleRequest ? await base.SendRequestAsync(flurlRequest, null, cancellationToken) :                   
              await base.SendRequestWithJsonAsync(flurlRequest, data, cancellationToken);
            return await WrapResponseWithJsonAsync<T>(flurlResponse, cancellationToken);
        }
        catch (FlurlHttpException ex)
        {
            throw new WechatTenpayException(ex.Message, ex);
        }
    }

`

异常代码段: await base.SendRequestWithJsonAsync(flurlRequest, data, cancellationToken); try cahch 无法获得异常信息就直接跳出了,大家帮看下问题出在哪里,是我的配置有问题吗?还是https://api.mch.weixin.qq.com/v3/pay/transactions/native 这边的问题。在线急等!!!

[BUG] 酒店押金退款接口响应类缺失商户退款单号属性

关于问题的简单描述

酒店押金退款接口响应类 CreateDepositRefundResponse 缺失映射 out_refund_no 字段的商户退款单号属性 OutRefundNumber

参考 微信支付酒店押金申请退款文档 中的返回结果部分,可以发现,该接口应返回字段 out_refund_no,但该文档的响应示例中缺失了该字段。在实际测试调用 /deposit/refund 接口时观察响应结果,可以发现out_refund_no 字段是存在的。

实际测试调用结果(敏感信息已用星号代替):

<xml>
        <return_code><![CDATA[SUCCESS]]></return_code>
        <result_code><![CDATA[SUCCESS]]></result_code>
        <appid><![CDATA[wx1ade********]]></appid>
        <mch_id><![CDATA[15********]]></mch_id>
        <sub_mch_id><![CDATA[15********]]></sub_mch_id>
        <nonce_str><![CDATA[hiAK********]]></nonce_str>
        <sign><![CDATA[06250F************************************************]]></sign>
        <transaction_id><![CDATA[4200********************************]]></transaction_id>
        <out_refund_no><![CDATA[DEMO************************]]></out_refund_no>
        <refund_id><![CDATA[5030************************]]></refund_id>
        <refund_fee>1</refund_fee>
        <total_fee>2</total_fee>
        <fee_type><![CDATA[CNY]]></fee_type>
        <coupon_refund_fee>0</coupon_refund_fee>
</xml>

与问题相关的源代码

酒店押金退款接口响应类 SKIT.FlurlHttpClient.Wechat.TenpayV2.Models.CreateDepositRefundResponse

[BUG] 企业微信wechat_channels 异常

异常信息:

SKIT.FlurlHttpClient.Wechat.Work.WechatWorkException: Response could not be deserialized to JSON: GET https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=&department_id=1&fetch_child=1
---> Flurl.Http.FlurlParsingException: Response could not be deserialized to JSON: GET https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=****&department_id=1&fetch_child=1
---> System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $.userlist[0].external_profile.wechat_channels | LineNumber: 0 | BytePositionInLine: 481.
---> System.InvalidOperationException: Cannot get the value of a token type 'StartObject' as a string.
at System.Text.Json.Utf8JsonReader.GetString()
at System.Text.Json.Serialization.Converters.StringConverter.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.JsonPropertyInfo1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.JsonPropertyInfo1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader) at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)

查看了下微信文档
结构应该为
"wechat_channels": {
"nickname": "视频号名称",
"status": 1
},
对象

源码中为:

public class CgibinUserCreateRequest : WechatWorkRequest
///


/// 获取或设置视频号名称。
///

[Newtonsoft.Json.JsonProperty("wechat_channels")]
[System.Text.Json.Serialization.JsonPropertyName("wechat_channels")]
public string? WechatChannels { get; set; }

[FEATURE] V2 付款码支付撤掉订单接口支持微信订单号字段

关于建议的简单描述

参考 V2 付款码支付撤销订单接口文档:

https://pay.weixin.qq.com/wiki/doc/api/micropay_sl.php?chapter=9_11&index=3

该接口同时支持微信订单号 transaction_id 字段与商户订单号 out_trade_no,而目前 SKIT.FlurlHttpClient.Wechat.TenpayV2.Models.ReversePayOrderRequest 类尚未提供 TransactionId 属性。

实现思路或解决方案

为上述类提供 TransactionId 属性,调整 OutTradeNumber 属性为 string?


补充说明

虽然微信支付文档中给出 transaction_id 字段为非必填参数,而 out_trade_no 为必填参数,但描述中给出说明

transaction_id:微信的订单号,优先使用
out_trade_no:商户系统内部的订单号,transaction_id、out_trade_no二选一,如果同时存在优先级:transaction_id> out_trade_no

且经过测试,该接口实际支持只提供 transaction_id 且不提供 out_trade_no 调用接口执行订单撤销的行为,因此 TransactionIdOutTradeNumber 属性应都为 string? 类型且保留默认值为 null

微信支付V3,报错

Method not found: 'System.Threading.Tasks.Task`1<Flurl.Http.IFlurlResponse> Flurl.Http.GeneratedExtensions.SendJsonAsync(Flurl.Http.IFlurlRequest, System.Net.Http.HttpMethod, System.Object, System.Threading.CancellationToken, System.Net.Http.HttpCompletionOption)'.

[BUG] tenpay v3 2.1.2 版本jsapi下单加解密异常


关于问题的简单描述

JSAPI 下单时直接异常


与问题相关的源代码

 var payRequest = new CreatePayTransactionJsapiRequest
        {
            Amount = new CreatePayTransactionJsapiRequest.Types.Amount { Total = Amount },
            AppId = _wxApiClient.Credentials.AppId,
            Description = $"支付",
            NotifyUrl = NotifyUrl,
            Payer = new CreatePayTransactionJsapiRequest.Types.Payer { OpenId = openId },
            OutTradeNumber = $"{studentId}{DateTimeOffset.Now:yyyyMMddHHmmssfff}",
        };
        var payResponse = await _payClient.ExecuteCreatePayTransactionJsapiAsync(payRequest, cancellationToken: HttpContext.RequestAborted);

异常堆栈或异常原因

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
SKIT.FlurlHttpClient.Wechat.TenpayV3.Exceptions.WechatTenpayResponseDecryptionException: Decrypt response failed. Please see the InnerException for more details.
---> System.NotSupportedException: Collection is read-only.
at System.Collections.ObjectModel.ReadOnlyDictionary`2.System.Collections.IDictionary.set_Item(Object key, Object value)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.ReflectionUtility.InnerReplaceEachCollectionPropertyStringValue[T](T& obj, Type objType, ReplacePropertyStringValueReplacement replacement, PropertyInfo currentProp)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.ReflectionUtility.InnerReplacePropertyStringValue[T](T& obj, ReplacePropertyStringValueReplacement replacement, PropertyInfo currentProp)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.ReflectionUtility.ReplacePropertyStringValue[T](T& obj, ReplacePropertyStringValueReplacement replacement)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClientResponseDecryptionExtensions.DecryptResponseSensitiveProperty[TResponse](WechatTenpayClient client, TResponse response)
--- End of inner exception stack trace ---
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClientResponseDecryptionExtensions.DecryptResponseSensitiveProperty[TResponse](WechatTenpayClient client, TResponse response)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClient.GetResposneAsync[T](IFlurlResponse flurlResponse)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClient.SendRequestWithJsonAsync[T](IFlurlRequest flurlRequest, Object data, CancellationToken cancellationToken)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClientExecutePayTransactionsExtensions.ExecuteCreatePayTransactionJsapiAsync(WechatTenpayClient client, CreatePayTransactionJsapiRequest request, CancellationToken cancellationToken)


发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统:Win 10 pro
  2. .NET 版本:.NET 6.0
  3. 使用的模块及版本:SKIT.FlurlHttpClient.Wechat.TenpayV3 2.1.2

补充说明

SKIT.FlurlHttpClient.Wechat.TenpayV3 2.1.1 没有问题
更新至 SKIT.FlurlHttpClient.Wechat.TenpayV3 2.1.2 后报此错误。

"AutoEncryptRequestSensitiveProperty": true,
"AutoDecryptResponseSensitiveProperty": true

昨天更新到了最新版本,实现了几个常用功能,启动报以下问题是什么原因

System.Reflection.ReflectionTypeLoadException:“Unable to load one or more of the requested types.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.SnsJsCode2SessionResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.SnsOAuth2AccessTokenResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.SnsJsCode2SessionResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.SnsOAuth2AccessTokenResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinTokenResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinTicketGetTicketResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinTokenResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinTicketGetTicketResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.”

下单报错:One or more errors occurred. (Input string was not in a correct format.)

关于问题的简单描述

如题,商户号证书信息都有,但是 new CreatePayTransactionJsapiRequest的时候抛出错误
One or more errors occurred. (Input string was not in a correct format.)

与问题相关的源代码

var request = new CreatePayTransactionJsapiRequest()
            {
                OutTradeNumber = order.OrderNo,
                AppId = userLogin.AppId,
                Description = goodsNameTest,
                ExpireTime = DateTimeOffset.Now.AddMinutes(15),
                NotifyUrl = "https://example.com",
                Amount = new CreatePayTransactionJsapiRequest.Types.Amount()
                {
                    Total = int.Parse((order.PayPrice * 100).ToString())
                },
                Payer = new CreatePayTransactionJsapiRequest.Types.Payer()
                {
                    OpenId = userLogin.WxOpenId
                }
            };

发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统:win11
  2. .NET 版本:.NET Core 3.1
  3. 使用的模块及版本:skit.flurlhttpclient.wechat.tenpayv3 2.15.2版
  4. 其他环境信息。

ExecuteCreateProfitSharingOrderAsync 接口加密错误

执行ExecuteCreateProfitSharingOrderAsync接口时报错:attempt to process message to long for cipher

详细错误信息:
[10:53:06 ERR] Encrypt request failed. Please see the InnerException for more details.
SKIT.FlurlHttpClient.Wechat.TenpayV3.Exceptions.WechatTenpayRequestEncryptionException: Encrypt request failed. Please see the InnerException for more details.
---> Org.BouncyCastle.Crypto.DataLengthException: attempt to process message to long for cipher
at Org.BouncyCastle.Crypto.BufferedAsymmetricBlockCipher.ProcessBytes(Byte[] input, Int32 inOff, Int32 length) in //crypto/src/crypto/BufferedAsymmetricBlockCipher.cs:line 107
at Org.BouncyCastle.Crypto.BufferedAsymmetricBlockCipher.DoFinal(Byte[] input, Int32 inOff, Int32 length) in /
/crypto/src/crypto/BufferedAsymmetricBlockCipher.cs:line 138
at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.RSAUtility.EncryptWithECB(String publicKey, String plainText, String paddingMode)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClientRequestEncryptionExtensions.<>c__DisplayClass0_0`1.b__0(Object target, PropertyInfo currentProp, String oldValue)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.ReflectionUtility.InnerReplacePropertyStringValue[T](T& obj, ReplacePropertyStringValueReplacementHandler replacement)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.ReflectionUtility.InnerReplaceEachCollectionPropertyStringValue[T](T& obj, Type objType, ReplacePropertyStringValueReplacementHandler replacement, PropertyInfo currentProp)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.ReflectionUtility.InnerReplacePropertyStringValue[T](T& obj, ReplacePropertyStringValueReplacementHandler replacement)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClientRequestEncryptionExtensions.InnerEncryptRequestSensitivePropertyByRSA[TRequest](WechatTenpayClient client, TRequest request)
at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClientRequestEncryptionExtensions.EncryptRequestSensitiveProperty[TRequest](WechatTenpayClient client, TRequest request)
--- End of inner exception stack trace ---

发生问题的运行环境
.net 6

[BUG] 部分方法的 XML 文档解析失败

背景

根据 W3C 标准,在 XML 文档中,需要将以下五个特殊字符转义为预定义实体:

特殊字符 预定义实体
" quot
& amp
' apos
< lt
> gt

.NET API 采用 XML 文档注释,注释文本中的特殊字符需按标准进行转义,否则 IDE 可能无法正确解析文档内容生成智能提示。


问题描述

ExecuteGetPayOrderAsync 为例,当前代码版本的 XML 注释在 IDE 中的呈现效果如图:

  • JetBrains Rider

image

  • Visual Studio

image

由于代码注释中的微信支付文档引用链接中出现了 & 字符,使得 XML 注释无法正常解析。

根据标准,将 & 替换为 &amp; 进行转义修正后,XML 注释在 IDE 中的呈现效果如图:

  • JetBrains Rider

image

  • Visual Studio

image


参考资料

Extensible Markup Language (XML) 1.1 (Second Edition)
XML 文档注释 - 使用 /// 注释记录 API | Microsoft Learn

ShopRegisterCheckResponse 参数不全。

文档地址: https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/ministore/minishopopencomponent2/API/enter/enter_check.html

json:

{
	"errcode": 0,
	"data": {
		"status": 2,
		"reject_reason": "",
		"access_info": {
			"spu_audit_success": 0,
			"pay_order_success": 0,
			"send_delivery_success": 0,
			"add_aftersale_success": 0,
			"spu_audit_finished": 0,
			"pay_order_finished": 0,
			"send_delivery_finished": 0,
			"add_aftersale_finished": 0,
			"test_api_finished": 0,
			"deploy_wxa_finished": 0,
			"open_product_task_finished": 0
		},
		"scene_group_list": [{
			"name": "视频号、公众号场景",
			"status": 3,
			"group_id": 1,
			"scene_group_ext_list": [{
				"name": "绑定视频号",
				"status": 3,
				"ext_id": 1
			}, {
				"name": "添加推广员",
				"status": 3,
				"ext_id": 2
			}]
		}]
	}
}

PS: 售后相关的接口也没有。https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/ministore/minishopopencomponent2/API/aftersale/add_new.html

[BUG] 小程序订阅消息获取消息模板列表的接口请求失败,200019

关于问题的简单描述

在请求小程序订阅消息获取消息模板列表的接口的时候,会返回,请求失败200019的错误,

与问题相关的源代码

public static async Task<Models.WxaApiNewTemplateGetPublicTemplateTitlesResponse> ExecuteWxaApiNewTemplateGetPublicTemplateTitlesAsync(this WechatApiClient client, Models.WxaApiNewTemplateGetPublicTemplateTitlesRequest request, CancellationToken cancellationToken = default)
        {
            if (client is null) throw new ArgumentNullException(nameof(client));
            if (request is null) throw new ArgumentNullException(nameof(request));

            IFlurlRequest flurlReq = client
                .CreateRequest(request, HttpMethod.Get, "wxaapi", "newtmpl", "getpubtemplatetitles")
                .SetQueryParam("access_token", request.AccessToken)
                .SetQueryParam("ids", "\"" + string.Join(",", request.CategoryIdList) + "\"")
                .SetQueryParam("start", request.Offset)
                .SetQueryParam("limit", request.Limit);

            return await client.SendRequestWithJsonAsync<Models.WxaApiNewTemplateGetPublicTemplateTitlesResponse>(flurlReq, data: request, cancellationToken: cancellationToken);
        }

请求参数,

var request = new WxaApiNewTemplateGetPublicTemplateTitlesRequest
            {
                AccessToken = "",
                CategoryIdList = new List<int>(){32},
                Limit = 10,
                Offset = 1
            };

异常堆栈或异常原因

200019,invalid parameter ids

发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统:Windows 10 21H2
  2. .NET 版本:.NET 6.0
  3. 使用的模块及版本:SKIT.FlurlHttpClient.Wechat.Api 2.6.0
  4. 其他环境信息。

补充说明

似乎在请求的时候,(猜测)转义字符“”被URLencode了,导致参数[32]会变成%2232%22

[BUG] Deserialize NotifyThirdFastRegisterEvent The XML element 'legal_persona_wechat' from namespace '' is already present in the current scope


关于问题的简单描述

反序列化小程序注册事件发生异常,提示The XML element 'legal_persona_wechat' from namespace '' is already present in the current scope


与问题相关的源代码

var registerData = wxClient.DeserializeEventFromXml<NotifyThirdFastRegisterEvent>(body);

异常堆栈或异常原因

SKIT.FlurlHttpClient.Wechat.Api.Exceptions.WechatApiEventSerializationException: Deserialize event failed. Please see the `InnerException` for more details.
 ---> System.InvalidOperationException: There was an error reflecting type 'SKIT.FlurlHttpClient.Wechat.Api.Events.NotifyThirdFastRegisterEvent'.
 ---> System.InvalidOperationException: There was an error reflecting property 'InfoData'.
 ---> System.InvalidOperationException: There was an error reflecting type 'SKIT.FlurlHttpClient.Wechat.Api.Events.NotifyThirdFastRegisterEvent.Types.InfoData'.
 ---> System.InvalidOperationException: There was an error reflecting property 'IdName'.
 ---> System.InvalidOperationException: The XML element 'legal_persona_wechat' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.
   at System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(INameScope scope, Accessor accessor)
   at System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(MemberMapping member, INameScope elements, INameScope attributes, Boolean isSequence)
   at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, String ns, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter limiter)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer.GenerateXmlTypeMapping(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace, String location)
   at SKIT.FlurlHttpClient.Wechat.Api.Utilities.XmlUtility.GetTypedSerializer(Type type)
   at SKIT.FlurlHttpClient.Wechat.Api.Utilities.XmlUtility.Deserialize(Type type, String xml)
   at SKIT.FlurlHttpClient.Wechat.Api.Utilities.XmlUtility.Deserialize[T](String xml)
   at SKIT.FlurlHttpClient.Wechat.Api.WechatApiClientEventExtensions.InnerDeserializeEventFromXml[TEvent](WechatApiClient client, String callbackXml)

发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统:win11
  2. .NET 版本:net6.0
  3. 使用的模块及版本:SKIT.FlurlHttpClient.Wechat.Api 2.20.0
  4. 其他环境信息。

NetCore5.0出错

⚠⚠ 请注意:不符合格式要求的 Issue 可能会被直接关闭。


关于问题的简单描述

请在此填写你遇到的问题。
Specified argument was out of the range of valid values. (Parameter 'cancellationToken')

与问题相关的源代码

await client.ExecuteCreatePayTransactionAppAsync(request,cancellationToken)

// Source Code

异常堆栈或异常原因

请在此填写你遇到的问题抛出错误时的异常消息和堆栈跟踪(如果有的话)。


发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统:请填写发生问题的操作系统环境信息(如:Windows Server 2012 R2)
  2. .NET 版本:请填写发生问题的 .NET 环境信息(如:.NET Framework 4.7.2 / .NET 5.0)
  3. 使用的模块及版本:请填写发生问题的模块信息(如:SKIT.FlurlHttpClient.Wechat.Api 1.0.0)
  4. 其他环境信息。

补充说明

请在此填写任何其他可以定位问题的信息。

[BUG] subscribe_msg_sent_event 事件模型定义问题

⚠⚠ 请注意:不符合格式要求的 Issue 可能会被直接关闭。


关于问题的简单描述

7K`_IP(ZIZGZLRUK1ZCWPSW

JSON 的 List 外面是没有包着 SubscribeMsgSentEvent 这一层的。

来自 QQ 群反馈。


发生问题的运行环境

SKIT.FlurlHttpClient.Wechat.Api

感谢开源

骂腾讯那段文档看着很爽
还有就是,想请作者喝杯咖啡

提示无法加载序列化动态库 System.Text.Json

⚠⚠ 请注意:不符合格式要求的 Issue 可能会被直接关闭。


关于问题的简单描述
提示无法加载序列化动态库,无论是 System.Text.Json 还是 Newtonsoft.Json 都报这样的错


与问题相关的源代码

请在此粘贴与问题相关的代码,或提供可复现问题的最小化项目(可提供仓库地址或 GitHub Gist)。

注意,请不要以截图形式提供代码。

var manager = new InMemoryCertificateManager();
            var options = new WechatTenpayClientOptions()
            {
                MerchantId = Tool.Mchid(),  //"微信商户号",
                MerchantV3Secret = Tool.WxPayKey(),   //"微信商户 v3 API 密钥",
                MerchantCertificateSerialNumber = Tool.Serial(), //"微信商户证书序列号",
                MerchantCertificatePrivateKey = @"-----BEGIN PRIVATE KEY-----
***
-----END PRIVATE KEY-----",
                PlatformCertificateManager = manager 
            };
            var client = new WechatTenpayClient(options);
            client.Configure(config =>
            {
                JsonSerializerOptions jsonSerializerOptions = FlurlSystemTextJsonSerializer.GetDefaultSerializerOptions();
                jsonSerializerOptions.WriteIndented = true;
                config.JsonSerializer = new FlurlSystemTextJsonSerializer(jsonSerializerOptions);
            });
            List<CreateTransferBatchRequest.Types.TransferDetail> details = new List<CreateTransferBatchRequest.Types.TransferDetail>();
            CreateTransferBatchRequest.Types.TransferDetail transferDetail = new CreateTransferBatchRequest.Types.TransferDetail();
            transferDetail.OutDetailNumber = orderno;
            transferDetail.TransferAmount = amount;
            transferDetail.TransferRemark = "会员分红提现";
            transferDetail.OpenId = openid;
            //transferDetail.UserName = "";
            details.Add(transferDetail);


            //商家转账到零钱
            var req = new CreateTransferBatchRequest()
            {
                AppId = Tool.WxAppID(),
                OutBatchNumber = orderno+"001",
                BatchName = "会员分红提现",
                BatchRemark = "会员分红提现",
                TotalAmount = amount,
                TotalNumber =1 ,
                TransferDetailList = details
            };
            CreateTransferBatchResponse resp = null;
            Task.Run(async () =>
            {
                resp = await client.ExecuteCreateTransferBatchAsync(req);
            }).GetAwaiter().GetResult();
...

异常堆栈或异常原因

System.IO.FileLoadException: Could not load file or assembly 'System.Text.Json, Version=6.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
文件名:“System.Text.Json, Version=6.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51”
在 SKIT.FlurlHttpClient.FlurlSystemTextJsonSerializer..ctor()
在 SKIT.FlurlHttpClient.CommonClientBase.<.ctor>b__8_0(ClientFlurlHttpSettings flurlSettings)
在 Flurl.Http.SettingsExtensions.Configure(IFlurlClient client, Action`1 action)
在 SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClient..ctor(WechatTenpayClientOptions options)
在 Crowd.buness.Mini.PayV3.PayV(String openid, String orderno, Int32 amount)
在 Crowd.web.Controllers.CashController.Transfer(Int32 id)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].


发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统: Windows Server 2012 R2
  2. .NET 版本: .NET Framework 4.6.1
  3. 使用的模块及版本:SKIT.FlurlHttpClient.Wechat.TenpayV3 2.4.0.0
  4. 其他环境信息。

补充说明

请在此填写任何其他可以定位问题的信息。

SKIT.FlurlHttpClient.Wechat.TenpayV3 升级到 2.3.0 运行报错

旧的依赖

    <PackageReference Include="SKIT.FlurlHttpClient.Wechat.Api" Version="2.3.0" />
    <PackageReference Include="SKIT.FlurlHttpClient.Wechat.TenpayV3" Version="2.2.2" />

升级为

    <PackageReference Include="SKIT.FlurlHttpClient.Wechat.Api" Version="2.3.0" />
    <PackageReference Include="SKIT.FlurlHttpClient.Wechat.TenpayV3" Version="2.3.0" />

异常信息

Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinComponentApiGetAuthorizerInfoResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinComponentApiStartPushTicketResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinComponentApiGetAuthorizerInfoResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinComponentApiStartPushTicketResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeAssembly.get_DefinedTypes()
at Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart.get_Types()
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFeatureProvider.PopulateFeature(IEnumerable1 parts, ControllerFeature feature) at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature) at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetControllerTypes() at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors() at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context) at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection() at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize() at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.<>c__DisplayClass11_0.<Subscribe>b__0() at Microsoft.Extensions.Primitives.ChangeToken.OnChange(Func1 changeTokenProducer, Action changeTokenConsumer)
at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.Subscribe()
at Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource..ctor(ControllerActionEndpointDataSourceIdProvider dataSourceIdProvider, IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory, OrderedEndpointsSequenceProvider orderSequence)
at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.GetOrCreateDataSource(IEndpointRouteBuilder endpoints)
at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllers(IEndpointRouteBuilder endpoints)
at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.b__1(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
System.TypeLoadException: Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinComponentApiGetAuthorizerInfoResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
System.TypeLoadException: Method 'set_RawStatus' in type 'SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinComponentApiStartPushTicketResponse' from assembly 'SKIT.FlurlHttpClient.Wechat.Api, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

建议CertificateManager增加异步方法

⚠⚠ 请注意:不符合格式要求的 Issue 可能会被直接关闭。


关于建议的简单描述

请教一下 这个抽象类public abstract class CertificateManager 是否能增加异步方法?
因为很多场景需要使用异步,自己实现这个类的时候也更灵活。


实现思路或解决方案

/// <summary>
/// 微信商户平台证书管理器接口。
/// </summary>
public abstract class CertificateManager
{
    /// <summary>
    /// 获取存储的全部证书。
    /// </summary>
    /// <returns></returns>
    public abstract IEnumerable<CertificateEntry> AllEntries();

    /// <summary>
    /// 添加一个证书实体。
    /// </summary>
    /// <param name="entry"></param>
    public abstract void AddEntry(CertificateEntry entry);

    /// <summary>
    /// 根据证书序列号获取证书实体。
    /// </summary>
    /// <param name="serialNumber"></param>
    /// <returns></returns>
    public abstract CertificateEntry? GetEntry(string serialNumber);

    // 异步获取证书
    public abstract Task<CertificateEntry?> GetEntryAsync(string serialNumber);

    /// <summary>
    /// 移除指定的证书实体。
    /// </summary>
    /// <param name="serialNumber"></param>
    /// <returns></returns>
    public abstract bool RemoveEntry(string serialNumber);
}

补充说明

请在此填写任何其他可以帮助说明的信息。

[BUG] V2 付款码接口响应类存在风格不一致的命名

关于问题的简单描述

商户退款单号字段在整个仓库中都被命名为 OutRefundNumber,而在 SKIT.FlurlHttpClient.Wechat.TenpayV2.Models.GetPayRefundResponse.Types.Refund 中的 商户退款单号 被命名为 OutRefundId,建议在下一次允许破坏性变更的版本中调整命名为统一的名称 OutRefundNumber


与问题相关的源代码

SKIT.FlurlHttpClient.Wechat.TenpayV2.Models.GetPayRefundResponse.Types.Refund.OutRefundId

解密微信支付回调报错

回调数据

{"id":"988bc17f-f0e4-50cd-a5b3-d5d18689d227","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource_type":"encrypt-resource","resource":{"algorithm":"AEAD_AES_256_GCM","original_type":"transaction","associated_data":"transaction","nonce":"pJzPEVj3TKtN","ciphertext":"P7D9wIf8UwkiTK7ZtaWXt9cNoD3ETw8hOBXmAVcPl79yOAHwDWTRKE8HGwYjZv02r+fBKci+9zh0xXZuM6AHj9Jg7vqLJjgleTNKU1F4MYrKyDA+TBaNETCde5Ngv2r8qM16u3mQruf6Ne0OeysgmZhVbghmQI4AyDgXLa9HcAp96eedL1bgUOIyHPHdnpNgxWkbHKX4z0r7P9MYEyKPhZsE8Ksqw0cUvgohlO46Lc7n8d8MEcx67ZBxIxyWjBdOGygLVYOx45Fut45T1CqwSp0Tb3Q+P5wD76sa18xw7K5pI77zWgiBlq9M/2ntr3z1YElkkiopaxjAhqK/1N7bfWBYMfiws0Z/GpjUofeVp9GAvOODhG2dvZF7wRYiaLZqWjOIwBE+O1quQX1NoVolfuLhAAnkGP+UN6VQvv63SHbc1J+H/DB0NRiJALXVIJmvvFyBgkvf6/AptcXM3ALw7BI1gIXbwxJUztShFiYzNLw4zzw7CrME8b0m0KsL9PsiS0a0cGlou5KYooZwZUXwAwQtCLU95uF68Fahmy4mj0pzdOuepKC8gC73CYCt6ZHpx4g/eBg="},"create_time":"2023-02-12T01:20:49+08:00"}

错误信息
SKIT.FlurlHttpClient.Wechat.TenpayV3.Exceptions.WechatTenpayEventDecryptionException: Decrypt event resource failed. Please see the InnerException for more details.
0|YunYiMp | ---> Org.BouncyCastle.Crypto.InvalidCipherTextException: mac check in GCM failed
0|YunYiMp | at Org.BouncyCastle.Crypto.Modes.GcmBlockCipher.DoFinal(Span`1 output) in C:\Users\Peter\code\bc-csharp-release\crypto\src\crypto\modes\GCMBlockCipher.cs:line 846
0|YunYiMp | at Org.BouncyCastle.Crypto.Modes.GcmBlockCipher.DoFinal(Byte[] output, Int32 outOff) in C:\Users\Peter\code\bc-csharp-release\crypto\src\crypto\modes\GCMBlockCipher.cs:line 632
0|YunYiMp | at Org.BouncyCastle.Crypto.BufferedAeadBlockCipher.DoFinal(Byte[] output, Int32 outOff) in C:\Users\Peter\code\bc-csharp-release\crypto\src\crypto\BufferedAeadBlockCipher.cs:line 246
0|YunYiMp | at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.AESUtility.DecryptWithGCM(Byte[] keyBytes, Byte[] nonceBytes, Byte[] aadBytes, Byte[] cipherBytes, String paddingMode)
0|YunYiMp | at SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities.AESUtility.DecryptWithGCM(String key, String nonce, String aad, String cipherText, String paddingMode)
0|YunYiMp | at SKIT.FlurlHttpClient.Wechat.TenpayV3.WechatTenpayClientEventDecryptionExtensions.DecryptEventResource[T](WechatTenpayClient client, Resource resource)
0|YunYiMp | --- End of inner exception stack trace ---

[BUG] 智能对话接口过时


智能对话文档(签名、智能对话)

关于智能对话的接口,仓库中的实现有如下几个问题:

  1. SignRequestAIBotRequest根据目前的文档,不需要加密。目前代码里实现了WechatOpenAIPlatformRequest.Serialization.IEncryptedXmlable接口,导致这两个接口进行了加密,从而请求失败。
  2. AIBotResponse结构已更新,无需data包裹。

与问题相关的源代码

public class TestCase_AIBotTests
{
    [Fact(DisplayName = "测试用例:智能对话")]
    public async void TestSendMessage()
    {
        var client = new TestClients();

        var signRequest = new SignRequest()
        {
            UserId = "test"
        };
        var signResponse = await TestClients.InstanceForPlatform.ExecuteSignAsync(signRequest);


        var request = new AIBotRequest()
        {
            Signature = signResponse.Signature,
            QueryString = "你说啥",
            Timeout = 36000
        };

        var response = await TestClients.InstanceForPlatform.ExecuteAIBotAsync(request);
        var str = Encoding.UTF8.GetString(response.RawBytes);
        Console.WriteLine(response);
    }
}

异常堆栈或异常原因

System.InvalidOperationException: There was an error generating the XML document.

System.InvalidOperationException
There was an error generating the XML document.
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces)
   at SKIT.FlurlHttpClient.Wechat.OpenAI.Utilities.XmlUtility.Serialize(Type type, Object obj) in C:\Users\dell\RiderProjects\DotNetCore.SKIT.FlurlHttpClient.Wechat\src\SKIT.FlurlHttpClient.Wechat.OpenAI\Utilities\Internal\XmlUtility.cs:line 48
   at SKIT.FlurlHttpClient.Wechat.OpenAI.Utilities.XmlUtility.Serialize[T](T obj) in C:\Users\dell\RiderProjects\DotNetCore.SKIT.FlurlHttpClient.Wechat\src\SKIT.FlurlHttpClient.Wechat.OpenAI\Utilities\Internal\XmlUtility.cs:line 60
   at SKIT.FlurlHttpClient.Wechat.OpenAI.WechatOpenAIPlatformClient.SendRequestWithJsonAsync[T](IFlurlRequest flurlRequest, Object data, CancellationToken cancellationToken) in C:\Users\dell\RiderProjects\DotNetCore.SKIT.FlurlHttpClient.Wechat\src\SKIT.FlurlHttpClient.Wechat.OpenAI\WechatOpenAIPlatformClient.cs:line 105
   at SKIT.FlurlHttpClient.Wechat.OpenAI.WechatOpenAIPlatformClientExecuteQueryExtensions.ExecuteSignAsync(WechatOpenAIPlatformClient client, SignRequest request, CancellationToken cancellationToken) in C:\Users\dell\RiderProjects\DotNetCore.SKIT.FlurlHttpClient.Wechat\src\SKIT.FlurlHttpClient.Wechat.OpenAI\Extensions\Platform\WechatOpenAIPlatformClientExecuteQueryExtensions.cs:line 27
   at SKIT.FlurlHttpClient.Wechat.OpenAI.UnitTests.TestCase_AIBotTests.TestSendMessage() in C:\Users\dell\RiderProjects\DotNetCore.SKIT.FlurlHttpClient.Wechat\test\SKIT.FlurlHttpClient.Wechat.OpenAI.UnitTests\TestCase_AIBotTests.cs:line 20
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_0(Object state)
   at Xunit.Sdk.AsyncTestSyncContext.<>c__DisplayClass7_0.<Post>b__0() in C:\Dev\xunit\xunit\src\xunit.execution\Sdk\AsyncTestSyncContext.cs:line 58

System.InvalidOperationException
The type SKIT.FlurlHttpClient.Wechat.OpenAI.Models.Platform.SignRequest was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
   at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write2_xml(Object o)

发生问题的运行环境

请在此填写以下几项内容:

  1. 操作系统:Windows 11
  2. .NET 版本:.NET 6
  3. 使用的模块及版本:SKIT.FlurlHttpClient.Wechat.OpenAI 2.0.0-rc7

补充说明

微信支付用户投诉回调,验证签名失败

如题

微信支付用户投诉回调开发者,验证签名失败


与问题相关的源代码

//回调接口
 [HttpPost("{id}")]
  public async Task<IActionResult> Complaints([FromRoute(Name = "id")] string mchId,
      [FromHeader(Name = "Wechatpay-Timestamp")] string timestamp,
      [FromHeader(Name = "Wechatpay-Nonce")] string nonce,
      [FromHeader(Name = "Wechatpay-Signature")] string signature,
      [FromHeader(Name = "Wechatpay-Serial")] string serialNumber)
  {
      using var reader = new StreamReader(Request.Body, Encoding.UTF8);
      string content = await reader.ReadToEndAsync();
      _logger.LogDebug($"Complaints merchantId:{mchId} timestamp:{timestamp} nonce:{nonce} signature:{signature} serialNumber:{serialNumber} content:{content}");

      var client = WeChartFlurlHttpClientFactory.CreateByMchId(mchId);
      bool valid = client.VerifyEventSignature(
          callbackTimestamp: timestamp,
          callbackNonce: nonce,
          callbackBody: content,
          callbackSignature: signature,
          callbackSerialNumber: serialNumber
      );

      _logger.LogDebug($"Complaints valid:{valid}");

      //测试
      return StatusCode(500);
  }

对应输出
2021-10-27 17:53:01,907 [23] DEBUG Complaints merchantId:1609546997 timestamp:1635328462 nonce:0isH6AcYy3jDk1TF9vMj09E1kFqfCKOF signature:UsEwyvCLgDRbZvFccyjYNhWArdQ0ewxVkSw5U81ILI5hYfqD22hXTR6qTnoRX5qczkEFRfC1memDbwEk37u4Y5YFvJczIVYh51eManRPlVJsZ2WLgryYbPauG/Cvbkb9A4WY9K3s626ikrienYp/niV+kkLhXLgkmwml87QxbVysN4wyqSDSph/dRaRLlJOBROtHNaPTTjWHhqC8zEsEs6zZCQ98R1nYHsLPfIVxdiOWlwYIQJLlCwfZUotvcIGjlDI4hiPauJc6/u34AXHfrQsR9FvqWHfY8mrNtP2GozClkR77e99/CYJ4F8GXBeLNs46+hCZ5tubz9Bbdaw8btg== serialNumber:5C01B08BD652B338CE771799B2190134B2DD4E51 content:{"id":"bb9d7373-3439-5219-8349-a6bf8fd587e5","create_time":"2021-10-27T16:17:46+08:00","resource_type":"encrypt-resource","event_type":"COMPLAINT.STATE_CHANGE","summary":"投诉状态变更","resource":{"original_type":"complaint","algorithm":"AEAD_AES_256_GCM","ciphertext":"T+Gn3a6xozZ5hgSQwziEl2x8gukWtTrdyePUid75v4Mf5o5Nj/vMqCgh2wKbJgciZb8DN+FEIToZFnkpqFFLhFHGZ+mpoTpFmwVOLun/7Xb5YhMbBk85FsBS3LHUmCVqssvYmpoVcvV5WUB/8xEiANK2LiIh4y8OeE8fl0m3uGfnvVmu6WexAbQRHUh6bgF2IIL22rS3CDFvgo11lZ1sgt0bE7Bw7mG4YMP8G5xBe9GYf9JyjDeULtds9Sg/K/3eMuYqwGIGSlhfipHfpot+wKAYW8LApK+cQDKuK5h6B00Pl2C66H6kQRta4NWQDkK0no0jxon0KgAposBm8mPkmeCbIgiYzh45C4bqz4DPMIeo5rii0ILSEq8PpEq2lxBOv1iNzomKZGAWOmieFsHJeeQUahjuMWNlNRh25cPLVrXBa74EVDVcu9BrTW+Zp3Mo3tvNdwvHpBYbjO0rdg5v1jKmMgRm+MBNSWJ9oS6B45GT8j7JJza+/ddJgl948e0apJ2Qu4+py19M3FD48EC/CMbKqyfN","associated_data":"complaint","nonce":"yIjtdEvxXJnk"}}

2021-10-27 17:53:01,921 [23] DEBUG Complaints valid:False


发生问题的运行环境

请在此填写以下几项内容:

  1. 项目.net core 2.2
  2. .NET 版本:Microsoft.NETCore.App 2.2.8
  3. Linux s-119 3.10.0-1160.31.1.el7.x86_64

补充说明

client.Credentials 对应的证书信息是正确的

打扰了~

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.