[HttpGet] public async Task<IActionResult> PayBack() { var code = Request.Query["code"]; var state = Request.Query["state"]; OAuthToken tokenModel = new OAuthToken(); //通过code换取token if (!string.IsNullOrEmpty(code)) { _logger.LogWarning("授权成功"); ViewBag.Code = code; tokenModel = OauthApi.GetAuthToken(code, wechatAppId); } var request = new WeChatPayUnifiedOrderRequest { Body = "微信公众号支付测试", OutTradeNo = DateTime.Now.ToString("yyyyMMddHHmmssfff"), TotalFee = 1,//分 单位 SpbillCreateIp = "127.0.0.1", NotifyUrl = "http://pay.one.com/notify/wechatpay/unifiedorder", TradeType = "JSAPI", OpenId = tokenModel.Openid //此处需进行授权 获取OpenId }; var response = await _client.ExecuteAsync(request); _logger.LogWarning($"统一下单接口返回:{response.ReturnCode}"); if (response.ReturnCode == "SUCCESS" && response.ResultCode == "SUCCESS") { var req = new WeChatPayH5CallPaymentRequest { Package = "prepay_id=" + response.PrepayId }; var parameter = await _client.ExecuteAsync(req); // 将参数(parameter)给 公众号前端 让他在微信内H5调起支付(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6) ViewData["parameter"] = JsonConvert.SerializeObject(parameter); _logger.LogWarning($"统一下单成功,即将调起微信支付:{ViewData["parameter"].ToString()}"); ViewData["response"] = response.Body; return View(); } ViewData["response"] = response.Body; return View(); }
其中:OAuthToken是网页授权 返回的实体:
/// 获取网页授权token时,返回的实体 /// </summary> public class OAuthToken : BaseRes { /// <summary> /// 网页授权接口调用凭证。注意:此access_token与基础支持的access_token不同 /// </summary> [JsonProperty("access_token")] public string AccessToken { get; set; } private int _expiresIn; /// <summary> /// access_token接口调用凭证超时时间,单位(秒) /// </summary> [JsonProperty("expires_in")] public int ExpiresIn { get { return _expiresIn; } set { ExpiresTime = DateTime.Now.AddSeconds(value); _expiresIn = value; } } /// <summary> /// 用于刷新access_token /// </summary> [JsonProperty("refresh_token")] public string RefreshToken { get; set; } /// <summary> /// 用户唯一标识。请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的openid /// </summary> [JsonProperty("openid")] public string Openid { get; set; } /// <summary> /// 用户授权的作用域,使用逗号(,)分隔 /// </summary> [JsonProperty("scope")] public string Scope { get; set; } [JsonProperty("expires_time")] public DateTime ExpiresTime { get; set; } /// <summary> /// 只有在用户将公众号绑定到微信开放平台账号后,才会出现该字段 /// </summary> [JsonProperty("unionid")] public string Unionid { get; set; } }
最后 贴一下支付成功后的回调函数: